2024년 4월 10일 수요일

LSTM 에서 model.train_on_batch(xs, ys) 와 model.reset_states()

 Python3.8 에서 돌아가는 TensorFlow 2.6 이전버전에는

# 모델을 정의합니다.
model = keras.Sequential([
keras.layers.LSTM(128, batch_input_shape=(1, 1, 45), 
        return_sequences=False, stateful=True),
keras.layers.Dense(45, activation='sigmoid')])


한다음
# 모델을 컴파일합니다.
model.compile(loss='binary_crossentropy', optimizer='adam'
    metrics=['accuracy'])


# 최대 100번 에포크까지 수행
for epoch in range(irepeat):
model.reset_states() # 중요! 매 에포크마다 1회부터 다시 훈련하므로 상태 초기화 필요
for i in range(train_idx[0], train_idx[1]):
xs = x_samples[i].reshape(1, 1, 45)
ys = y_samples[i].reshape(1, 45)
loss, acc = model.train_on_batch(xs, ys) # 배치만큼 모델에 학습시킴

와 같이 하면 가능했으나

Python3.10에서 돌아가는 TensorFlow 2.6 부터는

Unrecognized keyword arguments passed to LSTM
    {'batch_input_shape': (1, 1, 45)}

라고 에러를 쏱아낸다.
batch_input_shape 를 input_shape 로 고쳐도 안된다.

# 최근 TensorFlow 버전에서 Sequential 객체에는 reset_states 메서드가 없습니다.
# 이 메서드는 TensorFlow 2.6 버전에서 제거되었습니다.
# 대신 다음과 같은 방법으로 상태를 초기화할 수 있습니다:
# tf.compat.v1.reset_default_graph() 사용:
# 이 함수를 호출하여 그래프의 상태를 초기화할 수 있습니다.


model = Sequential()
model.add(LSTM(512, activation='tanh',
input_shape = (1, 45),
return_sequences = False, stateful=True))
model.add(Dense(n_features, activation='relu'))
model.compile(optimizer = 'adam', loss='mse', metrics=['accuracy'])


class end_epoch(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs):
tf.compat.v1.reset_default_graph()

history =model.fit(x=X_samples, y=y_samples, batch_size=1, epochs=250
validation_split=0.15, verbose=1, shuffle=False
callbacks=[end_epoch()])

과 같은 방법으로 해결하여야 한다.

댓글 없음:

tensorflow gpu 사용하기에서

 tensorflow 설치시 주의해야 한다. # Anything above 2.10 is not supported on the GPU on Windows Native python - m pip install "tensorflow<2.11...