Cat-Dog-Classifier / cat_dog.py
dhvanit2026's picture
Upload 3 files
bd0749b verified
Raw
History Blame Contribute Delete
2.99 kB
# cat_dog_classifier.py
# Import necessary libraries
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
import os
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report,mean_absolute_error,mean_squared_error,r2_score,ConfusionMatrixDisplay
from sklearn.neural_network import MLPClassifier
# Suppress TensorFlow warnings (optional)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# Set image parameters
img_width, img_height = 150, 150
batch_size = 32
epochs = 3 # Change to more epochs for better accuracy 1edit by me
# Path to your dataset
# The folder should have subfolders: 'cats' and 'dogs' with images inside each
train_data_dir = 'dataset/train'
validation_data_dir = 'dataset/validation'
# Image data generators for preprocessing
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
val_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary'
)
validation_generator = val_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary'
)
# Build a simple CNN model
model = Sequential([
Conv2D(32, (3,3), activation='relu', input_shape=(img_width, img_height, 3)),
MaxPooling2D(2,2),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D(2,2),
Conv2D(128, (3,3), activation='relu'),
MaxPooling2D(2,2),
Flatten(),
Dense(512, activation='relu'),
Dropout(0.5),
Dense(1, activation='sigmoid') # Binary classification
])
# Compile the model
model.MLPClassifier(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
# Train the model
model.fit(
train_generator,
steps_per_epoch=train_generator.samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=validation_generator.samples // batch_size
)
# Save the model
model.save('cat_dog_model.h5')
print("Model saved as cat_dog_model.h5")
# Example: predict a new image
from tensorflow.keras.preprocessing import image
import numpy as np
def predict_image(img_path):
img = image.load_img(img_path, target_size=(img_width, img_height))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0
prediction = model.predict(img_array)
if prediction[0][0] > 0.5:
print(f"{img_path} is a Dog")
else:
print(f"{img_path} is a Cat")
# Test with a new image
predict_image('dataset/test/cat_g1.jpg')