-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdog_vs_cat_dl_model_ (1).py
259 lines (166 loc) · 5.17 KB
/
dog_vs_cat_dl_model_ (1).py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# -*- coding: utf-8 -*-
"""Dog vs cat DL model .ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ZMFVM5HDayf5xj8c7gl1KpP9A41YM_G0
Extracting Dataset using Kaggle API
"""
#installing the kaggle library
!pip install kaggle
#configure the path of kaggle.json file
!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
!chmod 600 ~/.kaggle/kaggle.json
"""Importing the Dog vs Cat Dataset from Kaggle"""
# Kaggle API
!kaggle competitions download -c dogs-vs-cats
!ls
# extracting the compressed dataset
from zipfile import ZipFile
dataset = '/content/dogs-vs-cats.zip'
with ZipFile(dataset, 'r') as zip:
zip.extractall()
print('The dataset is extracted')
#extracting the compressed dataset
from zipfile import ZipFile
dataset = '/content/train.zip'
with ZipFile(dataset, 'r') as zip:
zip.extractall()
print('the dataset is extracted')
import os
# counting the number of files in train folder
path , dirs , files = next(os.walk('/content/train'))
file_count = len(files)
print('Number of images:' , file_count)
"""### Printing the name of the images"""
file_names = os.listdir('/content/train')
print(file_names)
"""Importing the Dependencies"""
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.image as mping
from sklearn.model_selection import train_test_split
from google.colab.patches import cv2_imshow
"""## Display the images of dog and cats"""
# display the image
img = mping.imread('/content/train/dog.8298.jpg')
imgplt = plt.imshow(img)
plt.show()
# display the image
img = mping.imread('/content/train/cat.4352.jpg')
imgplt = plt.imshow(img)
plt.show()
file_names = os.listdir('/content/train/')
for i in range(5):
name = file_names[i]
print(name[0:3])
file_names = os.listdir('/content/train/')
dog_count = 0
cat_count = 0
for img_file in file_names:
name = img_file[0:3]
if name == 'dog':
dog_count +=1
else:
cat_count +=1
print('Number of dog images = ' , dog_count)
print('Number of cat iamges = ' , cat_count)
"""Resizing all the images"""
#creating a directory for resized images
os.mkdir('/content/image resized')
original_folder = '/content/train/'
resized_folder = '/content/image resized/'
for i in range(2000):
filename = os.listdir(original_folder)[i]
img_path = original_folder+filename
img = Image.open(img_path)
img = img.resize((224 ,224))
img = img.convert('RGB')
newImgPath = resized_folder+filename
img.save(newImgPath)
img = mping.imread('/content/image resized/dog.1063.jpg')
imgplt = plt.imshow(img)
plt.show
# display cat image
image = mping.imread('/content/train/cat.4351.jpg')
imgplt = plt.imshow(image)
plt.show
"""Creating labels for resized images of dog and cats
Cat --> 0
Dog --> 1
"""
# creating a for loop to assign labels
filenames = os.listdir('/content/image resized/')
labels = []
for i in range(2000):
file_name = filenames[i]
label = file_name[0:3]
if label == 'dog':
labels.append(1)
else:
labels.append(0)
print(filenames[0:5])
print(len(labels))
print(labels[0:5])
print(len(labels))
# countig the images of the dog and cats out of 2000 images
values , counts = np.unique(labels,return_counts=True)
print(values)
print(counts)
"""Converting all the resized images to numpy array"""
import cv2
import glob
image_directory = '/content/image resized/'
image_extension = ['png' , 'jpg']
files = [ ]
[files.extend(glob.glob(image_directory + '*.' + e)) for e in image_extension]
dog_cat_images = np.asarray([cv2.imread(file) for file in files])
print(dog_cat_images)
type(dog_cat_images)
print(dog_cat_images.shape)
X = dog_cat_images
Y = np.asarray(labels)
"""### Train Test Split"""
X_train , X_test , Y_train , Y_test = train_test_split(X,Y , test_size =0.2,random_state=2)
print(X.shape , X_train.shape , X_test.shape)
"""1600 --> training images
400 --> testing images
"""
# Scaling the data
X_train_scaled = X_train/255
X_test_scaled = X_test/255
print(X_train_scaled)
"""**Building the Nueral Network**"""
import tensorflow as tf
import tensorflow_hub as hub
mobilenet_model = 'https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4'
pretrained_model = hub.KerasLayer(mobilenet_model , input_shape=(224,224,3) ,trainable=False)
num_of_classes = 2
model = tf.keras.Sequential([
pretrained_model,
tf.keras.layers.Dense(num_of_classes)
])
model.summary()
model.compile(
optimizer = 'adam',
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics = ['acc']
)
model.fit(X_train_scaled , Y_train, epochs=5)
score ,acc = model.evaluate(X_test_scaled ,Y_test)
print('Test Loss = ',score)
print('Test Accuracy = ' , acc)
"""Predictive System"""
input_image_path = input('Path of the image to be predicted:')
input_image = cv2.imread(input_image_path)
cv2_imshow(input_image)
input_image_resize = cv2.resize(input_image , (224,224))
input_image_scaled = input_image_resize/255
image_reshaped = np.reshape(input_image_scaled , [1,224,224,3])
input_prediction = model.predict(image_reshaped)
input_pred_label = np.argmax(input_prediction)
if input_pred_label == 0:
print('The Image represents a Cat')
else:
print('The Image represents a Dog')