<jupyter_start><jupyter_text><jupyter_code>import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
print(tf.__version__)
!wget --no-check-certificate \
      https://dicodingacademy.blob.core.windows.net/picodiploma/ml_pemula_academy/rockpaperscissors.zip \
      -O /tmp/rockpaperscissors.zip
# melakukan ekstraksi pada file zip
import zipfile,os,shutil
local_zip = '/tmp/rockpaperscissors.zip'
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('/tmp')
zip_ref.close()
     
base_dir = '/tmp/rockpaperscissors'
data_gen = ImageDataGenerator(
                        rescale=1./255,
                        rotation_range=20,
                        horizontal_flip=True,
                        shear_range = 0.2,
                        validation_split=0.2,
                        fill_mode = 'nearest')

data_gen_test = ImageDataGenerator(
                        validation_split=0.2)
train_generator = data_gen.flow_from_directory(
            base_dir,  # direktori data latih
            target_size=(150, 150),  # mengubah resolusi seluruh gambar menjadi 150x150 piksel,
            class_mode='categorical',
            classes=['paper', 'rock', 'scissors'],
            subset="training",
            batch_size=4)

validation_generator = data_gen_test.flow_from_directory(
            base_dir,  # direktori data latih
            target_size=(150, 150),  # mengubah resolusi seluruh gambar menjadi 150x150 piksel,
            class_mode='categorical',
            classes=['paper', 'rock', 'scissors'],
            subset="validation",
            batch_size=4)
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(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(128, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        tf.keras.layers.Flatten(),
        tf.keras.layers.Dropout(0.5),
        tf.keras.layers.Dense(512, activation='relu'),
        tf.keras.layers.Dense(3, activation='softmax')
    ])
model.compile(loss='categorical_crossentropy',
                  optimizer=tf.optimizers.RMSprop(),
                  metrics=['accuracy'])
model.summary()
class myCallback(tf.keras.callbacks.Callback):
   def on_epoch_end(self, epoch, logs={}):
      if(logs.get('accuracy') >= 0.959 and logs.get('val_accuracy') >= 0.959):
          print("\nAkurasi telah mencapai >=95%!")
          self.model.stop_training = True
callbacks = myCallback()

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=15, min_lr=0.00001, verbose=2)
history = model.fit(train_generator,
          steps_per_epoch=20,  # berapa batch yang akan dieksekusi pada setiap epoch
          epochs=300,
          batch_size=128,
          callbacks=[callbacks, reduce_lr],
          validation_data=validation_generator, # menampilkan akurasi pengujian data validasi
          validation_steps=5,  # berapa batch yang akan dieksekusi pada setiap epoch
          verbose=2)
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()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Loss Model')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
    import numpy as np
    from google.colab import files
    from keras.preprocessing import image
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    import matplotlib.pyplot as plt
    import matplotlib.image as mpimg
    %matplotlib inline
     
    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)
      print(classes)
      if classes[0][0]:
        print('paper')
      elif classes[0][1]:
        print('rock')
      else:
        print('scissors')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1258436751578489, 'fraction_numerical': 0.0276507729153059, 'mean_word_length': 2.8800675675675675, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 8, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '577954', 'license': 'MIT', 'n_tokens_mistral': 1623, 'n_tokens_neox': 1509, 'n_words': 267, 'path': 'ImageClassification/ML_Dicoding_Submission.ipynb', 'repo_name': 'berviantoleo/machine-learning-experiment', 'size': '4593'}