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

han811·2020년 11월 8일
0
post-thumbnail

2주차 강의에서는 fashion_mnist를 이용한 convolutional neural network를 학습하는 과정으로 진행되었다.

첫번째 주피터 파일

import tensorflow as tf
import numpy as np

mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()

tf.keras.datasets에 기본적으로 자주 사용되는 데이터셋의 url과 관련된 클래스가 존재한다.
원하는 데이터셋 객체를 생성하고 load_data()를 해주면 train test 데이터셋이 이쁘게 다운된다. 데이터는 numpy array의 형태이다.

model = tf.keras.models.Sequential([tf.keras.layers.Flatten(), 
                                    tf.keras.layers.Dense(128, activation=tf.nn.relu), 
                                    tf.keras.layers.Dense(10, activation=tf.nn.softmax)])
                                    
model.compile(optimizer = tf.optimizers.Adam(),
              loss = 'sparse_categorical_crossentropy',
              metrics=['accuracy'])

위와 같이 evaluation metrics는 compile단계에서 진행이 됨을 볼 수 있다.
compile에서 loss와 optimizer 그리고 evaluation metrics까지 정해준다.

model.fit(training_images, training_labels, epochs=5)

model.evaluate(test_images, test_labels)

evaluate 메서드를 이용하면 기본적으로 test셋의 loss를 반환해줄 뿐 아니라 evaluation metrics값도 반환이 된다.

단위 데이터에 대한 예측값을 알고싶으면 model.predict(~데이터~)해주면 된다.

두번째 주피터 파일

import tensorflow as tf
print(tf.__version__)

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

이처럼 tf.keras.callbacks.Callback클래스를 상속받아 on_epoch_end라는 새로운 메서드를 오버라이딩해주면 매 에폭이 끝날때마다 해당 메서드를 수행한다.
이때 인자를 logs={}를 주면 해당 log.get('loss')의 경우 loss값이 만약 metrics로 ['accuracy']등으로 해주었다면 'acc'의 accuracy값을 얻을 수 있다.
정 목록을 모르겠으면 print(logs)를 해줘서 출력하면 dictionary 형태로 값을 뽑아볼 수 있다.

callbacks = myCallback()
mnist = tf.keras.datasets.fashion_mnist
(training_images, training_labels), (test_images, test_labels) = mnist.load_data()
training_images=training_images/255.0
test_images=test_images/255.0
model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.optimizers.Adam(), loss='sparse_categorical_crossentropy')
model.fit(training_images, training_labels, epochs=5, callbacks=[callbacks])
history = model.fit(# YOUR CODE SHOULD START HERE
              x_train,
              y_train,
              epochs=10,
              callbacks=[callbacks]
              # YOUR CODE SHOULD END HERE
    )

만약 위에처럼 fit한 모델을 변수에 지정해주면 해당 변수로 epoch과 history 딕셔너리를 통해 loss와 accuracy같은 evaluation metrics에 접근 가능하다.

history.epoch, history.history['acc'][-1]

이참에 파이썬 f-formatting 과 os 모듈에 대해서도 짚어보고 넘어가자
파이썬 f포멧팅은 기존의 format과 %와 달리 훨씬 간단하게 문자열을 포멧팅 할 수 있다.

from os import path, getcwd, chdir
path = f"{getcwd()}/../tmp2/mnist.npz"

{}안에 getcwd() 즉 현재 경로가 들어간다.

os.getcwd() - 현재 경로 반환
os.listdir(~) - ~에 아무것도 없을시 현재경로내의 모든 파일 목록 리스트로 반환 / 만약 값이 있다면 해당 경로내의 모든 파일 목록 리스트로 반환
os.chdir(~) - ~로 디렉토리 경로를 변경합니다
os.path.abspath(~) - ~의 절대 경로 얻기
os.path.dir(~) - ~의 경로 중 디렉토리명만 얻기
os.path.basename(~) - ~의 경로 중 파일명만 얻기
os.path.exists(~) - ~파일 혹은 디렉토리가 존재하는지 체크
os.path.isdir(~) - ~디렉토리가 존재하는지 체크
os.path.isfile(~) - ~파일이 존재하는지 체크

https://github.com/han811/tensorflow

profile
han811

0개의 댓글