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

CNN Program

Machine learning

Uploaded by

divyansh7010
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)
5 views3 pages

CNN Program

Machine learning

Uploaded by

divyansh7010
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

CNN Program

import tensorflow as tf
from [Link] import Sequential
from [Link] import Conv2D, MaxPooling2D, Flatten,
Dense, Dropout
from [Link] import ImageDataGenerator

import numpy as np
import [Link] 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) =
[Link].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')
])

[Link](optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])

# Train the model


history = [Link](x_train, y_train, epochs=10,
validation_data=(x_test, y_test))

# Evaluate the model


test_loss, test_acc = [Link](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 = [Link](image_path)
img = [Link](img, (32, 32))
img = img / 255.0
img = np.expand_dims(img, axis=0)

prediction = [Link](img)

if prediction[0][0] > 0.5:


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

# Example usage:
image_path = '/content/[Link]'
predict_image(image_path)
Output:

You might also like