Python错误笔记(1)之Pytorch的mean()函数

本文档展示了在使用PyTorch时遇到的一个常见错误:尝试用`mean()`函数并传入`axis`参数时触发了TypeError。错误原因是`mean()`函数在PyTorch中需要使用`dim`而非`axis`。通过将`axis`替换为`dim`,问题得到解决。修正后的代码能够正确计算矩阵的列平均值,并输出结果。了解这些差异对于正确使用PyTorch库至关重要。
摘要由CSDN通过智能技术生成

TypeError: mean() received an invalid combination of arguments - got (axis=int, )

 运行程序

import torch

A = torch.arange(20,dtype=torch.float32).reshape(5,4)
#dtype=torch.float32防止numel()报错RuntimeError: Can only calculate the mean of floatingtypes. Got Long instead.
A.mean(axis=0),A.sum(axis=0) / A.shape[0]


出现如下错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-18-a6b2437fb377> in <module>
----> 1 A.mean(axis=0),A.sum(axis=0) / A.shape[0]

TypeError: mean() received an invalid combination of arguments - got (axis=int, ), but expected one of:
 * ()
      didn't match because some of the keywords were incorrect: axis
 * (torch.dtype dtype)
      didn't match because some of the keywords were incorrect: axis
 * (tuple of ints dim, torch.dtype dtype)
 * (tuple of ints dim, bool keepdim, torch.dtype dtype)
 * (tuple of ints dim, bool keepdim)

解决方法:

修改把axis替换成dim代码如下:

A.mean(dim=0),A.sum(dim=0) / A.shape[0]#此处为torch的mean()而不是numpy中的mean()
#dim
#指定为1时,求得是行的平均值;
#指定为0时,求得是列的平均值。

 输出如下:

(tensor([ 8.,  9., 10., 11.]), tensor([ 8.,  9., 10., 11.]))

原因分析:此处的mean()函数使用的torch里面的,而不是numpy的mean()函数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值