Machine Learning Foundations: Exercise 4 Happy and sad image classify model with 99.9% accuracy:code lab link
Build a mode to classify happy and sad model with convolution neuron network. with more 99.9% accuracy.
Note:
- Model over-fitting: Near 100% accuracy on training data, but lower accuracy on testing data.
- ImageDataGenerator: Label data automatic using directory name.
Code:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tensorflow as tf | |
import os | |
import zipfile | |
DESIRED_ACCURACY = 0.999 | |
# Get the happy-or-sad image data | |
!wget --no-check-certificate \ | |
"https://storage.googleapis.com/laurencemoroney-blog.appspot.com/happy-or-sad.zip" \ | |
-O "/tmp/happy-or-sad.zip" | |
zip_ref = zipfile.ZipFile("/tmp/happy-or-sad.zip", 'r') | |
zip_ref.extractall("/tmp/h-or-s") | |
zip_ref.close() | |
# Callback function to check model accuracy | |
class RayCallback(tf.keras.callbacks.Callback): | |
def on_epoch_end(self, epoch, logs={}): | |
if(logs.get('accuracy')>DESIRED_ACCURACY): | |
print("\nReached 99.9% accuracy so cancelling training!") | |
self.model.stop_training = True | |
callbacks = RayCallback() | |
# 5 layer neuron network | |
model = tf.keras.models.Sequential([ | |
tf.keras.layers.Conv2D(16, (3,3), activation='relu', | |
input_shape=(300, 300, 3)), # Fit ImageDataGenerator output size | |
tf.keras.layers.MaxPooling2D(2, 2), | |
tf.keras.layers.Conv2D(32, (3,3), activation='relu'), | |
tf.keras.layers.MaxPooling2D(2,2), | |
tf.keras.layers.Flatten(), | |
tf.keras.layers.Dense(512, activation='relu'), | |
tf.keras.layers.Dense(1, activation='sigmoid') | |
]) | |
from tensorflow.keras.optimizers import RMSprop | |
model.compile(loss='binary_crossentropy', | |
optimizer=RMSprop(lr=0.001), | |
metrics=['accuracy']) | |
# Label image data base on it's directory name | |
from tensorflow.keras.preprocessing.image import ImageDataGenerator | |
train_datagen = ImageDataGenerator(1./255) | |
train_generator = train_datagen.flow_from_directory( | |
'/tmp/h-or-s', # Data directory | |
target_size=(300, 300), # Output size | |
batch_size=128, # Size of the batches of data, each batch is 8 data since the training data are 80 images | |
class_mode='binary' # Two class: Happy, Bad | |
) | |
# Train the model | |
history = model.fit(train_generator, | |
steps_per_epoch = 8, # Load 8 data each epoch to parallize the training stage | |
epochs=15, | |
callbacks=callbacks | |
) | |
沒有留言:
張貼留言