0

I am working in VS Code to run a Python script in conda environment named myenv where sklearn is already installed. However when I import it and run the script I get the following error:

Traceback (most recent call last):
  File "d:\ML\Project\src\train.py", line 5, in <module>
    from sklearn.linear_models import LinearRegression
ModuleNotFoundError: No module named 'sklearn'

I have tried all possible solutions suggested in the following but nothing worked for me:

Can someone suggest a different way to fix this?

Ishan Dutta
  • 637
  • 11
  • 26
  • 1
    Can you run your script from the command line (or Powershell) with your virtualenv activated? If so, then VS Code isn't configured to use the virtualenv. – MattDMo Apr 05 '21 at 16:25
  • I am running the script from the VS Code Code Runner Extension, I could not find the `conda` command to run a script. – Ishan Dutta Apr 05 '21 at 16:27
  • 1
    Check that the Code Runner extension is set to use the python executable located in your virtualenv. – MattDMo Apr 05 '21 at 16:28
  • What should be the terminal command to run a file using `conda`? – Ishan Dutta Apr 05 '21 at 16:30
  • 1
    Activate the virtualenv, go to the folder containing your `train.py` file, and type `python train.py`. – MattDMo Apr 05 '21 at 16:33
  • Wow, this worked. I had not activated the environment. Writing `conda activate myenv` solved the issue. Thank you. – Ishan Dutta Apr 05 '21 at 16:35

3 Answers3

1

Have you tried https://code.visualstudio.com/docs/python/environments

Had the same issue and solved it by setting vscode to use my conda environment.

P_M_
  • 11
  • 2
0

I also have the same problem, but when I tried this command the error got fixed:

pip install sklearn

-2

Click on the terminal in the VS Code and run the following command to create the virtual environment in VS Code.

python -m venv path location of the working file\myvenv

in VS Code it will automatically activate.

I have attached an image

enter image description here

Henry Ecker
  • 31,792
  • 14
  • 29
  • 50
  • [answer], [tour], https://stackoverflow.com/editing-help – Yunnosch Feb 20 '22 at 18:52
  • Please don't post code as images. Code should be pasted as text, and formatted using Markdown. (The toolbar in the Stack Overflow editor can help you with this.) Code within images is harder to read, less accessible, can't be copied, and doesn't show up in relevant searches. Please [edit] your post to include the code as text; this will help you get better responses, and help prevent your answer from getting deleted. – Jeremy Caney Feb 21 '22 at 00:49