Installed PyTorch but VS code wont import torch - python

I have installed PyTorch by just using pip install torch. I also have the correct version of python installed (I don't have two different versions).
When I ran the following in VS code it returned the correct version, and when I check if PyTorch is installed with pip it works.
import torch
print(torch.__version__)
But for some reason VS code doesn't recognise torch when I try and import it, or try to inheret from nn.Module in a class.
I just get the error "Import torch could not be resolved" and "nn is not defined"
I'm really confused as to what to do as I cant find any other people having this issue and all PyTorch VS code examples I look at just install the python extension and have no issue.

Check if vscode is using the same python interpreter and environment in which pytorch was installed.
Hit cmd + shift + P and search for Interpreter. Click on Python Interpreter and choose the correct one.
Check the image shown below

Just selecting the interpreter in vs code won't work, you have to follow those steps.
(if you install PyTorch in an anaconda environment)
1-Open Anaconda Promote
2-Activate your environment (Conda activate --)
3-type Code -- (code) will open vscode
4-select interpreter Ctrl +shift +P then type Python:Selectinterpreter
5-select your anaconda env

Related

Can't import torch that could not be resolved

I'm trying to run this code take from https://github.com/ultralytics/yolov5. I installed all the files in requirements.txt, and when I check the pip list, I see the version of torch is available. I tried to run pip3 install torch but it announced "Requirement already satisfied". How can I fix this?
import torch
# Model
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5n - yolov5x6, custom
# Images
img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
# Inference
results = model(img)
# Results
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
Thanks
Problems like this with Python are often caused by packages getting installed to the wrong instance of Python.
First off, are you using a virtual environment to run your code? If you are, make sure you're enabling the virtual env when you're installing torch.
You can use the following two commands to check if the pip you're invoking is from the same instance as where you're running your code. If you're using a virtual environment, make sure you enable it before running the commands.
pip3 --version
and
python -m pip --version
(Depending on your system, you might need to replace python with python3)
If they don't match, that means you're installing torch into the site packages of a different python instance to the one you're running your code in. If you find yourself in this situation, I would carefully look at your PATH variable to ensure that your virtual environment is coming first.
Alternatively if you just want to keep moving and the second command reports the correct location/version of python, you can just use python -m pip install to install into that virtual env.

Using PYCHARM professonal with WSL2 as python interpreter: does not have access to some packages

I have python working on WSL2 along with ubuntu20.04. I then installed miniconda and then, also installed all common data package, such as: tensorflow, pandas, scikit-learn, matplotlib, sqlalchemy, seaborn pip git
Everything is working fine.
I also have PYCHARM professional installed and as a python interpreter, I am using WSL2(ubuntu20.04). When I try to run the same code that rans fine from WSL2 terminal, PYCHARM complains about unresolved reference to "sklearn" and offers to download that package. Two questions:
i. Should not PYCHARM has access to whatever packages are available from WSL2/Ubuntu20.04 terminal, as I am using WSL2 as the PYTHON interpreter?
ii. If I let PYCHARM download package regardless, would not it create duplicate packages that could be possibly different versions?
# import the necessary packages
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
I am also attaching python interpreter screenshot to show that I a doing it correctly.
UPDATE:
based on #batuhand suggestion, I would like to try using the virtual enviroment. However, the problem is that WSL interpreter is not available.
When I choose WSL interpreter, then \usr\bin\python3 is available.
When I choose virtual environment, \usr\bin\python is not available.
So, it seems that I can not follow #batuhand 's suggestion.
Thanks #PavelKarateev. He pointed out to me on JetBrains.com that my interpreter was pointing to /usr/bin/python3 and I have point it to current location. This in my case is:
wsl://UBUNTU2004/home/$USER/miniconda3/envs/PipInConda_DKU/bin/python3.
Here "PipInConda_DKU" was the virtual environment that I created inside the Conda. As the name suggest, I was also using pip to install some package from Anaconda.
You can create a virtual environment for each project in pycharm. If you do that, all you have to do is install packages with pip in pycharm terminal and you will not see any duplication error.

Why does importing Pytorch in Sublime Text cause a ModuleNotFoundError?

The command 'import torch' causes the build error: 'ModuleNotFoundError: No module named 'torch''.
But when I run the command in the terminal, pytorch works just fine (Python 3.7.X).
Are you using a venvin the project you are right now? If that is so, then you need to install torch in that venv, as it has been created just for the project, so it has not got any extra modules like that one.
Take a look at this. And make sure that the module is in the environment your project is!
In Pycharm for example, whenever you create a new project with a new venv(virtual environment), you need to add to your project settings->interpreter settings the module manually, so it can be imported. Because it may be installed in your system, but not in that venvspecifically, which will look in there!
try this
link
it might help.
Also Faced similar issue in Windows 10 with Anaconda installed. Installed pytorch package using conda install command which I found here: http://pytorch.org/
The usual import from command-line worked for my environment(torch):

Different numpy version in Anaconda and numpy.__version__ in IPython Shell

I used How do I check which version of NumPy I'm using? to learn how to get the version of numpy. However, when I run conda list | grep numpy, I get:
numpy 1.15.2 py36ha559c80_0
numpy-base 1.15.2 py36h8128ebf_0
numpydoc 0.8.0 py36_0
However, when I run version from IPython shell, I get:
import numpy as np
np.__version__
Out: '1.13.3'
np.version.version
Out: '1.13.3'
np.version.full_version
Out: '1.13.3'
Why are the two versions different? Which one should I trust? Thanks for any help.
Please note that I am not using venv (i.e. virtual environment). I am directly accessing Anaconda's packages. So, there is no issue about versioning.
Here's what PyCharm is showing me:
As per Conda's version information on package doesn't correspond to __version__, here's __file__ and sys.path. Please note that I have hidden my name for privacy issues.
It seems that you have besides your python 3 environment in anaconda, another python with IPython and numpy installed.
It looks like that PyCharm and Anaconda see (correctly) the same numpy versions, while IPython which, I assume you didn't start from within your anaconda environment, sees another python installation with the older numpy. In fact, your output shows, that there is another python3.6 in C:\Users\... which doesn't belong to anaconda.
To make numpy 1.15 available in IPython you can either start IPython from within your anaconda environment by typing in the terminal (easier solution)
C:\>activate <your_anaconda_environment_name>
(<your_anaconda_environment_name>) C:\>ipython
or you make your local IPython load the modules from the anaconda environment by having a look at this answer. This will be not a recommended option in this case, given the resulting cross linkings of two python installations.
The issue is that PyCharm reads older python version from location App-data\roaming... What I did is that in start-up script, I added the following code.
print("Correcting sys paths now...")
paths = [
'C:\\Anaconda3\\python36.zip',
'C:\\Anaconda3\\DLLs',
'C:\\Anaconda3\\lib',
'C:\\Anaconda3',
'C:\\Anaconda3\\lib\\site-packages',
'C:\\Anaconda3\\lib\\site-packages\\win32',
'C:\\Anaconda3\\lib\\site-packages\\win32\\lib',
'C:\\Anaconda3\\lib\\site-packages\\Pythonwin',
'C:\\Anaconda3\\lib\\site-packages\\IPython\\extensions',
]
import sys
for path in reversed(paths):
sys.path.insert(0,path)
print("Completed correcting sys paths now...")
del path
del paths
Above code will force Python to read latest files from Anaconda. However, if you are using virtual environment, you would need to point to that environment.
If you want to know where is Python installed, you can run:
import os
import sys
os.path.dirname(sys.executable)
Above answer is inspired from conda python isn't using the numpy version I try install if I also specify that it should use python 2. It doesn't provide the solution. I have posted a solution above.

Getting PyCharm to import sklearn

Beginner here.
I’m trying to use sklearn in pycharm. When importing sklearn I get an error that reads “Import error: No module named sklearn”
The project interpreter in pycharm is set to 2.7.10 (/anaconda/bin/python.app), which should be the right one.
Under default preferenes, project interpreter, I see all of anacondas packages. I've double clicked and installed the packages scikit learn and sklearn. I still receive the “Import error: No module named sklearn”
Does anyone know how to solve this problem?
To make sure you have Scikit-learn package installed on your PyCharm IDE, go to File Menu>Settings and search for Interpreter. Select Project Interpreter, and if you dont see Scikit-learn in the list of packages, click the + sign on the right end. It brings us another window with a search bar, where you can type 'Scikit-learn' and install (see screenshots). I hope this helps.
Screenshots:
,
please notice that, in the packages search 'Scikit-learn', instead 'sklearn'
go to terminal- type python -m pip install scikit-learn
then hit enter.
give it some seconds. It will be done.
Sample Image
Double check your python interpreter. Check whether you have select correct interpreter at the first when you create the project.
Or else you can check your interpreter from the project view under External Libraries.
In your case if you didn't select 2.7.10 (/anaconda/bin/python.app) as your interpreter for the project at the beginning still the program give the same error Import error: No module named sklearn.
Same error occurs to me i have fixed by selecting File Menu-> Default Settings-> Project Interpreter -> Press + button and type 'sklearn' Press install button. Installation will be done in 10 to 20 seconds.
If issue not resolved please check you PyCharm Interpreter path. Sometimes your machine have Python 2.7 and Python 3.6 both installed and there may be some conflict by choosing one.
I had exactly the same problem. I'm using PyCharm with Anaconda3 & Python 3.7, and I've installed other packages into/via PyCharms just fine (such as numpy, scipy, and others). But although scikit-learn (which contains sklearn, that was initially confusing) seems fully installed on my system, including "import sklearn" working outside of PyCharm, I could not get the "import sklearn" to succeed inside PyCharm.
I finally got a python-expert friend to help me. He verified everything was correctly installed on my system and verified that PyCharm was somehow messing up.
We finally determined that the venv (virtual environment) was not including scikit-learn (sklearn) even though I had imported it properly into the Project Interpreter in PyCharms.
Solution: Delete and recreate the VENV, specifically ticking the box Inherit Global Site Packages
See here: https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html
for how to create a new virtual environment and get to that parameter.
SOLVED:
reinstalled Python 3.7.9 (not the latet)
installed numpy 1.17.5 (not the latest)
installed scikit-learn (latest)
sklearn works now!
For Mac OS:
PyCharm --> Preferences --> Project Interpreter --> Double Click on pip (a new window will open with search option) --> mention 'Scikit-learn' on the search bar --> Install Packages --> Once installed, close that new window --> OK on the existing window
and you are done.

Categories