0

For some reason, this works:

from sklearn import svm

but this one does not

import sklearn  

sklearn.svm.LinearSVC()

saying module svm is not a subnodule of sklearn.

shouldn't they be the same thing?

Tim
  • 11,710
  • 4
  • 42
  • 43
Bob
  • 10,741
  • 27
  • 89
  • 143

2 Answers2

4

I've created a file system layout as follows.

[9:29pm][wlynch@watermelon layout] tree
.
├── __init__.py
└── sklearn
    ├── __init__.py
    └── svm
        └── __init__.py

[9:31pm][wlynch@watermelon layout] cat __init__.py 
[9:31pm][wlynch@watermelon layout] cat sklearn/__init__.py
[9:31pm][wlynch@watermelon layout] cat sklearn/svm/__init__.py
def LinearSVC():
    pass

Let's run python:

[9:29pm][wlynch@watermelon layout] python
Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sklearn
>>> sklearn.svm
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'svm'

>>> import sklearn.svm
>>> sklearn.svm.LinearSVC()
>>>

Often, a python library designer will resolve this issue, by having sklearn/__init__.py include the line import svm.

Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
  • Can you explain (or link to something that explains) what the `__init__.py` files do? – Tim Jul 22 '14 at 02:35
0

The first code works if svm is a variable in sklearn OR svm is a submodule of sklearn

from sklearn import svm

The second code only works if sklearn imports svm and holds it as a variable in its namespace

import sklearn
sklearn.svm.LinearSVC()
Andrew Johnson
  • 3,078
  • 1
  • 18
  • 24