Scikit learn import statements in their tutorials are on the form
from sklearn.decomposition import PCA
Another versions that works is
import sklearn.decomposition
pca = sklearn.decomposition.PCA(n_components = 2)
However
import sklearn
pca = sklearn.decomposition.PCA(n_components = 2)
does not, and complains
AttributeError: module 'sklearn' has no attribute 'decomposition'
Why is this, and how can I predict which ones will work and not so i don’t have to test around? If the understanding and predictiveness extends to python packages in general that would be the best.
sklearn
doesn’t automatically import its submodules. If you want to use sklearn.<SUBMODULE>
, then you will need to import it explicitly e.g. import sklearn.<SUBMODULE>
. Then you can use it without any further imports like result = sklearn.<SUBMODULE>.function(...)
.
Large packages often behave this way where they don’t automatically import all the submodules.
Skimmed related documentation docs.python.org/3/reference/import.html without success. I might have missed it though.
Can you add the link of what are you following. The documentation scikit-learn.org/stable/auto_examples/decomposition/… here tells importing as
from sklearn import decomposition
then using likepca = decomposition.PCA(n_components=3)
I think I based this mostly off of scikit-learn.org/stable/getting_started.html. It imports multiple things and consistently uses ‘from sklearn.submodule import function’. Clicking through some other random documentation now, you are right that ‘from sklearn import submodule’ is also frequently used.