You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用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的调用形式,可以用两种方式解决:

  1. 显式导入子模块:
import sklearn
import sklearn.model_selection  # 先加载子模块
xtrain, xtest, ytrain, ytest = sklearn.model_selection.train_test_split(x,y, test_size = 0.2)
  1. 直接导入子模块并使用:
from sklearn import model_selection
xtrain, xtest, ytrain, ytest = model_selection.train_test_split(x,y, test_size = 0.2)

内容的提问来源于stack exchange,提问作者user15346221

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 02:15:57