class My_loss(nn.Module): # 自定义损失函数(部分)
'''自定义损失函数'''
def __init__(self):
super().__init__()
def forward(self, x, y):
x = x.to(device)
y = y.to(device)
zhat = torch.mm(x, C.T)
print(x.T.shape) # torch.Size([4]) 1行4列
print("******")
print(C.shape) # torch.Size([4, 1]) 4行1列
print("######")
print(zhat.shape) # torch.Size([1])
print("------")
return zhat
报错:RuntimeError: self must be a matrix
报错原因(细节学到了):torch.mm()是两个矩阵相乘,即两个二维的张量相乘,否则会报错,但是x是具有4个元素的一维张量torch.Size([4]),而C是一个4行1列的二维张量torch.Size([4, 1])
解决方法:使用torch.matmul(),则得到结果的形状是torch.Size([1])
注:torch.Size([1])
表示的是一个PyTorch张量的形状,其形状为只有一个维度,该维度的长度为1。换言之,它是标识这个张量为一维张量并且只包含一个元素。