-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage_classification.py
198 lines (129 loc) · 5.68 KB
/
image_classification.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
# -*- coding: utf-8 -*-
"""image_classification.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1IHJX6KRImscZA2iN0s3exNBCtrq7B-2x
#**Libraries Installation**
"""
pip install -q tensorflow tensorflow-datasets
"""#**Importing the Libraries**"""
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow import keras
"""#**Finding Datasets**"""
tfds.list_builders()
"""#**Get information on the data**"""
builder = tfds.builder('rock_paper_scissors')
info = builder.info
info
"""#**Prepare the data**"""
ds_train = tfds.load('rock_paper_scissors', split='train')
ds_test = tfds.load('rock_paper_scissors', split='test')
"""#**Data viewing**"""
fig = tfds.show_examples(info, ds_train)
"""##**Convert data to numpy format**"""
train_images = np.array([example['image'].numpy()[:,:,0] for example in ds_train])
train_labels = np.array([example['label'].numpy() for example in ds_train])
test_images = np.array([example['image'].numpy()[:,:,0] for example in ds_test])
test_labels = np.array([example['label'].numpy() for example in ds_test])
train_images = train_images.reshape(2520,300, 300, 1)
test_images = test_images.reshape(372,300, 300, 1)
train_images = train_images.astype('float32')
test_images = test_images.astype('float32')
#to make all the values between 0 and 1 (question of performance)
train_images /=255
test_images /=255
train_images
"""#**Trainig the first network**"""
model = keras.Sequential([
keras.layers.Flatten(),
keras.layers.Dense(512, activation='relu'),
keras.layers.Dense(256, activation='relu'),
keras.layers.Dense(3, activation='softmax'),
])
model.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=10)
print("EVALUATION")
model.evaluate(test_images, test_labels)
"""#**Convolutional Neural Net (CNN) Approach**"""
model = keras.Sequential([
keras.layers.Conv2D(64, 3, input_shape=(300,300,1), activation='relu'),
keras.layers.Conv2D(32, 3, activation='relu'),
keras.layers.Flatten(),
keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_images, train_labels, batch_size=32, epochs=10)
print("EVALUATION")
model.evaluate(test_images, test_labels)
"""#**Improving our CNN**"""
model = keras.Sequential([
keras.layers.AveragePooling2D(6, 3, input_shape=(300,300,1)),
keras.layers.Conv2D(64, 3, activation='relu'),
keras.layers.Conv2D(64, 3, activation='relu'),
keras.layers.MaxPool2D(2,2),
keras.layers.Dropout(0.5),
keras.layers.Flatten(),
keras.layers.Dense(256, activation='relu'),
keras.layers.Dense(256, activation='relu'),
keras.layers.Dense(3, activation='softmax')
])
model.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(train_images, train_labels, batch_size=32, epochs=8)
print("EVALUATION")
model.evaluate(test_images, test_labels)
"""#**Using kerastuner to pick best hyperparameters**"""
pip install keras-tuner --upgrade
from kerastuner.tuners import RandomSearch
def build_model(hp):
model = keras.Sequential()
model.add(keras.layers.AveragePooling2D(6,3,input_shape=(300,300,1)))
for i in range(hp.Int("Conv Layers", min_value=0, max_value=3)):
model.add(keras.layers.Conv2D(hp.Choice(f"layer_{i}_filters", [16,32,64]), 3, activation='relu'))
model.add(keras.layers.MaxPool2D(2,2))
model.add(keras.layers.Dropout(0.5))
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(hp.Choice("Dense layer", [64, 128, 256, 512, 1024]), activation='relu'))
model.add(keras.layers.Dense(3, activation='softmax'))
model.compile(optimizer='adam',
loss=keras.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'])
return model
tuner = RandomSearch(
build_model,
objective='val_accuracy',
max_trials=32,
)
tuner.search(train_images, train_labels, validation_data=(test_images, test_labels), epochs=10, batch_size=32)
best_model = tuner.get_best_models()[0]
best_model.evaluate(test_images, test_labels)
best_model.summary()
tuner.results_summary()
"""#**Save and Load our Models**"""
best_model.save('./models')
loaded_model = keras.models.load_model('./models')
loaded_model.evaluate(test_images, test_labels)
"""#**Plot numpy arrays as images**"""
rgb_images = np.array([example['image'].numpy() for example in ds_train.take(1)])
rgb_image = rgb_images[0]
plt.imshow(rgb_image)
rgb_image.shape
"""#**Use Model to Predict Result for Single Example**"""
result = best_model.predict(np.array([train_images[0]]))
print(result)
predicted_value = np.argmax(result)
print(predicted_value)
"""#**Convert PNG/JPG images to Numpy Format**"""
import imageio
im = imageio.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/8/84/Massachusetts_State_House_-_panoramio_%281%29.jpg/280px-Massachusetts_State_House_-_panoramio_%281%29.jpg')
print(type(im))
im_np = np.asarray(im)
print(im_np.shape)