[Bug] Pytorch, AttributeError: module ‘torch‘ has no attribute ‘_six‘

文章描述了一位用户在使用Torch1.10py3.8环境下遇到AttributeError,因为torch模块缺少_six属性。用户发现此问题不同于已知的Python版本问题,并提供了自定义解决方案:从另一个环境复制_six.py文件并修改vision.py中对_six的引用。问题得到解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实验环境

Torch1.10py3.8,

问题描述

Bug: Pytorch, AttributeError: module ‘torch’ has no attribute ‘_six’, 确认了配置的Environment下torch包下面确实没有_six.py文件,

网上搜了下,有的是Pytorch, AttributeError: module ‘torch._six’ has no attribute ‘PY37’, 这个时python版本的问题,只需要在_six.py改一行代码即可, 我的问题于这个不太一样.

原因分析:

环境问题,由于该环境下已经撞了很多其他的工具包,再去重新装新的版本太麻烦,
报错位置位于vision.py文件下的

class VisionDataset(data.Dataset):
    """
    Base Class For making datasets which are compatible with torchvision.
    It is necessary to override the ``__getitem__`` and ``__len__`` method.

    Args:
        root (string): Root directory of dataset.
        transforms (callable, optional): A function/transforms that takes in
            an image and a label and returns the transformed versions of both.
        transform (callable, optional): A function/transform that  takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.

    .. note::

        :attr:`transforms` and the combination of :attr:`transform` and :attr:`target_transform` are mutually exclusive.
    """
    _repr_indent = 4

    def __init__(
            self,
            root: str,
            transforms: Optional[Callable] = None,
            transform: Optional[Callable] = None,
            target_transform: Optional[Callable] = None,
    ) -> None:
        torch._C._log_api_usage_once(f"torchvision.datasets.{self.__class__.__name__}")
        if isinstance(root, torch._six.string_classes):

可以看到实际上就使用了_six文件下定义的一个类别:torch._six.string_classes,

解决方案:

Step1. 我在另一个Environment: torch1.10py3.6下找到了_six.py, 内容如下:

import math
import sys

inf = math.inf
nan = math.nan
string_classes = (str, bytes)
PY37 = sys.version_info[0] == 3 and sys.version_info[1] >= 7

def with_metaclass(meta: type, *bases) -> type:
    """Create a base class with a metaclass."""
    # This requires a bit of explanation: the basic idea is to make a dummy
    # metaclass for one level of class instantiation that replaces itself with
    # the actual metaclass.
    class metaclass(meta):  # type: ignore[misc, valid-type]

        def __new__(cls, name, this_bases, d):
            return meta(name, bases, d)

        @classmethod
        def __prepare__(cls, name, this_bases):
            return meta.__prepare__(name, bases)

    return type.__new__(metaclass, 'temporary_class', (), {})

然后将其拷贝到目标环境的torch包下面,

Step 2: 修改vision中引用_six.py的地方, 如下,
from torch._six import string_classes as string_classes
#if isinstance(root, torch._six.string_classes): # before
if isinstance(root, string_classes): # after

OK.

### 回答1: 这错误通常是由于使用了过时的PyTorch版本引起的。可以尝试更新PyTorch版本或者是将代码中使用的`_six`替换为`six`。 具体操作可以尝试升级PyTorch版本,例如使用以下命令: ``` pip install torch --upgrade ``` 如果还是无法解决问题,可以在代码中将所有的`_six`替换为`six`。 ### 回答2: "AttributeError: module 'torch' has no attribute '_six'" 是一个错误提示,表示在torch模块中没有名称为'_six'的属性。 这个错误通常是因为你导入的torch版本较低或存在一些配置问题所致。可以尝试以下解决方法: 1. 更新torch版本:在终端或命令提示符中运行`pip install torch -U`,将torch升级到最新版本。 2. 检查torch模块的导入方式:确保正确导入torch模块。可以使用以下方式导入: ```python import torch ``` 3. 检查torch安装是否正常:可以在终端或命令提示符中运行`pip show torch`,查看torch是否正确安装。 4. 检查环境变量:确保Python解释器可以正确找到torch模块。可以在终端或命令提示符中运行`python -c "import torch;print(torch.__file__)"`,查看torch模块的位置。 如果以上方法都不能解决问题,可能需要进一步检查和调试代码,或者参考官方文档或社区提供的解决方案。 ### 回答3: "AttributeError: module 'torch' has no attribute '_six'" 错误产生的原因是在使用 torch 库的时候,尝试调用了 torch._six 属性,但是该属性在新版本的 torch 库中已经被移除。 torch._six 属性实际上是用来提供一些与 Python 版本兼容性相关的功能的。在更早版本的 torch 中,该属性被用来处理一些 Python2 和 Python3 之间的差异,但是随着时间的推移,torch 库已经不再需要这个属性了,并且为了简化代码和提高效率,开发人员决定将其移除。 因此,在遇到 "AttributeError: module 'torch' has no attribute '_six'" 错误时,可以采取以下几种解决方法: 1. 更新 torch 库:确保你正在使用最新版本的 torch 库。可以通过 pip install torch --upgrade 命令来更新 torch。 2. 检查代码:检查你的代码是否有依赖于 torch._six 属性的部分。如果存在这部分代码,需要进行相应的修改,以便与新版本的 torch 库兼容。 3. 阅读文档和社区讨论:在遇到问题时,查阅官方文档和相关的社区讨论,可以帮助你找到更具体的解决方法。 总之,"AttributeError: module 'torch' has no attribute '_six'" 错误是因为尝试调用已被移除的 torch._six 属性所致。更新 torch 库、检查代码和查阅相关文档和社区讨论都是解决该错误的有效方法。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MasterQKK 被注册

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值