본문 바로가기

공부/프로그래밍

딥러닝 Tensorflow | Optimization, Training with Keras

728x90
2021-02-03

Optimization

모델학습 전에 설정한다.

  • Loss function
  • Optimization
  • Metrics

Loss function

  • binary (단 2개일 때)
  • categorical (2개 이상 클래스 사용시)
    • loss = 'binary_crossentropy'
    • loss = 'categorical_crossentropy'

categorical 사용 기준

  • one hot 설정했다 -> tf.keras.losses.sparse_categorical_crossentropy
  • 설정 안했다 -> tf.keras.losses.categorical_crossentropy
In [39]:
loss_func = tf.keras.losses.sparse_categorical_crossentropy
#one hot 인코딩을 안할거라서 이걸로 선택한다.

Metrics

  • 모델 평가 방법
In [41]:
metrics = ['accuracy']
metrics = [tf.keras.metrics.Accuracy()]
#두가지 form으로 설정할 수 있다.
#accuracy 외에도 다양한 방법 있음.

Optimizer

In [42]:
optm = tf.keras.optimizers.Adam()
#다른방식도 있음

compile

In [43]:
model.compile(optimizer=optm, loss=loss_func, metrics=metrics)
#metrics는 리스트로 입력할 수 있다. 여러 평가방법을 사용하고 싶을때

적용: mnist dataset

In [44]:
(train_x, train_y), (test_x, test_y) = datasets.mnist.load_data()

shape 확인

In [45]:
train_x.shape, train_y.shape
#x 색상이 gray라 색상채널이 없다. 늘려줘야함
Out[45]:
((60000, 28, 28), (60000,))
In [46]:
test_x.shape, test_y.shape
Out[46]:
((10000, 28, 28), (10000,))

필요한 만큼 차원 수 늘리기

In [47]:
import numpy as np
np.expand_dims(train_x, -1).shape
#numpy 사용
Out[47]:
(60000, 28, 28, 1)
In [48]:
tf.expand_dims(train_x, -1).shape
#tensorflow 사용
Out[48]:
TensorShape([60000, 28, 28, 1])
In [49]:
train_x = train_x[... , tf.newaxis]
test_x = test_x[... , tf.newaxis]
#tensorflow 유용한 방식. 이걸로 쓰자.

shape 확인

In [50]:
train_x.shape, test_x.shape
Out[50]:
((60000, 28, 28, 1), (10000, 28, 28, 1))

Rescaling: 0~1 사이의 값으로 해준다. 학습이 너무 튀지 않게.

In [51]:
np.min(train_x), np.max(train_x)
Out[51]:
(0, 255)
In [52]:
train_x = train_x / 255.
test_x = test_x / 255.
In [53]:
np.min(train_x), np.max(train_x)
#0~1 사이로 바뀌었다.
Out[53]:
(0.0, 1.0)

Training

  • 학습용 hyperparameter 설정
    • num_epochs (= n 회독)
    • batch_size (1회독 당 학습시키는 데이터수, 메모리 효율때문에 제한해야함)
In [54]:
num_epochs = 1
batch_size = 32
  • model설정 -> model compile -> model fit 설정 마무리 단계
In [55]:
model.fit(train_x, train_y, 
          batch_size=batch_size, 
          shuffle=True, 
          epochs=1)
1875/1875 [==============================] - 254s 135ms/step - loss: 0.1306 - accuracy: 0.9586
Out[55]:
<tensorflow.python.keras.callbacks.History at 0x1f218d45b88>
반응형