|
|
|
|
|
|
| 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
|
|
|
| os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
|
|
|
|
| img_width, img_height = 150, 150
|
| batch_size = 32
|
| epochs = 3
|
|
|
|
|
|
|
| train_data_dir = 'dataset/train'
|
| validation_data_dir = 'dataset/validation'
|
|
|
|
|
| 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'
|
| )
|
|
|
|
|
| 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')
|
| ])
|
|
|
|
|
| model.MLPClassifier(loss='binary_crossentropy',
|
| optimizer='adam',
|
| metrics=['accuracy'])
|
|
|
|
|
| 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
|
| )
|
|
|
|
|
| model.save('cat_dog_model.h5')
|
| print("Model saved as cat_dog_model.h5")
|
|
|
|
|
| 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")
|
|
|
|
|
| predict_image('dataset/test/cat_g1.jpg')
|
|
|