def build_model():
    model = Sequential()
    model.add(Dense(units = 4, activation = 'relu', input_shape = (8, )))
    model.add(Dense(units = 20, activation = 'relu'))
    model.add(Dense(units = 10, activation = 'relu'))
    model.add(Dense(units = 1, activation = 'linear'))

    # 옵티마이저의 learning rate를 설정하는 방법
    model.compile(tf.keras.optimizers.RMSprop(learning_rate = 0.001), loss = 'mse', metrics = ['mse', 'mae'])
    #model.compile('adam', 'mse')
    return model

model = build_model()
early_stop = tf.keras.callbacks.EarlyStopping(monitor = 'val_loss', patience = 10)
epoch_history = model.fit(X_train, y_train, epochs = 100000, validation_split = 0.2, callbacks = [early_stop])
# 콜백이란?? 프레임워크가 실행하는 코드. 코드 실행을 프레임워크에 맡기는 것

monitor 파라미터에는 감시할 평가 데이터를 대입하고 patience에는 몇번 동안 개선이 없으면 학습을 중단할 건지 대입한다. 이걸 fit의 callbacks에 배열로 대입하면 된다.epochs에 십만을 대입했지만 실제로는 200번대 에서 중단했다.

 

def build_model():
    model = Sequential()
    model.add(Dense(units = 4, activation = 'relu', input_shape = (8, )))
    model.add(Dense(units = 20, activation = 'relu'))
    model.add(Dense(units = 10, activation = 'relu'))
    model.add(Dense(units = 1, activation = 'linear'))

    # 옵티마이저의 learning rate를 설정하는 방법
    model.compile(tf.keras.optimizers.RMSprop(learning_rate = 0.001), loss = 'mse', metrics = ['mse', 'mae'])
    #model.compile('adam', 'mse')
    return model
    
model = build_model()
epoch_history = model.fit(X_train, y_train, epochs = 1000, validation_split = 0.2)

Validation set(검정 데이터)은 training set으로 만들어진 모델의 성능을 측정하기 위해 사용된다. 일반적으로 어떤 모델이 가장 데이터에 적합한지 찾아내기 위해서 다양한 파라미터와 모델을 사용해보게 되며, 그 중 validation set으로 가장 성능이 좋았던 모델을 선택한다. validation_split이 0.2면 학습데이터의 20프로를 에포크 한번 끝날 때마다 오차를 측정하는 데 쓴다.

 

def build_model():
    model = Sequential()
    model.add(Dense(units = 4, activation = 'relu', input_shape = (8, )))
    model.add(Dense(units = 20, activation = 'relu'))
    model.add(Dense(units = 10, activation = 'relu'))
    model.add(Dense(units = 1, activation = 'linear'))

    # 옵티마이저의 learning rate를 설정하는 방법
    model.compile(tf.keras.optimizers.RMSprop(learning_rate = 0.001), loss = 'mse', metrics = ['mse', 'mae'])
    #model.compile('adam', 'mse')
    return model

위 코드처럼 컴파일 할 때 라이브러리로 옵티마이저를 불러오고 하이퍼 파라미터 learning_rate에 값을 대입한다.

from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from keras.models import Sequential
from keras.layers import Dense

def build_classifier(optimizer):
    # 모델링
    model = Sequential()
    model.add(Dense(units = 6, activation = 'relu', input_shape = (11,)))
    model.add(Dense(units = 6, activation = 'relu'))
    model.add(Dense(units = 1, activation = 'sigmoid'))
    model.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy'])
    return model
    
model = KerasClassifier(build_fn = build_classifier)
my_parameters = {'epochs':[30, 50], 'batch_size':[10,20], 'optimizer':['adam', 'rmsprop']}
grid_search = GridSearchCV(estimator = model, param_grid = my_parameters, scoring = 'accuracy')
grid_search.fit(X_train, y_train)

KerasClassifier와 GridSearchCV를 import한다

build_fn을 작성하고 대입한다.

하이퍼 파라미터들을 딕셔너리 형태로 만들고 대입한다

 

 
grid_search.best_params_
grid_search.best_score_
model2 = grid_search.best_estimator_
grid_search.best_params_는 최고의 파라미터를 딕셔너리로 리턴하고
grid_search.best_score_는 최고의 모델의 평가 점수를 리턴한다 위의경우 accuracy 정확도이다.
model2는 최적의 모델 그 자체이다.

 

먼저 데이터를 전처리하고 모델링 한다.

import tensorflow.keras
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import MinMaxScaler

def build_model():
    model = Sequential()
    model.add(Dense(units = 5, activation = 'relu', input_shape = (5, )))
    model.add(Dense(units = 25, activation = 'relu'))
    model.add(Dense(units = 10, activation = 'relu'))
    model.add(Dense(units = 1, activation = 'linear'))
    model.compile('adam', 'mse')
    return model

model = build_model()

마지막 레이어는 활성함수를 linear로 해줘야하고 compile loss 는 mse로 정해준다

epoch_history = model.fit(X_train, y_train, epochs = 20, batch_size = 10)
y_pred = model.predict(X_test)

# mse 계산
((y_test - y_pred) ** 2).mean()

# 예측 데이터 되돌리기
sc_y.inverse_transform(y_pred)

모델 학습을 시키고 예측을 한뒤 mse 측정을 한다.

inverse_transform으로 원래 단위로 되돌릴 수 있다.

준비된 데이터는 아래와 같다.

 

import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(units = 6, activation = 'relu', input_shape = (11,)))
model.add(Dense(units = 8, activation = tf.nn.relu))
model.add(Dense(units = 1, activation = 'sigmoid'))
model.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

input_shape는 X_train의 열 개수만큼 넣고 히든 레이어를 작성한 후 마지막을 sigmoid 활성함수로 지정한다.

손실함수는 binary_crossentropy 평가방법은 accuracy로 정한다.

model.fit(X_train, y_train, epochs = 20, batch_size = 10)
y_pred = model.predict(X_test)
y_pred = (y_pred > 0.5).astype(int)
cm = confusion_matrix(y_test, y_pred)

모델 학습시킨후 예측한 뒤 0과1로 바꿔주고 confusion_matrix를 살펴본다

fit(x=None, y=None, batch_size=None, epochs=1, verbose=1, callbacks=None, validation_split=0.0, validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, steps_per_epoch=None, validation_steps=None)
  • batch_size: 정수 혹은 None. 경사 업데이트 별 샘플의 수. 따로 정하지 않으면 batch_size는 디폴트 값인 32가 됩니다.
  • epochs: 정수. 모델을 학습시킬 세대의 수. 한 세대는 제공된 모든 x와 y 데이터에 대한 반복입니다. initial_epoch이 첫 세대라면, epochs은 "마지막 세대"로 이해하면 됩니다. 모델은 epochs에 주어진 반복의 수만큼 학습되는 것이 아니라, 단지 epochs 색인의 세대에 도달할 때까지만 학습됩니다.

 

+ Recent posts