尝试了以下3种损失函数,记录下报错情况
-
二分类损失函数binary_cross_entrophy_loss
torch.nn.functional.binary_cross_entropy(input, target, weight=None, reduction=‘mean’)
运行代码时报错:
Expected object of scalar type Float but got scalar type Long for argument #2 ‘target’
解决:将target类型转换为float
target = target.float() -
余弦损失 cosine_embedding_loss
报错:
IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
维度不对,输入是两个值,x1,x2。yy要求是-1或1。 -
hinge_embedding_loss
报错:
RuntimeError: The size of tensor a (128) must match the size of tensor b (2) at non-singleton dimension 1
y要求是-1或1,因此用np.where命令进行替换
替换完了以后报错:
TypeError: can’t convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first
这是因为我用了GPU,替换以后还得从CPU传到GPU上。
‘numpy.ndarray’ object has no attribute ‘cuda’
numpy是没法直接传到cuda上的,需要先转换成tensor。torch.tensor(x)