Skip to content

Commit 545b017

Browse files
authored
Add files via upload
1 parent c43c56f commit 545b017

File tree

1 file changed

+233
-0
lines changed

1 file changed

+233
-0
lines changed
+233
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
# -*- coding: utf-8 -*-
2+
"""DL Project 4. CIFAR-10 Object Recognition using ResNet50.ipynb
3+
4+
Automatically generated by Colaboratory.
5+
6+
Original file is located at
7+
https://colab.research.google.com/drive/1T46DXyngES0gbtxZrJ41mCzYS7ss3KUn
8+
"""
9+
10+
!pip install kaggle
11+
12+
# configuring the path of Kaggle.json file
13+
!mkdir -p ~/.kaggle
14+
!cp kaggle.json ~/.kaggle/
15+
!chmod 600 ~/.kaggle/kaggle.json
16+
17+
# daatset api
18+
!kaggle competitions download -c cifar-10
19+
20+
!ls
21+
22+
# extracting the compessed Dataset
23+
from zipfile import ZipFile
24+
dataset = '/content/cifar-10.zip'
25+
26+
with ZipFile(dataset,'r') as zip:
27+
zip.extractall()
28+
print('The dataset is extracted')
29+
30+
!ls
31+
32+
!pip install py7zr
33+
34+
import py7zr
35+
36+
archive = py7zr.SevenZipFile('/content/train.7z', mode='r')
37+
archive.extractall() #archive.extractall(path='/content/Training Data')
38+
archive.close()
39+
40+
!ls
41+
42+
"""Importing the Dependencies"""
43+
44+
import os
45+
import numpy as np
46+
import pandas as pd
47+
from PIL import Image
48+
import matplotlib.pyplot as plt
49+
import matplotlib.image as mpimg
50+
from sklearn.model_selection import train_test_split
51+
52+
filenames = os.listdir('/content/train')
53+
54+
type(filenames)
55+
56+
len(filenames)
57+
58+
print(filenames[0:5])
59+
print(filenames[-5:])
60+
61+
"""**Labels Processing**"""
62+
63+
labels_df = pd.read_csv('/content/trainLabels.csv')
64+
65+
labels_df.shape
66+
67+
labels_df.head()
68+
69+
labels_df[labels_df['id'] == 7796]
70+
71+
labels_df.head(10)
72+
73+
labels_df.tail(10)
74+
75+
labels_df['label'].value_counts()
76+
77+
labels_df['label']
78+
79+
labels_dictionary = {'airplane':0, 'automobile':1, 'bird':2, 'cat':3, 'deer':4, 'dog':5, 'frog':6, 'horse':7, 'ship':8, 'truck':9}
80+
81+
labels = [labels_dictionary[i] for i in labels_df['label']]
82+
83+
print(labels[0:5])
84+
print(labels[-5:])
85+
86+
# displaying sample image
87+
import cv2
88+
from google.colab.patches import cv2_imshow
89+
90+
img = cv2.imread('/content/train/7796.png')
91+
cv2_imshow(img)
92+
93+
# displaying sample image
94+
import cv2
95+
from google.colab.patches import cv2_imshow
96+
97+
img = cv2.imread('/content/train/45888.png')
98+
cv2_imshow(img)
99+
100+
labels_df[labels_df['id'] == 45888]
101+
102+
labels_df.head()
103+
104+
id_list = list(labels_df['id'])
105+
106+
print(id_list[0:5])
107+
print(id_list[-5:])
108+
109+
"""**Image Processing**"""
110+
111+
# convert images to numpy arrays
112+
113+
train_data_folder = '/content/train/'
114+
115+
data = []
116+
117+
for id in id_list:
118+
119+
image = Image.open(train_data_folder + str(id) + '.png')
120+
image = np.array(image)
121+
data.append(image)
122+
123+
type(data)
124+
125+
len(data)
126+
127+
type(data[0])
128+
129+
data[0].shape
130+
131+
data[0]
132+
133+
# convert image list and label list to numpy arrays
134+
135+
X = np.array(data)
136+
Y = np.array(labels)
137+
138+
type(X)
139+
140+
print(X.shape)
141+
print(Y.shape)
142+
143+
"""**Train Test Split**"""
144+
145+
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=2)
146+
147+
print(X.shape, X_train.shape, X_test.shape)
148+
149+
# scaling the data
150+
151+
X_train_scaled = X_train/255
152+
153+
X_test_scaled = X_test/255
154+
155+
X_train_scaled
156+
157+
X_train[0]
158+
159+
"""**Building the Neural Network**"""
160+
161+
import tensorflow as tf
162+
from tensorflow import keras
163+
164+
num_of_classes = 10
165+
166+
# setting up the layers of Neural Network
167+
168+
model = keras.Sequential([
169+
170+
keras.layers.Flatten(input_shape=(32,32,3)),
171+
keras.layers.Dense(64, activation='relu'),
172+
keras.layers.Dense(num_of_classes, activation='softmax')
173+
])
174+
175+
# compile the neural network
176+
model.compile(optimizer='adam',
177+
loss='sparse_categorical_crossentropy',
178+
metrics=['acc'])
179+
180+
# training the neural network
181+
model.fit(X_train_scaled, Y_train, validation_split=0.1, epochs=10)
182+
183+
"""**ResNet50**"""
184+
185+
from tensorflow.keras import Sequential, models, layers
186+
from tensorflow.keras.layers import Dense, Dropout, Flatten
187+
from tensorflow.keras.layers import BatchNormalization
188+
from tensorflow.keras.models import load_model
189+
from tensorflow.keras.models import Model
190+
from tensorflow.keras.applications.resnet50 import ResNet50
191+
from tensorflow.keras import optimizers
192+
193+
convolutional_base = ResNet50(weights='imagenet', include_top=False, input_shape=(256,256,3))
194+
convolutional_base.summary()
195+
196+
num_of_classes = 10
197+
198+
model = models.Sequential()
199+
model.add(layers.UpSampling2D((2,2)))
200+
model.add(layers.UpSampling2D((2,2)))
201+
model.add(layers.UpSampling2D((2,2)))
202+
model.add(convolutional_base)
203+
model.add(layers.Flatten())
204+
model.add(layers.BatchNormalization())
205+
model.add(layers.Dense(128, activation='relu'))
206+
model.add(layers.Dropout(0.5))
207+
model.add(layers.BatchNormalization())
208+
model.add(layers.Dense(64, activation='relu'))
209+
model.add(layers.Dropout(0.5))
210+
model.add(layers.BatchNormalization())
211+
model.add(layers.Dense(num_of_classes, activation='softmax'))
212+
213+
model.compile(optimizer=optimizers.RMSprop(lr=2e-5), loss='sparse_categorical_crossentropy', metrics=['acc'])
214+
215+
history = model.fit(X_train_scaled, Y_train, validation_split=0.1, epochs=10)
216+
217+
loss, accuracy = model.evaluate(X_test_scaled, Y_test)
218+
print('Test Accuracy =', accuracy)
219+
220+
h = history
221+
222+
# plot the loss value
223+
plt.plot(h.history['loss'], label='train loss')
224+
plt.plot(h.history['val_loss'], label='validation loss')
225+
plt.legend()
226+
plt.show()
227+
228+
# plot the accuracy value
229+
plt.plot(h.history['acc'], label='train accuracy')
230+
plt.plot(h.history['val_acc'], label='validation accuracy')
231+
plt.legend()
232+
plt.show()
233+

0 commit comments

Comments
 (0)