-
Notifications
You must be signed in to change notification settings - Fork 0
/
submission_dicoding.py
127 lines (102 loc) · 3.6 KB
/
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
# -*- coding: utf-8 -*-
"""Submission Dicoding.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1CAEGnZ6cY5ovdLAaT1nuXAlB-7bQq2A3
"""
import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import numpy as np
import zipfile
import os
import time
from google.colab import files
import matplotlib.pyplot as plt
from tensorflow.keras.preprocessing import image
!wget --no-check-certificate https://github.com/dicodingacademy/assets/releases/download/release/rockpaperscissors.zip -O /tmp/rockpaperscissors.zip
local_zip = '/tmp/rockpaperscissors.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
base_dir = '/tmp/rockpaperscissors/rps-cv-images'
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True,
validation_split=0.4
)
train_generator = train_datagen.flow_from_directory(
base_dir,
target_size=(150, 150),
batch_size=32,
class_mode='categorical',
subset='training'
)
val_generator = train_datagen.flow_from_directory(
base_dir,
target_size=(150, 150),
batch_size=32,
class_mode='categorical',
subset='validation'
)
model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
MaxPooling2D((2, 2)),
Conv2D(64, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Conv2D(128, (3, 3), activation='relu'),
MaxPooling2D((2, 2)),
Flatten(),
Dense(512, activation='relu'),
Dropout(0.5),
Dense(3, activation='softmax')
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
class MyCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs=None):
if logs.get('accuracy') >= 0.85:
self.model.stop_training = True
early_stopping = EarlyStopping(monitor='val_loss', patience=10)
model_checkpoint = ModelCheckpoint('/tmp/best_model.h5', monitor='val_accuracy', save_best_only=True)
start_time = time.time()
history = model.fit(train_generator,
epochs=34,
validation_data=val_generator,
callbacks=[MyCallback(), early_stopping, model_checkpoint])
end_time = time.time()
training_time = end_time - start_time
print(f"Training time: {training_time/60:.2f} minutes")
model.load_weights('/tmp/best_model.h5')
loss, accuracy = model.evaluate(val_generator)
print(f"Validation Accuracy: {accuracy * 100:.2f}%")
def predict_and_display_image(image_path):
img = image.load_img(image_path, target_size=(150, 150))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0)
img_array /= 255.0
prediction = model.predict(img_array)
class_idx = np.argmax(prediction)
class_names = ['rock', 'paper', 'scissors']
predicted_class = class_names[class_idx]
plt.imshow(image.load_img(image_path))
plt.title(f'Predicted: {predicted_class}')
plt.axis('off')
plt.show()
# Unggah dan prediksi gambar
uploaded = files.upload()
for fname in uploaded.keys():
print(f'Predicted class for {fname}:')
predict_and_display_image(fname)
personal_data = {
"name": "Nama Dicoding Anda",
"dicoding_id": "Id Dicoding Anda",
"submission_date": "Tanggal Anda Mengirim Submision"
}
print(personal_data)