반응형
다중출력모델을 만들고 학습시킬 때, input 하나 당 y 값을 복수개를 지정해주어야 한다.
DataGenerator를 커스텀해서 이용할 수도 있지만
가장 간단한 방법으로 Tensorflow에 이미 만들어져있는 기능을 사용했다.
< Sample Model>
inputs = keras.Input(shape=(320, 320, 3), name="strawberry")
x = layers.Conv2D(16, 3, activation="relu")(inputs)
x = layers.Conv2D(32, 3, activation="relu")(x)
x = layers.MaxPooling2D(3)(x)
x = layers.Flatten()(x)
x = layers.Dropout(0.5)(x)
x = layers.Dense(32, activation='relu')(x)
a_out = layers.Dense(df['area'].nunique(), name='a', activation='softmax')(x)
g_out = layers.Dense(1, name='g', activation='sigmoid')(x)
d_out = layers.Dense(df['disease'].nunique(), name='d', activation='softmax')(x)
model = keras.Model(inputs, [a_out, d_out, g_out], name="multiOut")
Model: "multiOut"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
strawberry (InputLayer) [(None, 320, 320, 3 0 []
)]
conv2d_2 (Conv2D) (None, 318, 318, 16 448 ['strawberry[0][0]']
)
conv2d_3 (Conv2D) (None, 316, 316, 32 4640 ['conv2d_2[0][0]']
)
max_pooling2d_1 (MaxPooling2D) (None, 105, 105, 32 0 ['conv2d_3[0][0]']
)
flatten_1 (Flatten) (None, 352800) 0 ['max_pooling2d_1[0][0]']
dropout_1 (Dropout) (None, 352800) 0 ['flatten_1[0][0]']
dense_1 (Dense) (None, 32) 11289632 ['dropout_1[0][0]']
a (Dense) (None, 3) 99 ['dense_1[0][0]']
d (Dense) (None, 5) 165 ['dense_1[0][0]']
g (Dense) (None, 1) 33 ['dense_1[0][0]']
==================================================================================================
Total params: 11,295,017
Trainable params: 11,295,017
Non-trainable params: 0
__________________________________________________________________________________________________
< 사용한 데이터>
사용할 데이터에 이미지 경로, 라벨 등 정보가 모두 저장되어있다.
< ImageDataGenerator 사용 예시>
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
train_gen = ImageDataGenerator(rescale=1./255,
rotation_range=20,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
fill_mode='nearest')
valid_gen = ImageDataGenerator(rescale= 1. /255.)
train_generator = train_gen.flow_from_dataframe(train_df,
x_col='image',
y_col=['area', 'disease', 'grow'],
target_size=(IMAGE_SIZE, IMAGE_SIZE),
class_mode='multi_output', ######class mode######
batch_size=BATCH_SIZE)
valid_generator = valid_gen.flow_from_dataframe(valid_df,
x_col='image',
y_col=['area','disease','grow'],
target_size=(IMAGE_SIZE, IMAGE_SIZE),
class_mode='multi_output', ######class mode######
batch_size=BATCH_SIZE)
[flow_from_dataframe]
### Tensorflow API ###
flow_from_dataframe(
dataframe,
directory=None,
x_col='filename',
y_col='class',
weight_col=None,
target_size=(256, 256),
color_mode='rgb',
classes=None,
class_mode='categorical',
batch_size=32,
shuffle=True,
seed=None,
save_to_dir=None,
save_prefix='',
save_format='png',
subset=None,
interpolation='nearest',
validate_filenames=True,
**kwargs
)
x_col : x 데이터 컬럼명
y_col : y 데이터 컬럼명
사용한 데이터의 경우 이미지 파일명이 아니라 경로가 저장되어있어서 directory 옵션을 주지않았는데,
만약 이미지 파일명으로 저장되어있는 경우 directory에 이미지가 저장되어있는 경로를 지정하면 그 경로에서 이미지를 불러온다.
멀티아웃풋으로 사용하기 위해서 가장 중요한 부분은,
class_mode 이다.
class_mode를 multi_output으로 지정하고 y_col에 y데이터 컬럼들을 리스트 형태로 지정하면 된다.
class_mode에는 다양한 옵션이 있다.
- categorical : default, 원핫인코딩이 되어있는 2차원 배열, multi-label output
- binary : 이진분류
- sparse : 다중분류이지만 원핫인코딩이 되어있지 않는 라벨.
- raw : y 컬럼의 값 그대로
- None : y값이 리턴되지 않음.
> 자세한 내용
tf.keras.preprocessing.image.ImageDataGenerator | TensorFlow Core v2.9.1
Generate batches of tensor image data with real-time data augmentation.
www.tensorflow.org
< Model 컴파일 및 학습>
model.compile(loss={ 'a' : 'sparse_categorical_crossentropy',
'g' : 'binary_crossentropy',
'd' : 'sparse_categorical_crossentropy'},
optimizer=Adam(learning_rate=1e-4),
metrics=['accuracy'])
model.fit(train_generator,
validation_data=valid_generator,
epochs=EPOCHS,
verbose=1,
steps_per_epoch = len(train_df)//BATCH_SIZE)
반응형
'Programming > Tensorflow' 카테고리의 다른 글
[Tensorflow 1.15] 이미지 Convolution, Pooling의 결과 확인하기 (0) | 2022.04.14 |
---|---|
[Tensorflow 1.15 ] Convolution 연산 - Sample Case (2) | 2022.04.14 |
[Tensorflow] MNIST DNN으로 구현해보기 (0) | 2022.04.12 |
[Tensorflow] 학습한 모델 저장하기 (0) | 2022.04.07 |
[Tensorflow] Tensorflow 2.xx with Keras (0) | 2022.04.07 |