前言
在机器学习的构建训练中,我们常常需要对模型的训练效果进行检验,以及对模型做进一步的调参优化。在学习中总结了以下模型评估及优化方法,将其运用示例放这里方便滤清思路。
模型评估方法
模型评估方法即对模型的运行效果进行评估的手段,以下是相关的手段及其API
交叉验证
定义:通过将数据集划分为多个子集,循环使用其中一部分作为测试集、其他部分作为训练集来评估模型性能。
Python API:sklearn.model_selection库中的cross_val_score、KFold
from sklearn.datasets import load_iris
from sklearn.model_selection import cross_val_score, KFold
from sklearn.linear_model import LogisticRegression
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 初始化模型
model = LogisticRegression(max_iter=200) # 增加max_iter以避免警告
# 初始化KFold交叉验证器,设置折数为3
kf = KFold(n_splits=3, shuffle=True, random_state=42)
# 使用cross_val_score进行交叉验证
# scoring参数指定了评分策略,这里使用'accuracy'即准确率
scores = cross_val_score(model, X, y, cv=kf, scoring='accuracy')
# 打印每一折的准确率
print("每一折的准确率:", scores)
# 打印平均准确率
print("平均准确率:", scores.mean())
混淆矩阵
定义:用于衡量分类模型预测结果的准确性,包括真正例、假正例、真负例和假负例等指标。
Python API: sklearn.metrics库中的confusion_matrix
# 导入必要的库
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier # 示例使用K近邻分类器
from sklearn.metrics import confusion_matrix
# 加载数据
iris = load_iris()
X = iris.data
y = iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 初始化模型(这里以K近邻分类器为例)
model = KNeighborsClassifier(n_neighbors=3)
# 训练模型
model.fit(X_train, y_train)
# 使用模型进行预测
y_pred = model.predict(X_test)
# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred)
# 打印混淆矩阵
print("Confusion Matrix:")
print(cm)
准确率、精确率、召回率和F1分数
定义:用于评估分类模型的性能指标
Python API: sklearn.metrics库中的accuracy_score、precision_score、recall_score、f1_score
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# y_test、y_pred的计算略去
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
模型优化方法
特征工程
定义:对原始特征进行处理,包括特征选择、特征变换、特征构建等,以提高模型性能。
Python API:sklearn.preprocessing库中的MinMaxScaler(归一化)、StandardScaler(标准化)、LabelEncoder(编码)
# 这里只举标准化一例
from sklearn.preprocessing import StandardScaler
# x表示需要进行标准化的列
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
网格搜索
定义:通过系统地搜索多个参数组合来找到最佳的模型超参数设置
Python API: sklearn.model_selection库中的GridSearchCV、RandomizedSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV
# 定义参数网格
param_grid = {
'n_estimators': [3, 10, 30],
'max_features': [2, 4, 6, 8]
}
# 初始化随机森林回归器
forest_reg = RandomForestRegressor()
# 初始化GridSearchCV对象
grid_search = GridSearchCV(forest_reg, param_grid, cv=5, scoring='neg_mean_squared_error', verbose=1)
# 假设X_train和y_train是你的训练数据
grid_search.fit(X_train, y_train)
# 训练结束后,你可以通过best_params_获取最优参数组合
print(grid_search.best_params_)
from scipy.stats import randint, uniform
from sklearn.model_selection import RandomizedSearchCV
# 定义参数分布
param_distributions = {
'n_estimators': randint(low=1, high=100),
'max_features': randint(low=1, high=8),
'max_depth': randint(low=1, high=100)
}
# 初始化随机森林回归器
forest_reg = RandomForestRegressor()
# 初始化RandomizedSearchCV对象
random_search = RandomizedSearchCV(forest_reg, param_distributions, n_iter=10, cv=5, scoring='neg_mean_squared_error', verbose=1, random_state=42)
# 假设X_train和y_train是你的训练数据
random_search.fit(X_train, y_train)
# 训练结束后,你可以通过best_params_获取最优参数组合
print(random_search.best_params_)
(题外话:从这里面可以看出,两种网格搜索算法不同的地方在于,GridSearchCV会对给出的选择对象进行全部排列组合之后验证,而RandomizedSearchCV需要给出的不是参数选择而是参数分布,从指定的参数分布中随机选择样本来进行搜索)
正则化
定义:通过L1正则化、L2正则化等方法控制模型复杂度(一般是高次项),防止过拟合。
Python API: sklearn.linear_model库中的Ridge、Lasso
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error
# 生成模拟数据
X, y = make_regression(n_samples=100, n_features=1, noise=20, random_state=42)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 初始化岭回归模型,alpha为L2正则化强度
# alpha值越大,正则化强度越大,模型越简单
ridge = Ridge(alpha=1.0)
# 训练模型
ridge.fit(X_train, y_train)
# 预测测试集
y_pred = ridge.predict(X_test)
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error: {mse}")
# 查看模型系数
print(f"Model coefficients: {ridge.coef_}")
集成学习
定义:通过bagging或boosting思想来加强模型...
Python API:sklearn.ensemble库中的随机森林RandomForest、AdaBoost、GBDT,以及XGBoost、LightGBM等,一般分为回归和分类两种
(这里就不举例了,里面水深)