當我想測試時nn.CrossEntropyLoss()是報錯,如下:
>>> x = torch.rand(64, 4) >>> y = torch.rand(64) >>> criterion(x, y) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/modules/module.py", line 1051, in _call_impl return forward_call(*input, **kwargs) File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/modules/loss.py", line 1120, in forward return F.cross_entropy(input, target, weight=self.weight, File "/Users/rogn/opt/anaconda3/envs/deeplearning/lib/python3.8/site-packages/torch/nn/functional.py", line 2824, in cross_entropy return torch._C._nn.cross_entropy_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index) RuntimeError: expected scalar type Long but found Float
參考https://stackoverflow.com/questions/60440292/runtimeerror-expected-scalar-type-long-but-found-float
原因是categorical target不能為浮點型,只能是整數,比如屬於某一類
所以,把target改為整型
>>> x = torch.rand(64, 4) >>> y = torch.randint(0,4, (64,)) >>> criterion(x, y) tensor(1.4477)