梯度爆炸問題
在影片練習中,你學到了在處理 RNN 模型時可能出現的兩個問題:梯度消失與梯度爆炸。
這個練習著重於梯度爆炸問題,會示範函式的導數如何可能呈指數成長,以及如何用一個簡單技巧來解決它。
資料已經載入為環境中的 X_train、X_test、y_train 和 y_test。
你將使用隨機梯度下降(Stochastic Gradient Descent,SGD)最佳化器,以及均方誤差(Mean Squared Error,MSE)作為損失函式。
第一步,你會透過在訓練集與測試集上計算 MSE 來觀察梯度爆炸。第 2 步,你會在最佳化器中使用 clipvalue 參數來解決這個問題。
Keras 中的隨機梯度下降已可透過 SGD 載入。
本練習屬於課程
使用 Keras 建立語言模型的循環神經網路(RNN)
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create a Keras model with one hidden Dense layer
model = Sequential()
model.add(Dense(25, input_dim=20, activation='relu', kernel_initializer=he_uniform(seed=42)))
model.add(Dense(1, activation='linear'))
# Compile and fit the model
model.compile(loss='mean_squared_error', optimizer=____(learning_rate=0.01, momentum=0.9))
history = model.fit(X_train, y_train, validation_data=(____, ____), epochs=100, verbose=0)
# See Mean Square Error for train and test data
train_mse = model.____(X_train, y_train, verbose=0)
test_mse = model.evaluate(X_test, y_test, verbose=0)
# Print the values of MSE
print('Train: %.3f, Test: %.3f' % (____, ____))