我试图重塑尺寸为[10,200,1]到[2000,1,1]的火炬张量Yp时遇到问题。张量是从维度[2000,1]的numpy阵列y获得的。我正在做以下事情:
Yp = reshape(Yp, (-1,1,1))
我尝试通过执行以下操作将结果减去y的火炬张量版本:
Yp[0:2000,0] - torch.from_numpy(y[0:2000,0])
我希望结果是一个零数组,但事实并非如此。重新整形时调用不同的顺序(order ='F'或'C')不能解决问题,并且在进行减法时奇怪地输出相同的结果。我只能通过调用张量Yp得到一个零数组,使用order ='F'来表示ravel方法。
我做错了什么?我想用重塑来解决这个问题!
答案 0 :(得分:1)
我同意@ linamnt的评论(尽管实际产生的形状是[2000, 1, 2000]
)。
这是一个小型演示:
import torch
import numpy as np
# Your inputs according to question:
y = np.random.rand(2000, 1)
y = torch.from_numpy(y[0:2000,0])
Yp = torch.reshape(y, (10,200,1))
# Your reshaping according to question:
Yp = torch.reshape(Yp, (-1,1,1))
# (note: Tensor.view() may suit your need more if you don't want to copy values)
# Your subtraction:
y_diff = Yp - y
print(y_diff.shape)
# > torch.Size([2000, 1, 2000])
# As explained by @linamnt, unwanted broadcasting is done
# since the dims of your tensors don't match
# If you give both your tensors the same shape, e.g. [2000, 1, 1] (or [2000]):
y_diff = Yp - y.view(-1, 1, 1)
print(y_diff.shape)
# > torch.Size([2000, 1, 1])
# Checking the result tensor contains only 0 (by calculing its abs. sum):
print(y_diff.abs().sum())
# > 0