3. CNN - changing the Hyperparameters
AIM:
Description:
Program:
# Convolutional Neural Network
# Installing Theano
# pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
# Installing Tensorflow
# Install Tensorflow from the website: https://www.tensorflow.org/versions/r0.12/get_started/os_setup.html
# Installing Keras
# pip install --upgrade keras
# Part 1 - Building the CNN
# Importing the Keras libraries and packages
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu'))
# Step 2 - Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Adding a second convolutional layer
classifier.add(Convolution2D(32, 3, 3, activation = 'relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2)))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units = 128, activation = 'relu'))
classifier.add(Dense(units = 1, activation = 'sigmoid'))
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])
# Part 2 - Fitting the CNN to the images
from keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale = 1./255,
shear_range = 0.2,
zoom_range = 0.2,
horizontal_flip = True)
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/1_training_set',
target_size = (64, 64),
batch_size = 40,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/1_test_set',
target_size = (64, 64),
batch_size = 8,
class_mode = 'binary')
classifier.fit(training_set,
steps_per_epoch = 10,
epochs = 20,
validation_data = test_set,
validation_steps = 10)
import numpy as np
from tensorflow.keras.preprocessing import image
# Load the trained model
# Assuming you have already trained and saved the model as 'classifier'
model = classifier
# Load the image you want to classify
image_path = '/content/drive/MyDrive/1_predict/dog2.jpg' # Replace with the actual path of your image
img = image.load_img(image_path, target_size=(64, 64))
# Preprocess the image
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array /= 255.0 # Rescale to match the normalization done during training
# Make predictions on the image
predictions = model.predict(img_array)
#predicted_class = np.argmax(predictions)
print("Predictions:", predictions)
predicted_class = np.round(predictions)
# Print the predicted class label
print("Predicted class label:", predicted_class)
if(predicted_class==0):
print('cat')
else: print('dog')
3.B: Updated one
******************************************************************************
**************************************************
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Flatten, Dense, Dropout
#from keras.preprocessing.image import ImageDataGenerator
#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
from tensorflow.keras.preprocessing import image
# Initialising the CNN
classifier = Sequential()
# Step 1 - Convolution
classifier.add(Convolution2D(32, (3, 3), padding='same', activation='relu', input_shape=(64, 64, 3)))
classifier.add(Convolution2D(32, (3, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.25))
# Adding more convolutional layers
classifier.add(Convolution2D(64, (3, 3), padding='same', activation='relu'))
classifier.add(Convolution2D(64, (3, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.25))
# Adding a third convolutional block
classifier.add(Convolution2D(128, (3, 3), padding='same', activation='relu'))
classifier.add(Convolution2D(128, (3, 3), activation='relu'))
classifier.add(MaxPooling2D(pool_size=(2, 2)))
classifier.add(Dropout(0.5))
# Step 3 - Flattening
classifier.add(Flatten())
# Step 4 - Full connection
classifier.add(Dense(units=512, activation='relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(units=1, activation='sigmoid'))
# Compiling the CNN
classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
rotation_range=20, # Add rotation
width_shift_range=0.2, # Add width shift
height_shift_range=0.2 # Add height shift
)
# Part 2 - Fitting the CNN to the images
test_datagen = ImageDataGenerator(rescale = 1./255)
training_set = train_datagen.flow_from_directory('/content/drive/MyDrive/1_training_set',
target_size = (64, 64),
batch_size = 20,
class_mode = 'binary')
test_set = test_datagen.flow_from_directory('/content/drive/MyDrive/1_test_set',
target_size = (64, 64),
batch_size = 4,
class_mode = 'binary')
classifier.fit(training_set,
steps_per_epoch = 20,
epochs = 25,
validation_data = test_set,
validation_steps = 10)
from tensorflow.keras.preprocessing import image
# Load the trained model
model = classifier
# Load the image you want to classify
image_path = '/content/drive/MyDrive/1_predict/cat2.jpg'
img = image.load_img(image_path, target_size=(64, 64))
# Preprocess the image
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array /= 255.0 # Rescale to match the normalization done during training
# Make predictions on the image
predictions = model.predict(img_array)
print("predictions", predictions)
# Convert predictions to binary
predicted_class = np.round(predictions).astype(int)
# Print the predicted class label
if predicted_class == 0:
print('cat')
else:
print('dog')
Comments
Post a Comment