scikit-learn 中的模型参数可以分为三大类,理解它们的区别对于模型训练、调优和避免错误至关重要:

(图片来源网络,侵删)
- 超参数
- 模型参数
- 拟合参数
超参数
这是最重要的一类参数,也是我们通常所说的“调参”对象。
定义
超参数是在学习之前需要由用户设置的参数,它们定义了模型的结构、学习行为和复杂度,并且不会在训练过程中自动学习,超参数的值直接影响模型的性能。
如何设置
通常通过构造函数传入,当你创建一个模型实例时,就设置了它的超参数。
例子
RandomForestClassifier中的n_estimators(决策树的数量)。SVC中的C和gamma(控制正则化和核函数的参数)。KNeighborsClassifier中的n_neighbors(K近邻中的K值)。
如何查找和修改
每个 scikit-learn 模型都有 get_params() 和 set_params() 方法,并且可以通过直接访问属性来修改。

(图片来源网络,侵删)
from sklearn.ensemble import RandomForestClassifier
# 1. 在创建模型时设置超参数
model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
# 2. 查看所有可用的超参数及其默认值
print("模型所有超参数:")
print(model.get_params())
# 输出类似:
# {'bootstrap': True, 'class_weight': None, 'criterion': 'gini', ... 'n_estimators': 100, ...}
# 3. 修改超参数
# 方法一:直接修改属性
model.n_estimators = 200
# 方法二:使用 set_params 方法
model.set_params(max_depth=10)
# 再次查看,确认修改
print("\n修改后的 n_estimators:", model.n_estimators) # 输出 200
print("修改后的 max_depth:", model.max_depth) # 输出 10
调优方法
由于超参数对模型性能影响巨大,我们需要找到最优的组合,常用方法有:
- 网格搜索:
GridSearchCV- 遍历所有给定的参数组合。 - 随机搜索:
RandomizedSearchCV- 在给定的参数分布中随机采样。 - 贝叶斯优化:
BayesSearchCV(来自scikit-optimize等库) - 更智能的搜索方法。
模型参数
定义
模型参数是在模型训练过程中从数据中学习得到的参数,它们代表了模型从数据中学到的“知识”或“模式”。
如何设置
完全由训练过程自动确定,用户无法直接设置,它们是 fit() 方法的计算结果。
例子
- 线性回归:
coef_: 每个特征的权重系数。intercept_: 截距项。
- 支持向量机:
support_vectors_: 支持向量。dual_coef_: 与支持向量相关的系数。
- 逻辑回归:
coef_: 特征的权重。intercept_: 截距。
如何访问
模型在调用 fit() 方法之后,学到的参数会存储在以下属性中(通常以下划线 _ :

(图片来源网络,侵删)
coef_: 权重系数。intercept_: 截距。support_vectors_: 支持向量。n_iter_: 实际迭代次数。
from sklearn.linear_model import LinearRegression
from sklearn.datasets import make_regression
# 1. 创建模型
model = LinearRegression()
# 2. 准备数据
X, y = make_regression(n_samples=100, n_features=1, noise=20, random_state=42)
# 3. 在 fit 之前,这些属性不存在或为空
try:
print("训练前的 coef_:", model.coef_)
except AttributeError:
print("训练前无法访问 coef_")
# 4. 训练模型
model.fit(X, y)
# 5. 训练后,可以访问学到的参数
print("\n训练后的模型参数:")
print("学到的系数 (coef_):", model.coef_)
print("学到的截距 (intercept_):", model.intercept_)
拟合参数
定义
拟合参数是 fit() 方法本身的一些参数,它们控制训练过程,但不是模型结构的一部分,它们不会像模型参数一样被保存下来。
如何设置
通过 fit() 方法传入。
例子
sample_weight: 为每个训练样本设置不同的权重,这对于处理不平衡数据集非常有用。X和y: 训练数据本身。
from sklearn.linear_model import SGDClassifier
from sklearn.datasets import make_classification
# 1. 创建模型
model = SGDClassifier(random_state=42)
# 2. 准备数据
X, y = make_classification(n_samples=1000, n_features=20, weights=[0.9, 0.1], random_state=42)
# 3. 为样本设置权重,让模型更关注少数类
# 假设少数类(标签为1)的权重是多数类的10倍
sample_weights = np.ones(y.shape)
sample_weights[y == 1] = 10
# 4. 训练模型,传入 sample_weight
# sample_weight 是一个拟合参数
model.fit(X, y, sample_weight=sample_weights)
print("\n使用样本权重训练后的模型系数:", model.coef_)
总结与最佳实践
| 类别 | 定义 | 设置方式 | 例子 | 访问/修改 |
|---|---|---|---|---|
| 超参数 | 训练前由用户设置,定义模型结构和行为。 | 构造函数, set_params() |
n_estimators, C, kernel |
model.get_params(), model.param_name = value |
| 模型参数 | 训练过程中从数据中学习得到,代表模型知识。 | 自动学习,用户无法设置 | coef_, intercept_, support_vectors_ |
model.coef_ (需先 fit) |
| 拟合参数 | 控制训练过程本身,不作为模型结构保存。 | fit() 方法传入 |
sample_weight |
model.fit(X, y, sample_weight=w) |
最佳实践流程
-
实例化模型: 创建模型实例,使用合理的超参数默认值。
model = RandomForestClassifier(n_estimators=100, random_state=42)
-
数据准备: 准备好特征
X和标签y,必要时进行预处理(如标准化、归一化)。 -
模型训练: 调用
fit()方法,将数据传入,此时模型会自动学习模型参数。model.fit(X_train, y_train)
-
模型评估: 使用测试集评估模型性能。
score = model.score(X_test, y_test) print(f"模型准确率: {score:.4f}") -
超参数调优: 如果性能不佳,使用
GridSearchCV或RandomizedSearchCV来寻找最优的超参数组合。from sklearn.model_selection import GridSearchCV param_grid = { 'n_estimators': [50, 100, 200], 'max_depth': [None, 10, 20] } grid_search = GridSearchCV(estimator=model, param_grid=param_grid, cv=5) grid_search.fit(X_train, y_train) # 获取最佳模型 best_model = grid_search.best_estimator_ print("最佳超参数:", grid_search.best_params_) -
最终评估: 使用调优后的最佳模型在测试集上进行最终评估。
通过清晰地理解这三类参数的区别,你将能够更有条理地进行机器学习项目,并有效地提升模型性能。
