with fluid.dygraph.guard(place):
# 创建一个用于情感分类的网络实例,sentiment_classifier
sentiment_classifier = SentimentClassifier("sentiment_classifier", embedding_size, num_steps=max_seq_len)
# 创建优化器AdamOptimizer,用于更新这个网络的参数
adam = fluid.optimizer.AdamOptimizer(learning_rate=learning_rate, parameter_list=sentiment_classifier.parameters())
# 定义优化算法,这里使用随机梯度下降-SGD
# 学习率设置为0.01
# opt = fluid.optimizer.SGD(learning_rate=learning_rate)
for n in range(epoch_num):
sentiment_classifier.train()
for sequences, labels in train_data_readr(batch_size):
sequences_var = fluid.dygraph.to_variable(sequences)
labels_var = fluid.dygraph.to_variable(labels)
pred, loss = sentiment_classifier(sequences_var, labels_var)
# print(loss)
# print(np.array(sequences_var))
# print(labels_var)
# print(pred)
# print(loss)
loss.backward()
adam.minimize(loss)
sentiment_classifier.clear_gradients()
step += 1
if step % 10 == 0:
print("step %d, loss %.5f, epoch_num: %d" % (step, loss.numpy()[0], n))
# 我们希望在网络训练结束以后评估一下训练好的网络的效果
# 通过eval()函数,将网络设置为eval模式,在eval模式中,网络不会进行梯度更新
sentiment_classifier.eval()
参考这个https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/dygraph_cn/save_dygraph_cn.html