오답노트

[Keras] Functional API 본문

Python/DL

[Keras] Functional API

권멋져 2022. 9. 13. 21:32

Linear Regression

Sequential은 add 함수를 통해 모델에 레이어를 쌓았다면, Functional은 레이어를 변수로 만들고, 레이어간 연결을 직접 정의할 수 있다. Dense에 대한 변수를 정의할 때를 잘 살펴보자.

 

from sklearn.datasets import load_boston
boston = load_boston()

x = boston.data
y = boston.target

print(x.shape, y.shape) # (506, 13), (506,)

#모델링
# 케라스 세션 클리어
keras.backend.clear_session()

#레이어 선언
il = keras.layers.Input(shape=(1,))
ol = keras.layers.Dense(1)(il)

#모델 선언
model = keras.models.Model(il,ol)

#모델 컴파일
model.compile(loss='mse',optimizer='adam')

#모델 학습
model.fit(x,y,epochs=10,verbose=1)

#모델 예측
print(model_boston.predict(x).reshape(-1)[:5]) # [-143.90042 -128.74472 -123.72013 -115.80247 -117.86544]
print(y[:5]) # [24.  21.6 34.7 33.4 36.2]

 

Logistic Regression

from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()

x = cancer.data
y = cancer.target

print(x.shape, y.shape) # (569, 30), (569,)

#모델링
#케라스 세션 클리어
keras.backend.clear_session()

#레이어 선언
il_boston = keras.layers.Input(shape=(13,))
ol_boston = keras.layers.Dense(1)(il_boston)

#모델 선언
model_boston = keras.models.Model(il_boston,ol_boston)

#모델 컴파일
model_boston.compile(loss='mse',optimizer='adam')

#모델 학습
model_boston.fit(x,y,epochs=10,verbose=1)

#모델 예측
print(model_cancer.predict(x).reshape(-1)[:10])
# [0.0000000e+00 4.7399735e-35 1.6038484e-27 1.4171174e-01 1.9208638e-11 2.0547948e-07 5.4881117e-28 8.3965273e-13 1.2773573e-03 4.2186571e-06]
print(y[:10])
# [0 0 0 0 0 0 0 0 0 0]

'Python > DL' 카테고리의 다른 글

[Keras] EarlyStopping  (0) 2022.09.15
[Keras] Flatton Layer  (0) 2022.09.15
[Keras] ANN  (0) 2022.09.14
[Keras] MultiClass - SoftMax  (0) 2022.09.13
[Keras] Sequential API  (0) 2022.09.13