我想找出函数wrt变量T的梯度。我得到了错误操作数广播。为什么会出现此错误,以及如何修复它?L取值范围从0到4。
def grad(l,d1,d2):
grad_T = 0
b = 1
w = np.ones(5,1)
w.reshape(5,1)
T = np.random.rand(46,5)
D = np.random.rand(46,9063)
if(y[d2]!=y[d1]):
difVec = D[ : ,d2].astype(float) - D[ :,d1].astype(float)
dify = 1
if(y[d2]<y[d1]):
dify = -1
grad_T = grad_T + (-1*dify*w[l,0]*difVec)/(1+np.exp(dify(
w.transpose() @ T.transpose() @ difVec + b )))
return(grad_T)
Error
<ipython-input-40-56571fb637a5> in grad(d1, d2)
20 if(y[d2]<y[d1]):
21 dify = -1
---> 22 grad_T = grad_T +
(-1*dify*w[l,1]*difVec)/(1+np.exp(dify * ( w.transpose() @
T.transpose() @ difVec + b )))
ValueError: operands could not be broadcast together with shapes (46,)
(5,)发布于 2019-06-21 09:19:54
你好,欢迎来到SO。
首先,你的代码根本不能运行。以下是使其正常工作的修复。对于操作数广播错误,请继续执行下面的操作。
w = np.ones(5,1)) # excess right paranthesis here
# numpy.ones([5,1]) it should be a list of dimensions
w.reshape(5,1)
T.reshape(46,5) # unnecessary
D = np.random,rand(46, 9063) # random,rand
# You meant random.rand I suppose
grad_T = grad_T + b
(-1*dify*w[l,1]*difVec)/(1+np.exp(dify * ( w.transpose() @
T.transpose() @ difVec + b )))
# This here will not work w is [5,1] you cannot index w[l, 1]
# It is definitely out of bounds. You meant w[l, 0] I suppose.我让你的代码在Colab上工作。矩阵乘法的所有维度都是正确的。我摆脱了b,因为我不知道它的大小。b可能是您得到的错误的罪魁祸首。如果去掉b,您的提名符的形状为(46,),您的分母为(1,)。您得到的错误可能是因为b的形状为(5,)。因为你的w是5,1,我想你的偏差(b)是相同的维度。所以索引b矩阵就可以解决你的问题了。
https://stackoverflow.com/questions/56695560
复制相似问题