当前位置:   article > 正文

(报错)RuntimeError: expected scalar type Float but found Long

expected scalar type float but found long

报错代码

  1. import torch
  2. def synthetic_data(w,b,num_examples):
  3. X = torch.normal(0,1,(num_examples,len(w)))
  4. y = torch.matmul(X,w) + b
  5. y += torch.normal(0,0.01,y.shape)
  6. return X,y.reshape((-1,1))
  7. true_w = torch.tensor([2,-3,4])
  8. true_b = 4.2
  9. features,labels = synthetic_data(true_w,true_b,1000)
  10. print('features:',features[0],'\nlabels:',labels[0

错误信息

  1. E:\tool\anaconda\envs\pytorch_38\python.exe "E:\deep_learning\chapter_1\4_Linear regression.py"
  2. Traceback (most recent call last):
  3. File "E:\deep_learning\chapter_1\4_Linear regression.py", line 17, in <module>
  4. features,labels = synthetic_data(true_w,true_b,1000)
  5. File "E:\deep_learning\chapter_1\4_Linear regression.py", line 11, in synthetic_data
  6. y = torch.matmul(X,w) + b
  7. RuntimeError: expected scalar type Float but found Long
  8. Process finished with exit code 1

此错误是因为features,labels = synthetic_data(true_w,true_b,1000)中true_w在传递参数时是torch.long型数据,而y = torch.matmul(X,w)中需要torch.float型,因此在定义true_w时显性定义为float型

true_w = torch.tensor([2,-3,4],dtype=torch.float32)

然后代码正常运行

  1. E:\tool\anaconda\envs\pytorch_38\python.exe "E:\deep_learning\chapter_1\4_Linear regression.py"
  2. features: tensor([-0.1643, -1.1914, 0.7178])
  3. labels: tensor([10.3341])
  4. Process finished with exit code 0

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/649829
推荐阅读
相关标签
  

闽ICP备14008679号