Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't use scikit-learn - "AttributeError: 'module' object has no attribute ..."

I'm trying to follow this tutorial of scikit-learn (linear regression).

I've installed scikit through pip install -U scikit-learn, I use python 2.7 and Ubuntu 13.04

When I try to run the first lines of code there I get an error and it happens every time I'm trying to run anything with scikit-learn.

import pylab as pl
import numpy as np
from sklearn import datasets, linear_model

# Load the diabetes dataset
diabetes = datasets.load_diabetes()

I get the following:

AttributeError: 'module' object has no attribute 'load_diabetes'

When I try:

regr = linear_model.LinearRegression()

I get :

AttributeError: 'module' object has no attribute 'LinearRegression'

It seems to me that it's either I'm using the package wrong (but I've copied from their tutorial), or I've installed something wrong (but the package is loaded successfully).

Can anyone help?

like image 853
Zach Moshe Avatar asked May 24 '13 21:05

Zach Moshe


3 Answers

Another cause of this problem (not the problem with the OP's code) - but the one that got me - is that python does not automatically import subpackages or modules unless that is explicitly done by the package developer. And sklearn does not automatically import its subpackages, so if you have

import sklearn 
diabetes = sklearn.datasets.load_diabetes()

then you will get

AttributeError: module 'sklearn' has no attribute 'datasets'

This is a highly misleading error message, because sklearn does have a subpackage called datasets - you just need to import it explicitly

import sklearn.datasets 
diabetes = sklearn.datasets.load_diabetes()
like image 194
Roko Mijic Avatar answered Oct 27 '22 05:10

Roko Mijic


OK.. Found it finally.. Posting it here in case someone will get into the same problem.

I had another version of sklearn (probably because of apt-get install) in a different directory. It was partially installed somehow but it was the one that got loaded.

Make sure to look at your pip script's output to see where does it install the package, and when you load it from python, check sklearn.__path__ to see where is it taking it from.

like image 22
Zach Moshe Avatar answered Oct 27 '22 04:10

Zach Moshe


This worked for me:

from sklearn.datasets import make_moons
like image 27
Neuro Avatar answered Oct 27 '22 05:10

Neuro