Mxnet 元素明智的相乘
Mxnet element wise multiply
在 MXNet 中,如果我想创建一个权重向量来乘以每个输入,即 w*x_i
然后反向传播权重 w
我该怎么做?
我试过了:
y_hat = input
w1 = mx.sym.Variable("w1")
y_hat = mx.symbol.broadcast_mul(w1, y_hat)
您可以根据点积进行计算:
x = mx.nd.array([[1, 2, 3], [4, 5, 6]])
w = mx.nd.array([2,2,2])
mx.nd.dot(w, x.T)
将如您所愿得到 [12. 30.]。
现在只需随机初始化 w
,计算输出与目标输出之间的损失,然后反向传播。您可以为此使用新的 gluon
界面 (http://gluon.mxnet.io/)。
具体来说,让我们看一个改编的最小示例 http://mxnet.io/tutorials/gluon/gluon.html and http://gluon.mxnet.io/P01-C05-autograd.html
准备数据
label = mx.nd.array([12,30])
x = mx.nd.array([[1, 2, 3], [4, 5, 6]])
w = random weights
w.attach_grad()
然后训练
with autograd.record():
output = mx.nd.dot(w, x.T)
loss = gluon.loss.L2Loss(output, label)
loss.backward()
不要忘记 updating the weights 您在向后传递中计算的梯度。渐变将在 w.grad
中可用。 运行 训练代码和循环中的权重更新作为单个更新可能不足以收敛。
在 MXNet 中,如果我想创建一个权重向量来乘以每个输入,即 w*x_i
然后反向传播权重 w
我该怎么做?
我试过了:
y_hat = input
w1 = mx.sym.Variable("w1")
y_hat = mx.symbol.broadcast_mul(w1, y_hat)
您可以根据点积进行计算:
x = mx.nd.array([[1, 2, 3], [4, 5, 6]])
w = mx.nd.array([2,2,2])
mx.nd.dot(w, x.T)
将如您所愿得到 [12. 30.]。
现在只需随机初始化 w
,计算输出与目标输出之间的损失,然后反向传播。您可以为此使用新的 gluon
界面 (http://gluon.mxnet.io/)。
具体来说,让我们看一个改编的最小示例 http://mxnet.io/tutorials/gluon/gluon.html and http://gluon.mxnet.io/P01-C05-autograd.html
准备数据
label = mx.nd.array([12,30])
x = mx.nd.array([[1, 2, 3], [4, 5, 6]])
w = random weights
w.attach_grad()
然后训练
with autograd.record():
output = mx.nd.dot(w, x.T)
loss = gluon.loss.L2Loss(output, label)
loss.backward()
不要忘记 updating the weights 您在向后传递中计算的梯度。渐变将在 w.grad
中可用。 运行 训练代码和循环中的权重更新作为单个更新可能不足以收敛。