-
Notifications
You must be signed in to change notification settings - Fork 0
/
final_submission_dicoding.py
212 lines (172 loc) · 6.46 KB
/
final_submission_dicoding.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
# -*- coding: utf-8 -*-
"""submission_dicoding.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1ajF3yNqjuYffSb0uMQgnVYzBaJV9JVzV
**Nama : Afif Ramadhan**
**Email: [email protected]**
***Data Science student Enthusiast***
Linkedin: https://www.linkedin.com/in/afiframadhan27
"""
import tensorflow as tf
import os
import zipfile
import random
import shutil
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn.model_selection import train_test_split
from shutil import copyfile
# Download and extract dataset
!wget --no-check-certificate \
https://github.com/dicodingacademy/assets/releases/download/release/rockpaperscissors.zip \
-O /tmp/rockpaperscissors.zip
zip_ref = zipfile.ZipFile('/tmp/rockpaperscissors.zip', 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
# Define dataset path
base_dir = '/tmp/rockpaperscissors'
# Define a path for training and validation set
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'val')
# Define a path for each label
rock_dir = os.path.join(base_dir, 'rock')
paper_dir = os.path.join(base_dir, 'paper')
scissors_dir = os.path.join(base_dir, 'scissors')
# Split the dataset into training and validation sets
train_rock_dir, val_rock_dir = train_test_split(os.listdir(rock_dir), test_size=0.4)
train_paper_dir, val_paper_dir = train_test_split(os.listdir(paper_dir), test_size=0.4)
train_scissors_dir, val_scissors_dir = train_test_split(os.listdir(scissors_dir), test_size=0.4)
# Create a training and validation folder
os.makedirs(os.path.join(train_dir, 'rock'), exist_ok=True)
os.makedirs(os.path.join(train_dir, 'paper'), exist_ok=True)
os.makedirs(os.path.join(train_dir, 'scissors'), exist_ok=True)
os.makedirs(os.path.join(validation_dir, 'rock'), exist_ok=True)
os.makedirs(os.path.join(validation_dir, 'paper'), exist_ok=True)
os.makedirs(os.path.join(validation_dir, 'scissors'), exist_ok=True)
# Move images into the training and validation set folder
def copy_images(file_names, source_dir, dest_dir):
for file_name in file_names:
source = os.path.join(source_dir, file_name)
dest = os.path.join(dest_dir, file_name)
copyfile(source, dest)
copy_images(train_rock_dir, rock_dir, os.path.join(train_dir, 'rock'))
copy_images(train_paper_dir, paper_dir, os.path.join(train_dir, 'paper'))
copy_images(train_scissors_dir, scissors_dir, os.path.join(train_dir, 'scissors'))
copy_images(val_rock_dir, rock_dir, os.path.join(validation_dir, 'rock'))
copy_images(val_paper_dir, paper_dir, os.path.join(validation_dir, 'paper'))
copy_images(val_scissors_dir, scissors_dir, os.path.join(validation_dir, 'scissors'))
# Implement image augmentation
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
horizontal_flip=True,
shear_range=0.2,
zoom_range=0.2,
fill_mode='nearest'
)
validation_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
horizontal_flip=True,
shear_range=0.2,
zoom_range=0.2,
fill_mode='nearest'
)
# Determine batch size and target size
batch_size = 32
target_size = (150, 150)
# Utilize image data generator
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=target_size,
batch_size=batch_size,
class_mode='categorical'
)
validation_generator = validation_datagen.flow_from_directory(
validation_dir,
target_size=target_size,
batch_size=batch_size,
class_mode='categorical'
)
# Build sequential model
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Conv2D(256, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(3, activation='softmax')
])
model.summary()
# Compile model
model.compile(optimizer = RMSprop(lr=0.001),
loss = 'categorical_crossentropy',
metrics = ['accuracy'])
# Create a callback function to stop data training when the task is already accomplished
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('accuracy') > 0.97):
print("\nAccuracy has reached > 97%!")
self.model.stop_training = True
# Utilize callback function
callbacks = myCallback()
# Model training
history = model.fit(
train_generator,
steps_per_epoch=train_generator.n // train_generator.batch_size,
epochs=30,
validation_data=validation_generator,
validation_steps=validation_generator.n // validation_generator.batch_size,
verbose=1,
callbacks=[callbacks]
)
# Create an accuracy and loss graph
import matplotlib.pyplot as plt
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs_range = range(len(acc))
plt.figure(figsize=(12, 12))
plt.subplot(2, 2, 1)
plt.plot(epochs_range, acc, label='Training Accuracy')
plt.plot(epochs_range, val_acc, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')
plt.subplot(2, 2, 2)
plt.plot(epochs_range, loss, label='Training Loss')
plt.plot(epochs_range, val_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show()
import numpy as np
from google.colab import files
# Define label from existing class
labels = ['paper', 'rock', 'scissors']
# Function to predict new images
def predict_image(filename):
img = tf.keras.preprocessing.image.load_img(
filename, target_size=(150,150)
)
img_array = tf.keras.preprocessing.image.img_to_array(img)
img_array = tf.expand_dims(img_array, 0)
predictions = model.predict(img_array)
score = tf.nn.softmax(predictions[0])
print("This image most likely belongs to {}."
.format(labels[np.argmax(score)]))
plt.imshow(img)
plt.axis('off')
plt.title(labels[np.argmax(score)])
plt.show()
# Upload a new file image
uploaded = files.upload()
# Call the predict_image function for each file uploaded
for fn in uploaded.keys():
predict_image(fn)