Search code examples
pythonscikit-learnpython-import

module 'sklearn' has no attribute 'model_selection'


Why does the code below return the error

module 'sklearn' has no attribute 'model_selection'
import sklearn
xtrain, xtest, ytrain, ytest = sklearn.model_selection.train_test_split(x,y, test_size = 0.2)

but this one works fine:

from sklearn.model_selection import train_test_split
xtrain, xtest, ytrain, ytest = train_test_split(x,y, test_size = 0.2)

note that I did declare x and y as arrays.


Solution

  • In Python, when you import a module using a statement like

     import sklearn
    

    you're essentially importing only the top-level module, and you do not automatically gain access to all the submodules or functions contained within that module. That's why you often need to import specific submodules like

    from sklearn.model_selection import train_test_split