AI/DeepLearning

multi-input & Concatenate layer / Add layer

oaho 2023. 3. 6. 02:31
반응형
Modeling : multi-input & Concatenate layer

 

💡 Setosa, Versicolor, Virginica 품종을 예측하기 

 

 

 

꽃잎, 꽃받침의 Length, Width 의 특징으로 품종을 구별한다.

-> train 데이터를 Length, Width끼리 묶는다.

 

 

 

모델링 과정

 

🔸 Length끼리, Width끼리

train_x_length = train_x.loc[:, ['sepal length', 'petal length']]
train_x_width = train_x.loc[:, ['sepal width', 'petal width']]

test_x_length = test_x.loc[:, ['sepal length', 'petal length'] ]
test_x_width = test_x.loc[:, ['sepal width', 'petal width'] ]

 

🔸 One-hot Encoding

train_y = to_categorical(train_y, 3)
test_y = to_categorical(test_y, 3)
 

🔸 모델링

# 세션 클리어
keras.backend.clear_session()

# 레이어 사슬 처럼 엮기
il_ㅣ = keras.layers.Input(shape=(2, ), name='inputLength')
il_w = keras.layers.Input(shape=(2, ), name='inputWidth)

hl_l = keras.layers.Dense(4, activation='relu', name='hiddenLength')(il_l)
hl_w = keras.layers.Dense(4, activation='relu', name='hiddenWidth')(il_w)

cl = keras.layers.Concatenate()[hl_l, hl_w)
ol = keras.layers.Dense(3, activation='softmax')(cl)

# 모델 시작 끝 지정
model = keras.models.Model([il_l, il_w], ol)

# 컴파일
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer='adam')

 

 

 

 

Modeling : multi-input & Concatenate layer

 

 

꽃잎(Petal), 꽃받침(Sepal)별 길이, 넓이의 특징으로 품종을 예측한다.

 

 

 

모델링 과정

 

🔸 Sepal끼리, petal끼리 trainset, testset

train_x_se = x_train.loc[ : ,['sepal length', 'sepal width']  ]
train_x_pe = x_train.loc[ : ,['petal length', 'petal length'] ]

test_x_se = x_test.loc[ : ,['sepal length', 'sepal width']  ]
test_x_pe = x_test.loc[: ,['petal length', 'petal length'] ]

 

🔸 one-hot Encoding 

train_y = to_categorical(train_y, 3)
test_y = to_categorical(test_y, 3)

 

🔸 모델링

keras.backend.celsr_session()

il_se = keras.layers.Input(shape=(2,))
il_pe = keras.layers.Input(shape=(2,))

hl_se = keras.layers.Dense(4, activation='relu', name='hl_sepal')(il_se)
hl_pe = keras.layers.Dense(4, activation='relu', name='hl_petal')(il_pe)

add_l = keras.layers.Add()([hl_se, hl_pe])
ol = keras.layers.Dense(3, activation='softmax')(add_l)

model = keras.models.Model([il_se, il_pe], ol)

model.compile(loss='categorical_crossentropy', metrics=['accurcay'], optimizer='adam')

 

 

🔸 학습시키기

from tensorflow.keras.callbacks import EarlyStopping

es = EarlyStopping(monitor = 'val_loss',
				   min_delta = 0,
                   patience = 5,
                   verbose = 1,
                   restore_best_weights=True)
                   
model.fit([tr_x_se, tr_x_pe], y_train, validation=0.2, epochs=10000, verbose=1, callbacks=[es])

 

🔸 예측하기

y_pred = model.predict([te_x_se, te_x_pe])
반응형