-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubmission_3_(1).py
159 lines (126 loc) · 4.45 KB
/
submission_3_(1).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
# -*- coding: utf-8 -*-
"""submission 3 (1).ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1DKCK-hjHRczpobqq4fQYhuxJPy6To8Wd
"""
from google.colab import files
!pip install -q kaggle
uploaded = files.upload()
!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
!chmod 600 ~/.kaggle/kaggle.json
!kaggle datasets download -d ashishsaxena2209/animal-image-datasetdog-cat-and-panda
import tensorflow as tf
import keras_preprocessing
from keras_preprocessing import image
from keras_preprocessing.image import ImageDataGenerator
import os
import zipfile
import shutil
local_zip = '/content/animal-image-datasetdog-cat-and-panda.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/content/')
zip_ref.close()
dir_utama = os.path.join('/content/animals')
print(os.listdir(dir_utama))
ignore_dir = ['images', 'animals']
for dir in ignore_dir:
path = os.path.join(dir_utama, dir)
shutil.rmtree(path)
print(os.listdir(dir_utama))
from PIL import Image
jumlah_sampel = 0
for x in os.listdir(dir_utama):
dir = os.path.join('/content/animals/', x)
y = len(os.listdir(dir))
print(x+':', y)
jumlah_sampel = jumlah_sampel + y
img_name = os.listdir(dir)
for z in range(5):
img_path = os.path.join(dir, img_name[z])
img = Image.open(img_path)
print('-',img.size)
print('---------------')
print('\nJumlah total sampel:', jumlah_sampel)
train_datagen = ImageDataGenerator(
rescale = 1./255,
rotation_range = 20,
horizontal_flip = True,
shear_range = 0.2,
zoom_range = 0.2,
fill_mode = 'nearest',
validation_split = 0.2 # Membagi Data Validasi 20% dan Training 80%
)
batch_size = 128
generator_latih = train_datagen.flow_from_directory(
dir_utama,
target_size = (150,150), # Besar Input harus sama besar dan dijadikan 150x150
class_mode = 'categorical', # Menggunakan lebih dari 2 kelas
batch_size = batch_size,
subset = 'training' # Penentuan sebagai data latih
)
generator_validasi = train_datagen.flow_from_directory(
dir_utama, # Direktori sama dengan generator latih karena pembagian dilakukan oleh Generator
target_size = (150,150),
class_mode = 'categorical',
batch_size = batch_size,
subset = 'validation' # Penentuan sebagai data latih
)
model = tf.keras.models.Sequential([
# Besar masukan dibuat sebesar 150x150 dengan warna 3 bytes
# Konvulasi pertama
tf.keras.layers.Conv2D(64, (3,3), activation='relu', input_shape=(150, 150, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
# Konvolusi Kedua
tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# Konvolusi Ketiga
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# Konvolusi Keempat
tf.keras.layers.Conv2D(128, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
# Meratakan input menjadi 1 dimensi
tf.keras.layers.Flatten(),
# Menggunakan Dropout sebesar 50%
tf.keras.layers.Dropout(0.5),
# 512 neuron terhadap hidden layer
tf.keras.layers.Dense(512, activation='relu'),
# 3 neuron/kelas pada output layer
tf.keras.layers.Dense(3, activation='softmax')
])
model.summary()
model.compile(loss = 'categorical_crossentropy',
optimizer = 'rmsprop', # Opmitizer RMSprop
metrics = ['accuracy'])
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if (logs.get('accuracy')>0.80 and logs.get('val_accuracy')>0.80) :
print("\nAkurasi di atas 80%, hentikan pelatihan!")
self.model.stop_training = True
callbacks = myCallback()
history = model.fit(generator_latih,
epochs = 40,
steps_per_epoch = 2400//batch_size,
validation_data = generator_validasi,
verbose = 1,
validation_steps = 600//batch_size,
callbacks = [callbacks])
import matplotlib.pyplot as plt
def plot_graphs(history, string):
plt.plot(history.history[string])
plt.plot(history.history['val_'+string])
plt.xlabel("Epochs")
plt.ylabel(string)
plt.legend([string, 'val_'+string])
plt.show()
plot_graphs(history, "accuracy")
plot_graphs(history, "loss")
# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
# Save the model.
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
!ls -a