Python pytorch,AttributeError:模块“torch”没有属性“Tensor”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47317141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:09:03  来源:igfitidea点击:

pytorch, AttributeError: module 'torch' has no attribute 'Tensor'

pythonpython-3.5centos7torchpytorch

提问by DavideChicco.it

I'm working with Python 3.5.1on a computer having CentOS Linux 7.3.1611(Core) operating system.

我在装有CentOS Linux 7.3.1611(核心)操作系统的计算机上使用Python 3.5.1

I'm trying to use PyTorchand I'm getting started with this tutorial.

我正在尝试使用PyTorch并且我正在开始学习本教程

Unfortunately, the #4 line of the example creates troubles:

不幸的是,示例的 #4 行造成了麻烦:

>>> torch.Tensor(5, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'torch' has no attribute 'Tensor'

I cannot understand this error... of course in Torch the 'torch' does have an attribute 'Tensor'. The same command works in Torch.

我无法理解这个错误……当然,在 Torch 中,“火炬”确实有一个属性“张量”。相同的命令适用于 Torch。

How can I solve this problem?

我怎么解决这个问题?

回答by Martijn Pieters

The Python binary that you are running does not have torchinstalled. It doeshave a directory named torchon the module search path, and it is treated as a namespace package:

您正在运行的 Python 二进制文件尚未torch安装。它确实有一个torch在模块搜索路径上命名的目录,它被视为一个命名空间包

$ pwd
/some/path
$ python3 -c 'import torch; print(torch); print(torch.__path__)'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'torch'
$ mkdir torch
$ python3 -c 'import torch; print(torch); print(torch.__path__)'
<module 'torch' (namespace)>
_NamespacePath(['/some/path/torch'])

Any directory without a __init__.pyfile present in it, located on your module search path, will be treated as a namespace, provided no other Python modules or packages by that name are foundanywhere else along the search path.

__init__.py位于模块搜索路径上的任何没有文件的目录都将被视为命名空间,前提在搜索路径的其他任何地方都找不到具有该名称的其他 Python 模块或包

This means that if torchwas installed for your Python binary, it doesn't matter if there is a local torchdirectory:

这意味着如果torch为您的 Python 二进制文件安装,则是否有本地torch目录并不重要:

$ ls -ld torch/
drwxr-xr-x  2 mjpieters users  68 Nov 23 13:57 torch/
$ mkdir -p additional_path/torch/
$ touch additional_path/torch/__init__.py
$ PYTHONPATH="./additional_path" python3 -c 'import os.path as p, sys; print(*(t for t in (p.join(e, "torch") for e in sys.path) if p.exists(t)), sep="\n")'
torch
/some/path/additional_path/torch
$ PYTHONPATH="./additional_path" python3 -c 'import torch; print(torch); print(torch.__path__)'
<module 'torch' from '/some/path/additional_path/torch/__init__.py'>
['/some/path/additional_path/torch']

The above shows that sys.pathlists the torchdirectory first, followed by additional_path/torch, but the latter is loaded as the torchmodule when you try to import it. That's because Python gives priority to top-level modules and packages before loading a namespace package.

上面显示首先sys.path列出torch目录,然后是additional_path/torch,但是torch当您尝试导入它时,后者作为模块加载。这是因为 Python 在加载命名空间包之前优先考虑顶级模块和包。

You need to install torch correctly for your current Python binary, see the project homepage; when using pipyou may want to use the Python binary with the -mswitch instead:

您需要为当前的 Python 二进制文件正确安装火炬,请参阅项目主页;使用时,pip您可能希望使用带有-m开关的 Python 二进制文件:

python3.5 -m pip install http://download.pytorch.org/whl/cu80/torch-0.2.0.post3-cp35-cp35m-manylinux1_x86_64.whl 
python3.5 -m pip install torchvision

So replace the pip3the homepage instructions use with python3.5 -m pip; python3.5can also be the full path to your Python binary.

因此,pip3将主页说明使用替换为python3.5 -m pip; python3.5也可以是 Python 二进制文件的完整路径。

Do use the correct download.pytorch.orgURL for the latest version.

请使用正确的download.pytorch.orgURL 获取最新版本。

You don't have to move the directory aside, but if you do want to and don't know where it is located, use print(torch.__path__)as I've shown above.

您不必将目录移到一边,但如果您确实想要并且不知道它的位置,请使用print(torch.__path__)我上面显示的方法。

Again, note that if you dohave an __init__.pyfile in a local torchdirectory, it becomes a regular package and it'll mask packages installed by pipinto the normal site-packageslocation. If you have such a package, or a local torch.pysingle-file module, you need to rename those. The diagnostic information looks different in that case:

此外,需要注意的是,如果你这样做有一个__init__.py在本地文件torch目录,就变成一个普通包,它会掩盖由安装包pip到正常的site-packages位置。如果您有这样的包或本地torch.py单文件模块,则需要重命名它们。在这种情况下,诊断信息看起来不同:

$ pwd
/some/path
$ python3 -c 'import torch; print(torch); print(torch.__path__)'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'torch'
$ mkdir torch
$ touch torch/__init__.py  # make it a package
$ python3 -c 'import torch; print(torch); print(torch.__path__)'
<module 'torch' from '/some/path/torch/__init__.py'>
['/some/path/torch']
$ rm -rf torch/
$ touch torch.py           # make it a module
$ python3 -c 'import torch; print(torch); print(torch.__file__)'
<module 'torch' from '/some/path/torch.py'>
/some/path/torch.py

Note the differences; a namespace package, above, uses <module 'name' (namespace)>, while a regular package uses ), while a plain module uses`.

注意差异;上面的命名空间包使用<module 'name' (namespace)>,而常规包使用), while a plain module uses`。

Such packages and modules (not namespace packages) are found first and stop the search. If the found package or module is not the one you wanted, you need to move them aside or rename them.

首先找到此类包和模块(不是命名空间包)并停止搜索。如果找到的包或模块不是您想要的,您需要将它们移到一边或重命名它们。

回答by stacksonstacks

Looks like the notebook is running with python2.
See the metadatasection of the notebook file(open in a text editor)

看起来笔记本正在运行python2
查看笔记本文件metadata部分(在文本编辑器中打开)

 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.13"
  }
 }


FIX
1. Ensure the python3.5kernel for ipython/jupyter is installed:
python3.5 -m ipykernel install --name python3.5.1

2. Run jupyter notebookand change kernel version in the notebook:
enter image description here


修复
1. 确保python3.5安装了 ipython/jupyter的内核:
python3.5 -m ipykernel install --name python3.5.1

2.jupyter notebook在笔记本中运行并更改内核版本:
在此处输入图片说明



or hackily edit the <notebook.ipynb>directly (not recommended):



或者<notebook.ipynb>直接修改(不推荐):

 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.5.1",
   "language": "python",
   "name": "python3.5.1"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.1"
  }
 }

回答by Sarthak

I Faced similar issue. Just install pytorch in new conda environment. It will work You may have to install jupyter in new conda environment again, if you want to work on jupyter notebook.

我遇到了类似的问题。只需在新的 conda 环境中安装 pytorch。它将起作用如果您想在 jupyter notebook 上工作,您可能需要在新的 conda 环境中再次安装 jupyter。

回答by user12703284

I got the same question, one .py works well and another report this error. Try to run the following command:

我遇到了同样的问题,一个 .py 运行良好,另一个报告此错误。尝试运行以下命令:

import torch
print(torch.__path__)
If (you get a wrong path): 
  then you know what you need to do.
Else if (even can not get the path printed): 
  just remove the temp file of your IDE(.idea or __pycache__). 

I do not know why, but it works for me. I hope it helps.

我不知道为什么,但它对我有用。我希望它有帮助。