0% found this document useful (0 votes)
4 views

CNN Program

Machine learning

Uploaded by

divyansh7010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CNN Program

Machine learning

Uploaded by

divyansh7010
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

CNN Program

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten,
Dense, Dropout
from tensorflow.keras.preprocessing.image import ImageDataGenerator

import numpy as np
import matplotlib.pyplot as plt
import cv2

# Load and preprocess the CIFAR-10 dataset, selecting only dog and cat
classes
(x_train, y_train), (x_test, y_test) =
tf.keras.datasets.cifar10.load_data()

class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer',


'dog', 'frog', 'horse', 'ship', 'truck']
index_dog = class_names.index('dog')
index_cat = class_names.index('cat')

# Fix: Flatten y_train before creating the boolean index


y_train = y_train.flatten()
y_test = y_test.flatten()

x_train = x_train[(y_train == index_dog) | (y_train == index_cat)]


y_train = y_train[(y_train == index_dog) | (y_train == index_cat)]

x_test = x_test[(y_test == index_dog) | (y_test == index_cat)]


y_test = y_test[(y_test == index_dog) | (y_test == index_cat)]

# Normalize pixel values to the range [0, 1]


x_train = x_train / 255.0
x_test = x_test / 255.0

# Build the CNN model


model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(64, activation='relu'),
Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])

# Train the model


history = model.fit(x_train, y_train, epochs=10,
validation_data=(x_test, y_test))

# Evaluate the model


test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
print('\nTest accuracy:', test_acc)

# Function to predict the class of a single image


def predict_image(image_path):
img = cv2.imread(image_path)
img = cv2.resize(img, (32, 32))
img = img / 255.0
img = np.expand_dims(img, axis=0)

prediction = model.predict(img)

if prediction[0][0] > 0.5:


print('Predicted: Dog')
else:
print('Predicted: Cat')

# Example usage:
image_path = '/content/ket.jpg'
predict_image(image_path)
Output:

You might also like