728x90
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]:
In [46]:
test_x.shape, test_y.shape
Out[46]:
필요한 만큼 차원 수 늘리기
In [47]:
import numpy as np
np.expand_dims(train_x, -1).shape
#numpy 사용
Out[47]:
In [48]:
tf.expand_dims(train_x, -1).shape
#tensorflow 사용
Out[48]:
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]:
Rescaling: 0~1 사이의 값으로 해준다. 학습이 너무 튀지 않게.
In [51]:
np.min(train_x), np.max(train_x)
Out[51]:
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]:
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)
Out[55]:
반응형
'공부 > 프로그래밍' 카테고리의 다른 글
딥러닝 Tensorflow | Perceptron (0) | 2021.02.04 |
---|---|
딥러닝 Tensorflow | Keras training model.fit() 오류 (0) | 2021.02.04 |
딥러닝 Tensorflow | fully-connected (0) | 2021.02.03 |
딥러닝 Tensorflow | layer, feature extraction - convolution (0) | 2021.02.03 |
딥러닝 Tensorflow | 방학 중 진행상황 (0) | 2021.01.24 |