Cnnbyrohanga: # Create Datasets

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

CNN by ROHAN G A

In [1]: import matplotlib.pyplot as plt


import tensorflow as tf
import pandas as pd
import numpy as np

In [2]: import warnings


warnings.filterwarnings('ignore')

In [3]: from tensorflow import keras


from keras import layers
from tensorflow.keras.models import Sequential

In [4]: from tensorflow.keras.layers import Activation, Dropout, Flatten, Dense


from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.utils import image_dataset_from_directory
from tensorflow.keras.preprocessing.image import ImageDataGenerator, load_img

In [5]: from tensorflow.keras.preprocessing import image_dataset_from_directory


import os
import matplotlib.image as mpimg

In [6]: import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'

In [7]: import os
path= "D:\dogs and cats dataset\dogs and cats dataset\datasets"
classes= os.listdir(path)
classes

['cats', 'dogs']
Out[7]:

In [8]: import matplotlib.image as mpimg


import matplotlib. pyplot as plt
fig = plt.gcf()
fig.set_size_inches(16, 16)

cat_dir = os.path.join('D:\dogs and cats dataset\dogs and cats dataset\datasets\cats')


dog_dir = os.path.join('D:\dogs and cats dataset\dogs and cats dataset\datasets\dogs')
cat_names = os.listdir(cat_dir)
dog_names = os.listdir(dog_dir)

pic_index = 210

cat_images = [os.path.join(cat_dir, fname)


for fname in cat_names[pic_index-8:pic_index]]
dog_images = [os.path.join(dog_dir, fname)
for fname in dog_names[pic_index-8:pic_index]]

for i, img_path in enumerate(cat_images + dog_images):


sp= plt.subplot(4, 4, i+1)
sp.axis('Off')

img = mpimg.imread(img_path)
plt.imshow(img)

plt.show()

In [9]: from tensorflow.keras.utils import image_dataset_from_directory


base_dir ='D:\dogs and cats dataset\dogs and cats dataset\datasets'

# Create datasets
train_datagen = image_dataset_from_directory(base_dir,
image_size=(200,200),
subset='training',
seed= 1,
validation_split=0.1,
batch_size= 32)
test_datagen = image_dataset_from_directory(base_dir,
image_size=(200,200),
subset='validation',
seed= 1,
validation_split=0.1,
batch_size=32)

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator
from tensorflow import keras
from keras import layers
model= tf.keras.models.Sequential([
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(200, 200, 3)),
layers.MaxPooling2D(2, 2),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D(2, 2),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D(2, 2),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D(2, 2),
layers.Flatten(),
layers.Dense(512, activation='relu'),
layers.BatchNormalization(),
layers.Dense(512, activation='relu'),
layers.Dropout(0.1),
layers.BatchNormalization(),
layers.Dense(512, activation='relu'),
layers.Dropout(0.2),
layers.BatchNormalization(),
layers.Dense(1, activation='sigmoid')
])
model.summary()

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

history= model.fit(train_datagen,
epochs=10,
validation_data=test_datagen)

history_df = pd.DataFrame(history.history)
history_df.loc[:, ['loss', 'val_loss']].plot()
history_df.loc[:, ['accuracy', 'val_accuracy']].plot()
plt.show()

import keras.utils as image


#Input image
test_image = image.load_img('D:\dogs and cats dataset\dogs and cats dataset\datasets\dogs\dog.4001.jpg', target_size=(200, 200))
plt.imshow(test_image)
test_image = image.img_to_array(test_image)
test_image = np.expand_dims(test_image,axis=0)
# Result array
result= model.predict(test_image)
#Napping result array with the main name list
i=0
if(result>=0.5):
print("Dog")
else:
print("Cat")

Found 2023 files belonging to 2 classes.


Using 1821 files for training.
Found 2023 files belonging to 2 classes.
Using 202 files for validation.
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 198, 198, 32) 896

max_pooling2d (MaxPooling2D (None, 99, 99, 32) 0


)

conv2d_1 (Conv2D) (None, 97, 97, 64) 18496

max_pooling2d_1 (MaxPooling (None, 48, 48, 64) 0


2D)

conv2d_2 (Conv2D) (None, 46, 46, 64) 36928

max_pooling2d_2 (MaxPooling (None, 23, 23, 64) 0


2D)

conv2d_3 (Conv2D) (None, 21, 21, 64) 36928

max_pooling2d_3 (MaxPooling (None, 10, 10, 64) 0


2D)

flatten (Flatten) (None, 6400) 0

dense (Dense) (None, 512) 3277312

batch_normalization (BatchN (None, 512) 2048


ormalization)

dense_1 (Dense) (None, 512) 262656

dropout (Dropout) (None, 512) 0

batch_normalization_1 (Batc (None, 512) 2048


hNormalization)

dense_2 (Dense) (None, 512) 262656

dropout_1 (Dropout) (None, 512) 0

batch_normalization_2 (Batc (None, 512) 2048


hNormalization)

dense_3 (Dense) (None, 1) 513

=================================================================
Total params: 3,902,529
Trainable params: 3,899,457
Non-trainable params: 3,072
_________________________________________________________________
Epoch 1/10
57/57 [==============================] - 26s 420ms/step - loss: 0.8835 - accuracy: 0.5409 - val_loss: 1.5360 - val_accuracy: 0.4653
Epoch 2/10
57/57 [==============================] - 29s 503ms/step - loss: 0.7315 - accuracy: 0.5810 - val_loss: 1.3872 - val_accuracy: 0.5693
Epoch 3/10
57/57 [==============================] - 23s 405ms/step - loss: 0.7084 - accuracy: 0.6030 - val_loss: 0.7866 - val_accuracy: 0.6337
Epoch 4/10
57/57 [==============================] - 28s 488ms/step - loss: 0.6659 - accuracy: 0.6326 - val_loss: 1.4096 - val_accuracy: 0.4703
Epoch 5/10
57/57 [==============================] - 25s 432ms/step - loss: 0.6272 - accuracy: 0.6678 - val_loss: 1.3085 - val_accuracy: 0.4604
Epoch 6/10
57/57 [==============================] - 27s 479ms/step - loss: 0.6253 - accuracy: 0.6584 - val_loss: 1.8041 - val_accuracy: 0.4604
Epoch 7/10
57/57 [==============================] - 24s 414ms/step - loss: 0.6094 - accuracy: 0.6908 - val_loss: 1.3604 - val_accuracy: 0.4851
Epoch 8/10
57/57 [==============================] - 24s 415ms/step - loss: 0.6091 - accuracy: 0.6733 - val_loss: 0.7924 - val_accuracy: 0.6089
Epoch 9/10
57/57 [==============================] - 26s 446ms/step - loss: 0.5557 - accuracy: 0.7144 - val_loss: 0.6400 - val_accuracy: 0.6386
Epoch 10/10
57/57 [==============================] - 25s 427ms/step - loss: 0.4878 - accuracy: 0.7699 - val_loss: 0.9569 - val_accuracy: 0.5693

1/1 [==============================] - 1s 770ms/step


Dog

You might also like