AttributeError: module 'torch' has no attribute 'randn'

I have installed Pytorch, but have been geting the above error. I installed it but still did not work. Please, how can I solve this problem? Thank you.

Are other PyTorch methods working?
Which version are you using? You can see it using print(torch.__version__).

Only import torch method is working. In fact when I try printing the pytorch version, I get the following error: AttributeError: module ‘torch’ has no attribute ‘version

Could you try to print torch.__file__?

I did that and this is the error it returned: AttributeError: module ‘torch’ has no attribute ‘file

OK, in that case it looks like your PyTorch install is broken.
How did you install it? Could you try to remove PyTorch completely and install it again?
You can find the instructions on the website.

If you are using conda, I would recommend to create a new virtual environment for the new install and see if it’s working.

Thanks. I followed the instruction for uninstalling it using pip uninstall torch, but didn’t work, how do I go about it?

Did you called pip uninstall torch twice?
What kind of message did you get?
Could you additionally try conda uninstall pytorch?

Did you use pip, conda to install PyTorch or did you build it from source?

Thank you. I’m surprised I did exactly that twice as you said (bash-3.2$ pip uninstall torch), but returns the following:
Skipping torch as it is not installed.
You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the ‘pip install --upgrade pip’ command.

import torch doesn’t return error, but throws error when importing other packages.

What do you get if you run conda list | grep torch?

It returns nothing (no error)

Thanks for the info.
Could you run the same again using pip?

pip list | grep torch

If you don’t find any torch or torch_nightly installations, I’m not sure what to do besides maybe reinstalling conda and try to install PyTorch again.

hi! i am tring to print the pytorch version it gives an error while print(pytorch file ) return the file location. what should i do to resolve this issue

You can print the version via print(torch.__version__). The .__file__ attribute was just a debugging step for the original issue.

How do you name your file? I named it as and it tried to import this file. Of course it has nothing there. The solution could be: 1. install pytorch properly; 2. rename your python file other than

Ref: MacOS conda install fails

I had the same issue and for me, it was caused by the Conda environment being called “torch”. I got Pytorch to work by deleting the environment and creating a new one called torchenv

conda deactivate torch
conda env remove -n torch
conda create -n torchenv python=3.9
conda activate torchenv
pip install torch

hope this helps :slight_smile: