开始使用免费开始使用

梯度爆炸问题

在视频练习中,您学习了在使用 RNN 模型时可能出现的两个问题:梯度消失和梯度爆炸。

本练习聚焦于梯度爆炸问题,展示函数的导数如何可能呈指数级增长,以及如何用一个简单技巧来解决它。

数据已在环境中加载为 X_trainX_testy_trainy_test

您将使用随机梯度下降(Stochastic Gradient Descent,SGD)优化器,以及均方误差(Mean Squared Error,MSE)作为损失函数。

第 1 步,您将通过在训练集和测试集上计算 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' % (____, ____))
编辑并运行代码