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)
* ( 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中读出来之后默认是bytele类型,这会导致你读出来的字符串前面多出一个b,比如b\'015601864.jpg\'这样的,接下来,就会导致opencv读不到图片然后引起一系列连锁反应随后你会怀疑自己写的代码是如此的垃圾然而并不是的,是python2和3的差异导致的。。。。
解决方法是在 Python3 中,bytes 和 str 互相转换:
str.encode(\'utf-8\')
bytes.decode(\'utf-8\')
继续阅读与本文标签相同的文章
-
2019年9月份 阿里云域名优惠口令汇总
2026-05-18栏目: 教程
-
《安全说道》第三期 | 你家“大门”关好了吗?猪猪侠有话说
2026-05-18栏目: 教程
-
为什么支付宝有这么多“原生”技术牛人?
2026-05-18栏目: 教程
-
阿里巴巴小程序繁星计划 9月27日有话要说
2026-05-18栏目: 教程
-
为什么我会这么多技术,还这么难找工作
2026-05-18栏目: 教程
