2023年11月29日发(作者:)

pytorch中遇到的问题(持续更新中)

G:

RuntimuntimeEreError: one of the variables needed forr gra gradient commputaputation has

been modified by an inplace operation.

什么是inplace operation:in-place operation在pytorch中是指改变⼀个tensor的值的时候,不经过复制操作,⽽是直接在原来的内存

上改变它的值。可以把它成为原地操作符。

pytorch中,通常加后缀“_”来表⽰原地运算符,例如.add_(),或者python中的 “+=”。

RuntimuntimeEreError: Expected object of backend CPU but got backend CUDA

for argumrgument #2 'went #2 'weight'

这种情况通常是数据还在cpu上,⼜要⽤到gpu上计算导致的,可以尝试数据后⾯加上.cuda()。

cpu上的tensor和gpu上的tensor是太⼀样的:PyTorch中的数据类型为Tensor,Tensor与Numpy中的ndarray类似,同样可以⽤于标量,向

量,矩阵乃⾄更⾼维度上⾯的计算。PyTorch中的tensor⼜包括CPU上的数据类型和GPU上的数据类型,⼀般GPU上的Tensor是CPU上的

Tensor加cuda()函数得到。通过使⽤Type函数可以查看变量类型。系统默认的是ensor类型。例如data =

(2,3)是⼀个2*3的张量,类型为FloatTensor; ()就将其转换为GPU的张量类型,ensor类型。

xxxxxx is not implemented foplemented for type torcngTensor

尝试将nsor转换为:ensor类型。

:

bool value of Tensor with more than one value is ambiguous

函数或者可调⽤对象使⽤时候没有加括号。

5.注意:关于减少时间消耗

(1)只要是⽤到for循环都是在cpu上进⾏的,会消耗巨量的时间

(2)只要是⽤到⽣成矩阵这种操作都是在cpu上进⾏的,会很消耗时间。

(3)数据往cuda()上搬运会⽐较消耗时间,也就是说 .cuda()会⽐较消耗时间,能去掉就去掉。

(4)在服务器上,如果可以在⼀块gpu上运⾏就不要采⽤net = rallel(net),这种gpu并⾏⽅式⽐单个gpu要耗时。

6. pytorrcch debug :断点调试 和 打印可能出错步的结果 真的可以很快的找到错误所在的

地⽅

关于断点调试:pycharm单步调试 - qq_33485434的博客 - CSDN博客

7.UserWaserWarning: To copy constrnstrucuct fromm a a tensor

x= (x) ------> x= ()

8.RuntimeError: Expected object of scalar type Long but got scalar type

Float for argument #2 'maent #2 'mat2'(期望对象为标量类型长,但得到标量类型浮点数)

这个好奇怪,对于x= (x,one_hot_copy), 只要提前把x和one_hot_copy后⾯加上.float()就可以解决。

**9. 张量乘法(未定):

⼆维张量相乘: ⼆维矩阵相乘 A*B: (B), 多维矩阵相乘 A*B: (B), 注意需要long()数据类型。(tensor)