1..Build a Convolution Neural Network for Image Recognition.

For Jupyter (on local machine) 


# 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('C:\\Somasundar\\DEEP LEARNING\\1\\dataset\\training_set1',

                                                 target_size = (64, 64),

                                                 batch_size = 20,

                                                 class_mode = 'binary')


test_set = test_datagen.flow_from_directory('C:\\Somasundar\\DEEP LEARNING\\1\\dataset\\test_set1',

                                            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)


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 = 'C:\\Somasundar\\DEEP LEARNING\\1\\dataset\\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 the predicted class label

print("Predictions:", predictions)


print("Predicted class label:", predicted_class)



Output:


Found 416 images belonging to 2 classes.
Found 42 images belonging to 2 classes.
Epoch 1/25
20/20 [==============================] - 2s 76ms/step - loss: 0.6966 - accuracy: 0.4773 - val_loss: 0.6918 - val_accuracy: 0.5000
Epoch 2/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6939 - accuracy: 0.4975 - val_loss: 0.6918 - val_accuracy: 0.5500
Epoch 3/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6929 - accuracy: 0.5025 - val_loss: 0.6926 - val_accuracy: 0.5000
Epoch 4/25
20/20 [==============================] - 1s 66ms/step - loss: 0.6923 - accuracy: 0.5404 - val_loss: 0.6893 - val_accuracy: 0.6000
Epoch 5/25
20/20 [==============================] - 1s 68ms/step - loss: 0.6924 - accuracy: 0.5025 - val_loss: 0.6873 - val_accuracy: 0.5000
Epoch 6/25
20/20 [==============================] - 1s 68ms/step - loss: 0.6882 - accuracy: 0.5455 - val_loss: 0.6871 - val_accuracy: 0.5750
Epoch 7/25
20/20 [==============================] - 1s 68ms/step - loss: 0.6846 - accuracy: 0.5783 - val_loss: 0.6952 - val_accuracy: 0.5000
Epoch 8/25
20/20 [==============================] - 1s 68ms/step - loss: 0.6939 - accuracy: 0.4949 - val_loss: 0.6892 - val_accuracy: 0.5750
Epoch 9/25
20/20 [==============================] - 1s 70ms/step - loss: 0.6870 - accuracy: 0.5126 - val_loss: 0.6841 - val_accuracy: 0.5000
Epoch 10/25
20/20 [==============================] - 1s 66ms/step - loss: 0.6780 - accuracy: 0.6338 - val_loss: 0.6839 - val_accuracy: 0.5000
Epoch 11/25
20/20 [==============================] - 1s 69ms/step - loss: 0.6711 - accuracy: 0.5758 - val_loss: 0.6723 - val_accuracy: 0.5250
Epoch 12/25
20/20 [==============================] - 1s 71ms/step - loss: 0.6824 - accuracy: 0.5328 - val_loss: 0.6837 - val_accuracy: 0.5750
Epoch 13/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6565 - accuracy: 0.6465 - val_loss: 0.6842 - val_accuracy: 0.5500
Epoch 14/25
20/20 [==============================] - 1s 66ms/step - loss: 0.6570 - accuracy: 0.6364 - val_loss: 0.6631 - val_accuracy: 0.6000
Epoch 15/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6946 - accuracy: 0.5354 - val_loss: 0.6970 - val_accuracy: 0.5000
Epoch 16/25
20/20 [==============================] - 1s 66ms/step - loss: 0.6706 - accuracy: 0.5884 - val_loss: 0.6792 - val_accuracy: 0.6750
Epoch 17/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6510 - accuracy: 0.6364 - val_loss: 0.7157 - val_accuracy: 0.5250
Epoch 18/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6542 - accuracy: 0.6237 - val_loss: 0.6888 - val_accuracy: 0.5750
Epoch 19/25
20/20 [==============================] - 1s 66ms/step - loss: 0.6458 - accuracy: 0.6212 - val_loss: 0.6971 - val_accuracy: 0.5500
Epoch 20/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6330 - accuracy: 0.6667 - val_loss: 0.7260 - val_accuracy: 0.5250
Epoch 21/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6399 - accuracy: 0.6313 - val_loss: 0.7164 - val_accuracy: 0.5250
Epoch 22/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6067 - accuracy: 0.7075 - val_loss: 0.6905 - val_accuracy: 0.6000
Epoch 23/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6100 - accuracy: 0.6869 - val_loss: 0.6902 - val_accuracy: 0.6500
Epoch 24/25
20/20 [==============================] - 1s 67ms/step - loss: 0.6401 - accuracy: 0.6425 - val_loss: 0.6916 - val_accuracy: 0.6000
Epoch 25/25
20/20 [==============================] - 1s 66ms/step - loss: 0.6296 - accuracy: 0.6591 - val_loss: 0.6774 - val_accuracy: 0.6250
WARNING:tensorflow:6 out of the last 6 calls to <function Model.make_predict_function.<locals>.predict_function at 0x000002601105D040> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorflow.org/guide/function#controlling_retracing and https://www.tensorflow.org/api_docs/python/tf/function for  more details.
1/1 [==============================] - 0s 113ms/step
Predictions: [[0.7894876]]
Predicted class label: 0

Links to Drive: (for Image Data)

https://drive.google.com/drive/folders/1shudwqEQnWl2RAFMo-Wu_nz59HD9Qs-U?usp=sharing

https://drive.google.com/drive/folders/1TxwerNZPte_EA_NXW3OgfxV9OORK4Hxa?usp=sharing

https://drive.google.com/drive/folders/1Dp9wcbo9qlsK3d_FvHcoNOUxKtGHkUIZ?usp=sharing

PPT:

https://docs.google.com/presentation/d/16_ukpSwjsbxDX0qBvOGRwk3pGe3WZabi/edit?usp=sharing&ouid=111226229820470175864&rtpof=true&sd=true

For Colab:


# 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 = 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)



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')




1.B



Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
Found 416 images belonging to 2 classes.
Found 42 images belonging to 2 classes.
Epoch 1/25
20/20 [==============================] - 3s 110ms/step - loss: 0.6977 - accuracy: 0.4798 - val_loss: 0.6944 - val_accuracy: 0.4750
Epoch 2/25
20/20 [==============================] - 3s 173ms/step - loss: 0.6926 - accuracy: 0.5177 - val_loss: 0.6924 - val_accuracy: 0.5250
Epoch 3/25
20/20 [==============================] - 2s 111ms/step - loss: 0.6921 - accuracy: 0.5051 - val_loss: 0.6921 - val_accuracy: 0.6250
Epoch 4/25
20/20 [==============================] - 2s 113ms/step - loss: 0.6943 - accuracy: 0.5126 - val_loss: 0.6957 - val_accuracy: 0.5000
Epoch 5/25
20/20 [==============================] - 3s 133ms/step - loss: 0.6914 - accuracy: 0.5177 - val_loss: 0.6929 - val_accuracy: 0.4750
Epoch 6/25
20/20 [==============================] - 3s 126ms/step - loss: 0.6918 - accuracy: 0.5455 - val_loss: 0.6913 - val_accuracy: 0.5750
Epoch 7/25
20/20 [==============================] - 3s 152ms/step - loss: 0.6877 - accuracy: 0.5934 - val_loss: 0.6876 - val_accuracy: 0.5250
Epoch 8/25
20/20 [==============================] - 2s 113ms/step - loss: 0.6871 - accuracy: 0.5631 - val_loss: 0.6901 - val_accuracy: 0.5250
Epoch 9/25
20/20 [==============================] - 2s 117ms/step - loss: 0.6866 - accuracy: 0.5581 - val_loss: 0.6868 - val_accuracy: 0.4750
Epoch 10/25
20/20 [==============================] - 2s 119ms/step - loss: 0.6816 - accuracy: 0.5909 - val_loss: 0.6814 - val_accuracy: 0.6250
Epoch 11/25
20/20 [==============================] - 2s 118ms/step - loss: 0.6740 - accuracy: 0.6136 - val_loss: 0.6755 - val_accuracy: 0.6250
Epoch 12/25
20/20 [==============================] - 3s 151ms/step - loss: 0.6696 - accuracy: 0.5884 - val_loss: 0.6807 - val_accuracy: 0.5750
Epoch 13/25
20/20 [==============================] - 3s 132ms/step - loss: 0.6672 - accuracy: 0.6212 - val_loss: 0.6570 - val_accuracy: 0.6000
Epoch 14/25
20/20 [==============================] - 2s 116ms/step - loss: 0.6504 - accuracy: 0.6125 - val_loss: 0.6703 - val_accuracy: 0.6000
Epoch 15/25
20/20 [==============================] - 2s 114ms/step - loss: 0.6605 - accuracy: 0.6111 - val_loss: 0.6821 - val_accuracy: 0.5750
Epoch 16/25
20/20 [==============================] - 2s 116ms/step - loss: 0.6572 - accuracy: 0.6414 - val_loss: 0.6686 - val_accuracy: 0.6250
Epoch 17/25
20/20 [==============================] - 3s 138ms/step - loss: 0.6374 - accuracy: 0.6894 - val_loss: 0.7424 - val_accuracy: 0.4750
Epoch 18/25
20/20 [==============================] - 2s 121ms/step - loss: 0.6463 - accuracy: 0.6313 - val_loss: 0.6882 - val_accuracy: 0.5250
Epoch 19/25
20/20 [==============================] - 2s 120ms/step - loss: 0.6226 - accuracy: 0.6641 - val_loss: 0.7030 - val_accuracy: 0.6500
Epoch 20/25
20/20 [==============================] - 2s 119ms/step - loss: 0.6222 - accuracy: 0.6692 - val_loss: 0.6921 - val_accuracy: 0.6000
Epoch 21/25
20/20 [==============================] - 3s 148ms/step - loss: 0.6272 - accuracy: 0.6263 - val_loss: 0.7351 - val_accuracy: 0.5750
Epoch 22/25
20/20 [==============================] - 2s 114ms/step - loss: 0.6453 - accuracy: 0.6162 - val_loss: 0.6654 - val_accuracy: 0.5750
Epoch 23/25
20/20 [==============================] - 2s 113ms/step - loss: 0.6411 - accuracy: 0.6061 - val_loss: 0.6958 - val_accuracy: 0.5750
Epoch 24/25
20/20 [==============================] - 2s 116ms/step - loss: 0.6088 - accuracy: 0.6894 - val_loss: 0.7624 - val_accuracy: 0.4500
Epoch 25/25
20/20 [==============================] - 3s 146ms/step - loss: 0.6173 - accuracy: 0.6566 - val_loss: 0.7217 - val_accuracy: 0.6000
1/1 [==============================] - 0s 102ms/step
Predictions: [[0.4815513]]
Predicted class label: [[0.]]
cat



# 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

from PIL import Image

# 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)

from google.colab import drive
drive.mount('/content/drive')

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)



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/cat2.jpg'  # Replace with the actual path of your image

img = image.load_img(image_path, target_size=(64, 64))

new_face = Image.open(image_path)
display(new_face)

# 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')

Comments

Popular posts from this blog

11. List of Capstone Projects for SOC - Deep Learning

8. Advanced CNN (Build AlexNet using Advanced CNN)