在Pytorch中,我想通过点乘操作得到S:
// 点乘操作
S=a.mm(b)
运行代码时,老是报错:
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
输出a和b的维度发现: a的形状为 [20 , 5], 但是b的形状为[5 , ]。考虑用pytorch中的view函数,改变b的形状为[5,1]:
// b最先的形状为[5,]: tensor([ 1, 2, 3, 4, 5], device='cuda:0')
// view后b的形状为[5,1]: tensor([ [1], [2], [3], [4], [5]], device='cuda:0')
b=b.view(len(b),1)
S=a.mm(b)
从numpy.array( )的数组中,取某一行的数据转换成pytorch变量时,容易出现这个问题。类似地,也可以提前考虑用numpy.reshape( )改变所取的那一行数据,再转换成pytorch变量,再进行点乘运算。代码如下:
// b最先的格式为: [1,2,3,4,5]
// reshape后b的格式为: [ [1.] [2.] [3.] [4.] [5.] ]
b = numpy.reshape(b,(len(b),1))
b = Variable(
torch.from_numpy(b).type(T.FloatTensor))
S=a.mm(b)