import tensorflow as tf
from tensorflow import keras
def build_model(n_hidden=1, n_neurons=30 , learning_rate=3e-3, input_shape=[8]):
model = keras.models.Sequential()
model.add(keras.layers.InputLayer(input_shape=input_shape))
for layer in range(n_hidden):
model.add(keras.layers.Dense(n_neurons, activation="relu"))
model.add(keras.layers.Dense(1))
optimizer = keras.optimizers.SGD(lr=learning_rate)
model.compile(loss="mse",optimizer=optimizer)
return model
#KerasRegressor
keras_reg = keras.wrappers.scikit_learn.KerasRegressor(build_model)
/usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:3: DeprecationWarning: KerasRegressor is deprecated, use Sci-Keras (https://github.com/adriangb/scikeras) instead. This is separate from the ipykernel package so we can avoid doing imports until
#캘리포니아 주택 가격 데이터 셋을 통해 예시를 살펴본다.
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
housing = fetch_california_housing()
X_train_full , X_test , y_train_full , y_test = train_test_split(
housing.data, housing.target
)
X_train, X_valid, y_train, y_valid = train_test_split(
X_train_full , y_train_full
)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_valid = scaler.transform(X_valid)
X_test = scaler.transform(X_test)
X_new =
keras_reg.fit(X_train, y_train , epochs=100,
validation_data = (X_valid , y_valid),
callbacks=[keras.callbacks.EarlyStopping(patience=10)])
mse_test = keras_reg.score(X_test,y_test)
#y_pred = keras_reg.predict(X_new)
from scipy.stats import reciprocal
from sklearn.model_selection import RandomizedSearchCV
import numpy as np
param_distribs = {
"n_hidden" : [0,1,2,3],
"n_neurons" : np.arange(1, 100),
"learning_rate" : reciprocal(3e-4,3e-2)
}
rnd_search_cv = RandomizedSearchCV(keras_reg, param_distribs, n_iter=10 , cv=3)
rnd_search_cv.fit(X_train, y_train, epochs=100,
validation_data=(X_valid, y_valid),
callbacks=[keras.callbacks.EarlyStopping(patience=10)])
rnd_search_cv.best_params_
#best parameters
rnd_search_cv.best_score_
#best score 확인 ( 음수 mse 값으로 나옴 사이킷런은 loss가 아니라 score를 계산해서)
model = rnd_search_cv.best_estimator_.model
#위와 같은 방식으로 베스트 모델을 가져울 수도 있다.