-
Notifications
You must be signed in to change notification settings - Fork 0
/
proyek_akhir_image_classification_model_deployment_millata_tasyakhanifa.py
257 lines (206 loc) · 7.45 KB
/
proyek_akhir_image_classification_model_deployment_millata_tasyakhanifa.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
# -*- coding: utf-8 -*-
"""Proyek Akhir_Image Classification Model Deployment_Millata Tasyakhanifa.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1k5qx9v44tEiH6z03hXLQtrvJZ5mfqfa_
#### Nama: Millata Tasyakhanifa
#### Username: millatasyaa
#### Email: millatatasyakhanifa@gmail.com
## Import library
"""
# Commented out IPython magic to ensure Python compatibility.
import pandas as pd
from pandas import DataFrame
# Library to extract files
import os
import zipfile
# Library to display images
# %matplotlib inline
from keras.preprocessing import image
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
# Library to using Image Generator
import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from google.colab import files
"""## Extract the zip file"""
local_zip = '/content/Satellite_Image.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/content')
zip_ref.close()
"""## Create a folder for cloud image data"""
cloudy_folder = os.path.join('/content/data/cloudy')
# Show the total number of images in the cloud folder
len_cloudy_folder = len(os.listdir(cloudy_folder))
print("Total paper pictures:", len_cloudy_folder)
# Show 5 data in the cloudy folder
cloudy = os.listdir(cloudy_folder)
print("5 data in the cloudy folder:")
i=0
cloudy_temp = []
for file_cloudy in cloudy[:5]:
cloudy_temp.append(file_cloudy)
i=i+1
data_cloudy = {'File Name': cloudy_temp}
df_cloudy = pd.DataFrame(data_cloudy,
index=[1,2,3,4,5])
df_cloudy.head()
image_cloud = image.load_img('/content/data/cloudy/train_14090.jpg')
image_cloud_plot = plt.imshow(image_cloud)
"""## Create a folder for desert image data"""
desert_folder = os.path.join('/content/data/desert')
# Show the total number of images in the desert folder
len_desert_folder = len(os.listdir(desert_folder))
print("Total desert pictures:", len_desert_folder)
# Show 5 data in the desert folder
desert = os.listdir(desert_folder)
print("5 data in the desert folder:")
i=0
desert_temp = []
for file_desert in desert[:5]:
desert_temp.append(file_desert)
i=i+1
data_desert = {'File Name': desert_temp}
df_desert = pd.DataFrame(data_desert,
index=[1,2,3,4,5])
df_desert.head()
image_desert = image.load_img('/content/data/desert/desert(248).jpg')
image_desert_plot = plt.imshow(image_desert)
"""## Create a folder for green area image data"""
green_area_folder = os.path.join('/content/data/green_area')
# Show the total number of images in the green area folder
len_green_area_folder = len(os.listdir(green_area_folder))
print("Total green area pictures:", len_green_area_folder)
# Show 5 data in the green area folder
green_area = os.listdir(green_area_folder)
print("5 data in the green area folder:")
i=0
green_area_temp = []
for file_green_area in green_area[:5]:
green_area_temp.append(file_green_area)
i=i+1
data_green_area = {'File Name': green_area_temp}
df_green_area = pd.DataFrame(data_green_area,
index=[1,2,3,4,5])
df_green_area.head()
image_green_area = image.load_img('/content/data/green_area/Forest_2315.jpg')
image_green_area_plot = plt.imshow(image_green_area)
"""## Create a folder for water image data"""
water_folder = os.path.join('/content/data/water')
# Show the total number of images in the water folder
len_water_folder = len(os.listdir(water_folder))
print("Total water pictures:", len_water_folder)
# Show 5 data in the water folder
water = os.listdir(water_folder)
print("5 data in the water folder:")
i=0
water_temp = []
for file_water in water[:5]:
water_temp.append(file_water)
i=i+1
data_water = {'File Name': water_temp}
df_water = pd.DataFrame(data_water,
index=[1,2,3,4,5])
df_water.head()
image_water = image.load_img('/content/data/water/SeaLake_245.jpg')
image_water_plot = plt.imshow(image_water)
"""## Using Image Generator"""
train_dir = os.path.join("/content/data")
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
horizontal_flip=True,
shear_range=0.2,
zoom_range=0.2,
fill_mode = 'nearest',
# Data is divided into 20% data test and 80% data training
validation_split=0.2)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=40,
class_mode='categorical',
subset='training')
validation_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=40,
class_mode='categorical',
subset='validation')
"""## Make models"""
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Dropout(0.4),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(4, activation='softmax')
])
# compile model
optimizer = tf.keras.optimizers.Adam(learning_rate=1.0000e-04)
model.compile(loss='categorical_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy')>=0.92 or logs.get('val_accuracy')>=0.92):
print("\nAccuracy or Validation Accuracy has reached 0.92")
self.model.stop_training = True
callbacks = myCallback()
# train models with model.fit
history = train_models = model.fit(
train_generator,
batch_size=64,
epochs=100,
validation_data=validation_generator,
validation_steps=5,
callbacks=[callbacks])
"""## Loss and Accuracy Plots During Training and Validation"""
plt.figure(figsize=(18, 6))
plt.plot(history.history['accuracy'], label='Train Accuracy')
plt.plot(history.history['val_accuracy'], label='Validation Accuracy')
plt.title('Train and Validation Accuracy Graphs')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.figure(figsize=(10, 6))
plt.plot(history.history['loss'], label='Train Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.title('Train and Validation Loss Graphs')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
uploaded = files.upload()
for fn in uploaded.keys():
# predicting images
path = fn
img = image.load_img(path, target_size=(150,150))
imgplot = plt.imshow(img)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
images = np.vstack([x])
classes = model.predict(images, batch_size=10)
print(fn)
if classes[0,0]!=0:
print('This picture shows cloud')
elif classes[0,1]!=0:
print('This picture shows disert')
elif classes[0,2]!=0:
print('This picture shows green area')
elif classes[0,3]!=0:
print('This picture shows water')
else:
print('Unknown image')
"""## Konversi Model"""
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
f.write(tflite_model)