I am trying to build my first predictive model using Scikit-learn, but I keep getting a TypeError: "ImportError: cannot import name 'LinearRegression' from 'sklearn'". I have already installed the library using pip, and other parts of my code seem to work. Why can't Python find LinearRegression directly within the main sklearn package? Is there a specific sub-module I should be referencing instead, or is my installation corrupted?
3 answers
The reason you are seeing this error is that LinearRegression is not located in the top-level sklearn package; it is housed within the linear_model sub-module. To fix this, you must change your import statement to from sklearn.linear_model import LinearRegression. Scikit-learn is organized this way to keep the library modular, grouping algorithms by their mathematical family. If you try to import directly from the root, Python looks for a class that doesn't exist there. Always refer to the official documentation to see the specific path for each estimator, as this is a very common pattern across the entire library for everything from SVMs to Random Forests.
I updated my import code as suggested, and that specific error went away, but now it says "ModuleNotFoundError: No module named 'sklearn'". Does this mean I have multiple versions of Python installed, or is there a trick to making sure my IDE is looking at the right library path where I ran my pip install?
Double-check your file names too! If you named your own script sklearn.py, Python will try to import from your file instead of the actual library, causing this exact error.
I agree with Jennifer, I’ve seen so many students name their practice file sklearn.py or linear_model.py and get stuck for hours. Renaming the file and deleting the __pycache__ folder usually clears it up immediately!
Mark, this almost always happens when your IDE is using a different virtual environment than the one where you ran the installation. Check your interpreter settings. In VS Code or PyCharm, ensure you've selected the environment where scikit-learn was actually installed. Also, remember that the package name for installation is pip install scikit-learn, but the name you use in your code is just import sklearn. Mixing those up is a classic mistake when setting up new Data Science workflows.