pytorch代码解析:pytorch中loss = y_hat - y.view(y_hat.size())
import torch
y_hat = torch.tensor([[-0.0044],
[-0.0015],
[-0.0010],
[-0.0053],
[-0.0107],
[ 0.0055],
[-0.0073],
[ 0.0070],
[ 0.0041],
[-0.0031]]) # (10,1)
y = torch.tensor([ 6.1894, 7.2714, 4.4549, 5.2858, 10.8752, 2.6536, 6.6904, -1.6226,
0.6733, 5.6745]) # (10,)
loss = y_hat - y.view(y_hat.size())
print('y_hat.size()为', y_hat.size())
print('y.view(y_hat.size())为:',y.view(y_hat.size()))
print(y.view([5,2])
y_hat.size() 获取 y_hat 的形状 例子为[10,1] 的二维张量
y.view() 是按要求改变y 的形状 ,例如 y.view([5,2]) 把 y 变成[5,2]的二维张量。
注:y 元素个数一定要刚好符合 10 才可以。
运行结果
y_hat.size()为 torch.Size([10, 1])
y.view(y_hat.size())为: tensor([[ 6.1894],
[ 7.2714],
[ 4.4549],
[ 5.2858],
[10.8752],
[ 2.6536],
[ 6.6904],
[-1.6226],
[ 0.6733],
[ 5.6745]])
tensor([[ 6.1894, 7.2714],
[ 4.4549, 5.2858],
[10.8752, 2.6536],
[ 6.6904, -1.6226],
[ 0.6733, 5.6745]])