A Neural Network Playground - TensorFlow : https://bit.ly/487HdL1
반복(epoch)가 많으면 과적합 될 수 있음
val error가 더이상 줄 지 않으면 멈춰라 : Early Stopping
일반적으로 train error는 계속 줄어 듦
Early stopping 옵션
from keras.callbacks import EarlyStopping
es = EarlyStopping(monitor = 'val_loss', min_delta = 0, patience = 0)
model.fit(x_train, y_train, epochs = 100, validation_split = .2, callbacks = [es])
과적합을 줄이기 위해 사용되는 규제regularization 기법 중 하나
학습시, 신경망의 일부 뉴런을 읨이로 비활성화 -> 모델을 강제로 일반화
절차
# hidden layer 노드 중 40%를 임의로 제외 시킴
# 보통 0.2~0.5 사이의 범위 지정
model3 = Sequential( [Input(shape = (nfeatures,)),
Dense(128, activation= 'relu'),
Dropout(0.4),
Dense(64, activation= 'relu'),
Dropout(0.4),
Dense(32, activation= 'relu'),
Dropout(0.4),
Dense(1, activation= 'sigmoid')] )
model.save('파일이름.keras')
from keras.models import load_model
model2 = load_model('파일이름.keras')
from keras.callbacks import ModelCheckpoint
cp_path = '/content/{epoch:03d}.keras' # Keras 2.11 이상 버전에서 모델 확장자 .keras
mcp = ModelCheckpoint(cp_path, monitor='val_loss', verbose = 1, save_best_only=True)
# 학습
hist = model1.fit(x_train, y_train, epochs = 50, validation_split=.2, callbacks=[mcp]).history
clear_session()
il = Input(shape=(nfeatures, ))
hl1 = Dense(18, activation='relu')(il)
hl2 = Dense(4, activation='relu')(hl1)
ol = Dense(1)(hl2)
model = Model(inputs = il, outputs = ol)
model.summary()
# 모델 구성
# name 은 생략 가능
input_1 = Input(shape=(nfeatures1,), name='input_1')
input_2 = Input(shape=(nfeatures2,), name='input_2')
# 첫 번째 입력을 위한 레이어
hl1_1 = Dense(10, activation='relu')(input_1)
# 두 번째 입력을 위한 레이어
hl1_2 = Dense(20, activation='relu')(input_2)
# 두 히든레이어 결합 (리스트로)
cbl = concatenate([hl1_1, hl1_2])
# 추가 히든레이어
hl2 = Dense(8, activation='relu')(cbl)
# 출력 레이어
output = Dense(1)(hl2)
# 모델 선언(리스트)
model = Model(inputs = [input_1, input_2], outputs = output)
model.summary()
# 학습
hist = model.fit([x_train1, x_train2], y_train, epochs=50, validation_split=.2).history
#예측
pred = model.predict([x_val1, x_val2])
<절차>
1. 데이터 분할 1:x,y
2. 스케일링
2차원 데이터셋(X) -> timesteps 단위로 잘라서
(한칸 씩 밀면서)
+) 만약 RNN Layer을 중첩해서 hidden layer을 만들려면,
마지막 output layer 바로 전이 아닌이상, return_sequences =True 로 시계열을 유지하여 넘겨야 한다.
1)🌟 y 만들기
data['y'] = data['AvgTemp'].shift(-1)
data.dropna(axis = 0, inplace = True)
data.head()
2) x,y 분리
x = data.loc[:, ['AvgTemp']]
y = data.loc[:,'y']
3) 스케일링
scaler = MinMaxScaler()
x = scaler.fit_transform(x)
4) 🌟3차원 구조 만들기
# 4주간의 데이터가 한 단위
x2, y2 = temporalize(x, y, 4)
x2.shape, y2.shape
5) 데이터 분할
# shuffle=False : 랜덤 분할하지 마라
# test_size = 숫자 : 데이터 건수 (끝에서부터)
# 53은 1년치 데이터
x_train, x_val, y_train, y_val = train_test_split(x2, y2, test_size= 53, shuffle = False)
# 분석 단위 2차원 (timesteps, nefeatures)
timesteps = x_train.shape[1]
nfeatures = x_train.shape[2]
2) 🌟모델 구조 설계
clear_session()
model = Sequential([Input(shape = (timesteps, nfeatures)),
SimpleRNN(8), # 4*8
Dense(1)]) # 1
model.summary()
3) 컴파일 및 학습
model.compile(optimizer = Adam(0.01), loss = 'mse')
hist = model.fit(x_train, y_train, epochs = 100, verbose = 0, validation_split = .2).history
4) 예측 및 평가
# 예측
pred = model.predict(x_val)
# 평가
mean_absolute_error(y_val, pred)
5) 시각화
plt.figure(figsize = (10,6))
plt.plot(y_val, label = 'actual')
plt.plot(pred, label = 'predicted')
plt.legend()
plt.grid()
plt.show()
LSTM 구조 : time step 간에 두 종류의 상태 값 업데이트 관리