Pytorch模型定义报错:TypeError: new() received an invalid combination of arguments-got(float, int)

Pytorch定义网络结构的时候出错:TypeError: new() received an invalid combination of arguments - got (float, int), but expected one of:

问题分析

首先,我的错误复现:

>>> import torch.nn as nn
>>> fc1 = nn.Linear(512*3, 512/2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/zhangboshen/anaconda3/lib/python3.6/site-packages/torch/nn/modules/linear.py", line 48, in __init__
    self.weight = Parameter(torch.Tensor(out_features, in_features))
TypeError: new() received an invalid combination of arguments - got (float, int), but expected one of:
 * (torch.device device)
 * (torch.Storage storage)
 * (Tensor other)
 * (tuple of ints size, torch.device device)
      didn't match because some of the arguments have invalid types: (float, int)
 * (object data, torch.device device)
      didn't match because some of the arguments have invalid types: (float, int)

其实上面这一段代码,放到python2.7里面定义是完全没有问题的,问题是我现有的python3的环境对于除法的规则和python2不一样。
上面的512/2,在python3中的结果是256.0,但是在python2中就是256,python2和3的这些区别,真的让人处处感到绝望。。。
解决方法,把/换成//,后者的运算能够保证是int型数据。

说到python2和3的坑,还有一个容易出现的问题是字符串,python3中读出来之后默认是byte类型,这会导致你读出来的字符串前面多出一个b,比如b'015601864.jpg'这样的,接下来,就会导致opencv读不到图片然后引起一系列连锁反应随后你会怀疑自己写的代码是如此的垃圾然而并不是的,是python2和3的差异导致的。。。。

解决方法是在 Python3 中,bytes 和 str 互相转换:

str.encode('utf-8')
bytes.decode('utf-8')
  • 29
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值