【已解决】cannot instantiate ‘PosixPath‘ on your system

问题描述

在使用预训练模型的时候,加载了官方提供的预训练模型出现以下问题:

  File "D:\ImageClassification\BiFormer_Demo\train.py", line 196, in <module>
    model_ft = biformer_tiny(pretrained=True)
  File "D:\ImageClassification\BiFormer_Demo\models\biformer.py", line 333, in biformer_tiny
    checkpoint = torch.hub.load_state_dict_from_url(url=url, map_location="cpu", check_hash=True, file_name=f"{
      
      model_key}.pth")
  File "D:\Users\wh109\anaconda3\lib\site-packages\torch\hub.py", line 731, in load_state_dict_from_url
    return torch.load(cached_file, map_location=map_location)
  File "D:\Users\wh109\anaconda3\lib\site-packages\torch\serialization.py", line 712, in load
    return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args)
  File "D:\Users\wh109\anaconda3\lib\site-packages\torch\serialization.py", line 1049, in _load
    result = unpickler.load()
  File "D:\Users\wh109\anaconda3\lib\pathlib.py", line 1084, in __new__
    raise NotImplementedError("cannot instantiate %r on your system"
NotImplementedError: cannot instantiate 'PosixPath' on your system

本地的电脑是Win11环境。
在这里插入图片描述

问题原因

通过在网上搜索同类的问题分析:应该是PosixPath不支持Window的路径。所以需要做修改,来适应Win11环境。

解决方法

点击报错的脚本pathlib.py,将下面的代码:

    def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        self = cls._from_parts(args, init=False)
        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        self._init()
        return self

在这里插入图片描述
修改为:

#修改后    
def __new__(cls, *args, **kwargs):
        if cls is Path:
            # cls = WindowsPath if os.name == 'nt' else PosixPath
            cls = WindowsPath
        self = cls._from_parts(args, init=False)
        # Windows doesn't support PosixPath
        if type(self) == PosixPath:
            cls = WindowsPath
            self = cls._from_parts(args, init=False)
        if not self._flavour.is_supported:
            raise NotImplementedError("cannot instantiate %r on your system"
                                      % (cls.__name__,))
        self._init()
        return self

在这里插入图片描述

然后,就可以正常运行了。

总结

出现这个问题,主要是Win11的兼容问题。如果有条件还是使用Ubuntu系统。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hhhhhhhhhhwwwwwwwwww/article/details/130470080
今日推荐