0% found this document useful (0 votes)
36 views3 pages

Cat and Dog Image Classifier Source Code

Uploaded by

Sandeep Rout
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views3 pages

Cat and Dog Image Classifier Source Code

Uploaded by

Sandeep Rout
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

CAT AND DOG IMAGE CLASSIFIER

SOURCE CODE
import numpy as np

import matplotlib.pyplot as plt

from tensorflow.keras.preprocessing.image import ImageDataGenerator

from tensorflow.keras.models import Sequential

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense

from tensorflow.keras.optimizers import Adam

# Set the path to the directory containing the training and testing datasets

train_dir = 'train_dir'

test_dir = 'test_dir'

# Set parameters

batch_size = 32

epochs = 20

image_size = (150, 150)

# Data augmentation and normalization for training

train_datagen = ImageDataGenerator(

rescale=1./255,

shear_range=0.2,

zoom_range=0.2,

horizontal_flip=True)

train_generator = train_datagen.flow_from_directory(

train_dir,

target_size=image_size,

batch_size=batch_size,
class_mode='binary')

# Data normalization for testing

test_datagen = ImageDataGenerator(rescale=1./255)

test_generator = test_datagen.flow_from_directory(

test_dir,

target_size=image_size,

batch_size=batch_size,

class_mode='binary')

# Build the CNN model

model = Sequential([

Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),

MaxPooling2D((2, 2)),

Conv2D(64, (3, 3), activation='relu'),

MaxPooling2D((2, 2)),

Conv2D(128, (3, 3), activation='relu'),

MaxPooling2D((2, 2)),

Conv2D(128, (3, 3), activation='relu'),

MaxPooling2D((2, 2)),

Flatten(),

Dense(512, activation='relu'),

Dense(1, activation='sigmoid')

])

# Compile the model

model.compile(optimizer=Adam(learning_rate=0.0001),

loss='binary_crossentropy',

metrics=['accuracy'])
# Train the model

history = model.fit(

train_generator,

steps_per_epoch=train_generator.samples // batch_size,

epochs=epochs,

validation_data=test_generator,

validation_steps=test_generator.samples // batch_size)

# Plot training and validation accuracy

plt.plot(history.history['accuracy'], label='Training Accuracy')

plt.plot(history.history['val_accuracy'], label='Validation Accuracy')

plt.xlabel('Epoch')

plt.ylabel('Accuracy')

plt.legend()

plt.show()

You might also like