Introduction
Daftar Anggota:
Hiskia Anggi Puji Pratama - A11.2020.12730
Moh. Arda Fadly Robby - A11.2020.13087
Muhammad Ariq Pratama - A11.2020.12944
Satrio Arda Alfiansyah - A11.2020.12739
Data Preparation
import zipfile,os
local_zip = 'kitset.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp/kitchenset')
zip_ref.close()
import splitfolders
import shutil
old_tmp_folder = "/tmp/kitchenset/"
new_tmp_folder = "/tmp/images"
splitfolders.ratio(old_tmp_folder, output=new_tmp_folder, seed=42, ratio=(.8, .2))
if os.path.isdir(old_tmp_folder):
shutil.rmtree(old_tmp_folder)
base_dir = '/tmp/images'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'val')
Data Preprocessing
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255,
rotation_range=20,
zoom_range=0.2,
shear_range=0.2,
fill_mode='nearest',
validation_split=0.1)
test_datagen = ImageDataGenerator(
rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(150, 150),
batch_size=16,
class_mode='categorical')
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=16,
class_mode='categorical')
train_generator.class_indices
Modelling
import tensorflow as tf
from tensorflow.keras.layers import Input
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications import ResNet152V2
model = tf.keras.models.Sequential([
ResNet152V2(weights="imagenet", include_top=False, input_tensor=Input(shape=(150, 150, 3))),
tf.keras.layers.Dropout(0.4),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(14, activation='softmax')
])
model.layers[0].trainable = False
model.summary()
model.compile(optimizer=tf.optimizers.Adam(),
loss='categorical_crossentropy',
metrics = ['accuracy'])
history = model.fit(train_generator,
validation_data=validation_generator,
epochs=50,
verbose=2)
Summary
import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Akurasi Model')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
Deploy
Kode di bawah menunjukkan bagaimana menyimpan model pengklasifikasi citra yang telah dibuat dan dilatih menggunakan TensorFlow. Fungsi save() digunakan untuk menyimpan model ke dalam file dengan nama 'pcd-ta.h5'. Ini memungkinkan model untuk digunakan kembali pada waktu yang akan datang tanpa perlu melakukan pelatihan ulang. File yang disimpan menggunakan format HDF5, yang merupakan format yang umum digunakan untuk menyimpan model pembelajaran mesin.
model.save('pcd-ta.h5')