首页 > 解决方案 > 向 ApplyGradientDescent 提供可变 alpha(学习率)

问题描述

这是创建变量、为其创建渐变并使用 ApplyGradientDescent 创建渐变更新操作的最小示例

auto w = Variable(scope, { 3 }, DT_FLOAT);

std::vector<Output> grad_outputs;
TF_CHECK_OK(AddSymbolicGradients(scope, { loss }, { w }, &grad_outputs));

auto apply_w1 = ApplyGradientDescent(scope, w, Cast(scope, 0.01, DT_FLOAT), { grad_outputs[0] });

然而,我真正想要的是有一个可变的学习率,我可以从图外部更新它,同时避免每次都在图上创建新的梯度操作......因此:

auto ph = Placeholder(scope, DT_FLOAT));
auto var = Variable(scope, {1}, DT_FLOAT));
auto assignVar = Assign(scope, var, ph));

Tensor newLr(DT_FLOAT, TensorShape({1}));
newLr.flat<float>().data()[0] = 0.001;

TF_CHECK_OK(session->Run({{ph, newLr}}, {assignVar}, nullptr));

auto apply = ApplyGradientDescent(scope, w, var, { grad_outputs[0] });

问题是上面失败了,因为 ApplyGradientDescent 期望 Scalar 作为 alpha,我不明白。有没有办法解决?

标签: c++tensorflow

解决方案


推荐阅读