본문 바로가기
AI & 머신러닝 coding skill

[INTRODUCTION TO TENSORFLOW FOR ARTIFICIAL INTELLIGENCE, MACHINE LEARNING, AND DEEP LEARNING] Handling Complex Images

by 호빵님 2020. 11. 16.
반응형

코세라의   deeplearning.AI tensorflow developer 전문가 자격증 과정내에

Introduction to TensorFlow for Artificial Intelligence, Machine Learning, and Deep Learning

과정의 4주차 Using Real-world Images

챕터의 코드 예제입니다.

 

Handling Complex Images

1) Happy or Sad image dataset를 받는다

2) myCallback함수에 traing accuracy가 99.9%이상이되면 훈련을 멈추도록 구현한다.

3) Conv2D를 이용한 네트워크를 구성한다.

4) preprocessing.image name space의  ImageDataGenerator를 이용해서, 밝기를 1/255로 정규화한다

5) flow_from_directory method를 이용해서, training data가 있는 디렉토리를 설정하고, target image size와 class mode, batch size를 설정한다.

6) fit_generator를 이용해서 모델을 훈련한다.

#!/usr/bin/env python
# coding: utf-8

# Below is code with a link to a happy or sad dataset which contains 80 images, 40 happy and 40 sad. 
# Create a convolutional neural network that trains to 100% accuracy on these images,  which cancels training upon hitting training accuracy of >.999
# 
# Hint -- it will work best with 3 convolutional layers.

# In[ ]:


import tensorflow as tf
import os
import zipfile
from os import path, getcwd, chdir

# DO NOT CHANGE THE LINE BELOW. If you are developing in a local
# environment, then grab happy-or-sad.zip from the Coursera Jupyter Notebook
# and place it inside a local folder and edit the path to that location
path = f"{getcwd()}/../tmp2/happy-or-sad.zip"

zip_ref = zipfile.ZipFile(path, 'r')
zip_ref.extractall("/tmp/h-or-s")
zip_ref.close()


# In[ ]:


# GRADED FUNCTION: train_happy_sad_model
def train_happy_sad_model():
    # Please write your code only where you are indicated.
    # please do not remove # model fitting inline comments.

    DESIRED_ACCURACY = 0.999


    class myCallback(tf.keras.callbacks.Callback):
      def on_epoch_end(self, epoch, logs={}):
        if(logs.get('acc')>DESIRED_ACCURACY):
          print("\nReached 99.9% accuracy so cancelling training!")
          self.model.stop_training = True

    callbacks = myCallback()
    
    # This Code Block should Define and Compile the Model. Please assume the images are 150 X 150 in your implementation.
    model = tf.keras.models.Sequential([
        # Your Code Here
        tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(150, 150, 3)),
        tf.keras.layers.MaxPooling2D(2, 2),
        # The second convolution
        tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        # The third convolution
        tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
        tf.keras.layers.MaxPooling2D(2,2),
        # Flatten the results to feed into a DNN
        tf.keras.layers.Flatten(),
        # 512 neuron hidden layer
        tf.keras.layers.Dense(512, activation='relu'),
        # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('horses') and 1 for the other ('humans')
        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'])
        

    # This code block should create an instance of an ImageDataGenerator called train_datagen 
    # And a train_generator by calling train_datagen.flow_from_directory

    from tensorflow.keras.preprocessing.image import ImageDataGenerator

    train_datagen = ImageDataGenerator(rescale=1/255)

    # Please use a target_size of 150 X 150.
    train_generator = train_datagen.flow_from_directory(
        '/tmp/h-or-s/',  # This is the source directory for training images
        target_size=(150, 150),  # All images will be resized to 300x300
        batch_size=128,
        # Since we use binary_crossentropy loss, we need binary labels
        class_mode='binary')
    # Expected output: 'Found 80 images belonging to 2 classes'

    # This code block should call model.fit_generator and train for
    # a number of epochs.
    # model fitting
    history = model.fit_generator(train_generator,steps_per_epoch=8,epochs=15,verbose=1,callbacks=[callbacks])
    # model fitting
    return history.history['acc'][-1]


# In[ ]:


# The Expected output: "Reached 99.9% accuracy so cancelling training!""
train_happy_sad_model()

 

 

반응형