3,1 表示最外層括號中有3條數據,2個逗號python
torch的數據維度表示,從外向裏表示,[3,1],表示外面有3行1列code
import torch import torch.nn as nn import torch.nn.functional as F data = torch.randn(3,1,6) data2 = torch.randn(3, 1) print(data2.size()) print(data2) data2 = torch.randn(1, 3) print(data2.size()) print(data2)
torch.Size([3, 1])
tensor([[ 1.5015],
[-1.8209],
[ 0.9194]])
torch.Size([1, 3])
tensor([[ 1.4510, -1.3262, -0.5420]])
orm
target的第2維和data的第3維數量要保持一致:不然報錯:get
import torch import torch.nn as nn import torch.nn.functional as F data = torch.randn(3,3,2) target = torch.tensor([[1,1],[0,1],[0,1]]) print(data.size(),target.size()) n = data.size(0) c = data.size(1) out_size = (n,) + data.size()[2:] if target.size()[1:] != data.size()[2:]: raise ValueError('Expected target size {}, got {}'.format( out_size, target.size())) # # print('data:', data.size(),target.size()) entropy_out = F.cross_entropy(data, target) print('entropy_out:', entropy_out, target.size())