为何使用sklearn.model_selection会报错,直接导入train_test_split却正常?
问题:为何
sklearn.model_selection调用报错,直接导入函数却正常? 以下代码运行时抛出错误: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)
但这段代码却能正常执行:
from sklearn.model_selection import train_test_split xtrain, xtest, ytrain, ytest = train_test_split(x,y, test_size = 0.2)
注:x和y已声明为数组。
原因解析
这是Python模块导入机制的特性导致的:
- 使用
import sklearn时,仅导入了sklearn的顶层模块,并不会自动加载所有嵌套的子模块(比如model_selection)。此时直接通过sklearn.model_selection访问,Python会认为顶层模块没有这个属性,从而报错。 - 而
from sklearn.model_selection import train_test_split的写法,会先触发sklearn.model_selection子模块的加载,再从中导入指定函数,因此能正常调用。
如果想保留sklearn.model_selection的调用形式,可以用两种方式解决:
- 显式导入子模块:
import sklearn import sklearn.model_selection # 先加载子模块 xtrain, xtest, ytrain, ytest = sklearn.model_selection.train_test_split(x,y, test_size = 0.2)
- 直接导入子模块并使用:
from sklearn import model_selection xtrain, xtest, ytrain, ytest = model_selection.train_test_split(x,y, test_size = 0.2)
内容的提问来源于stack exchange,提问作者user15346221
相关产品推荐
相关产品推荐

