multi-class 모델을 위한 수정
1. ImageDataGenerator for multi-class
- class_mode를 'categorical'로 수정한다.
- (이진 분류일 경우에는 'binary'로 설정했었다.)
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
train_dir,
target_size=(300, 300),
batch_size=128,
class_mode='categorical' # multi-class classification이므로 'binary'가 아니라 'categorical'
)
2. Model for multi-class
- 마지막 layer의 output 노드의 수를 class의 수와 동일하게 설정해준다.
- 그리고 activation function으로는 softmax를 사용한다.
- 이진분류 문제에서는 tf.keras.layers.Dense(1, activation='sigmoid')로 해주었다.
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3, 3), activation='relu', input_shape=(300, 300, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(32, (3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(64, (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(3, activation='softmax') # 여기를 수정해주어야 한다.
# 3 = class의 수
# activation은 sigmoid가 아니라 softmax
])
3. compile for multi-class
- loss로 'sparse_categorical_crossentropy' 혹은 'categorical_crossentropy'를 사용한다.
- target이 one-hot encoding되어 있다면 categorical_crossentropy를 사용하고,
- 그렇지 않다면 sparse_categorical_crossentropy를 사용하면 된다.
from tensorflow.keras.optimizers import RMSprop
model.compile(
loss='categorical_crossentropy', # not binary_crossentropy but categorical_crossentropy
optimizer=RMSprop(lr=0.001),
metrics=['acc']
)
'🙂 > Coursera_TF' 카테고리의 다른 글
WEEK2 : NLP in Tensorflow (Embedding) (0) | 2021.01.11 |
---|---|
WEEK1 : NLP in Tensorflow (Tokenizer, OOV token, pad_sequences) (0) | 2021.01.11 |
WEEK3 : CNN in TensorFlow (transfer learning, dropout) (0) | 2021.01.10 |
WEEK2 : CNN in TensorFlow (data augmentation) (0) | 2021.01.10 |
WEEK1 : CNN in TensorFlow (Cats and Dogs) (0) | 2021.01.10 |