网站源码怎么写,山西企业模板建站信息,物业管理系统功能,公司注册资金需要实际缴纳吗Scikit-learn (sklearn) 教程
Scikit-learn 是 Python 中最流行的机器学习库之一#xff0c;提供了丰富的机器学习算法、数据预处理工具以及模型评估方法#xff0c;广泛应用于分类、回归、聚类和降维等任务。
在本教程中#xff0c;我们将介绍如何使用 Scikit-learn 进行…Scikit-learn (sklearn) 教程
Scikit-learn 是 Python 中最流行的机器学习库之一提供了丰富的机器学习算法、数据预处理工具以及模型评估方法广泛应用于分类、回归、聚类和降维等任务。
在本教程中我们将介绍如何使用 Scikit-learn 进行数据加载、特征处理、模型训练与评估并展示一些常用的机器学习模型。
1. 安装 Scikit-learn
你可以使用以下命令安装 scikit-learn
pip install scikit-learn2. Scikit-learn 的核心组件
数据集提供内置数据集和数据集加载工具。特征工程包括特征缩放、编码、缺失值处理等。模型提供分类、回归、聚类、降维等多种算法。模型评估包括交叉验证、网格搜索等。
3. 数据集
Scikit-learn 提供了多种内置数据集例如 Iris、Boston并且提供了用于加载外部数据集的工具。
3.1 加载内置数据集
例如加载 Iris 数据集
from sklearn.datasets import load_iris# 加载 Iris 数据集
iris load_iris()
print(iris.feature_names) # 输出特征名称
print(iris.target_names) # 输出目标类别名称# 特征数据
X iris.data
# 目标数据
y iris.targetprint(X.shape, y.shape)3.2 使用 Pandas 加载 CSV 数据
你也可以使用 Pandas 加载本地 CSV 数据
import pandas as pd# 加载 CSV 数据
data pd.read_csv(data.csv)# 分离特征和目标
X data.drop(target_column, axis1)
y data[target_column]4. 数据预处理
Scikit-learn 提供了一些常用的特征预处理工具例如标准化、归一化、标签编码等。
4.1 标准化与归一化
标准化将数据转换为均值为 0方差为 1 的正态分布。归一化将数据缩放到 [0, 1] 或 [-1, 1] 的范围。
from sklearn.preprocessing import StandardScaler, MinMaxScaler# 标准化
scaler StandardScaler()
X_scaled scaler.fit_transform(X)# 归一化
min_max_scaler MinMaxScaler()
X_normalized min_max_scaler.fit_transform(X)4.2 标签编码
将分类标签转换为数字编码
from sklearn.preprocessing import LabelEncoder# 标签编码
label_encoder LabelEncoder()
y_encoded label_encoder.fit_transform(y)5. 训练/测试集拆分
在进行模型训练前通常需要将数据集划分为训练集和测试集。Scikit-learn 提供了 train_test_split 函数来完成这一操作。
from sklearn.model_selection import train_test_split# 划分训练集和测试集比例为 80:20
X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.2, random_state42)print(X_train.shape, X_test.shape)6. 模型训练
Scikit-learn 提供了丰富的机器学习算法。常见的分类、回归和聚类算法都可以通过 fit() 方法来训练模型。
6.1 分类任务示例K 最近邻 (KNN)
K 最近邻算法是一种经典的分类算法。以下是使用 KNN 进行分类的示例
from sklearn.neighbors import KNeighborsClassifier# 创建 KNN 模型
knn KNeighborsClassifier(n_neighbors3)# 训练模型
knn.fit(X_train, y_train)# 在测试集上进行预测
y_pred knn.predict(X_test)6.2 回归任务示例线性回归
对于回归任务可以使用线性回归模型进行训练
from sklearn.linear_model import LinearRegression# 创建线性回归模型
lr LinearRegression()# 训练模型
lr.fit(X_train, y_train)# 在测试集上进行预测
y_pred lr.predict(X_test)7. 模型评估
Scikit-learn 提供了多种评估指标用于衡量模型的性能。
7.1 分类模型评估
准确率分类模型中常用的评估指标表示预测正确的样本占总样本的比例。
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix# 计算准确率
accuracy accuracy_score(y_test, y_pred)
print(fAccuracy: {accuracy})# 分类报告
print(classification_report(y_test, y_pred))# 混淆矩阵
print(confusion_matrix(y_test, y_pred))7.2 回归模型评估
均方误差常用的回归模型评估指标衡量预测值与真实值的差距。
from sklearn.metrics import mean_squared_error, r2_score# 计算均方误差
mse mean_squared_error(y_test, y_pred)
print(fMean Squared Error: {mse})# R^2 分数
r2 r2_score(y_test, y_pred)
print(fR^2 Score: {r2})8. 交叉验证
交叉验证是一种常用的模型评估方法可以更稳健地评估模型性能。Scikit-learn 提供了 cross_val_score 来实现交叉验证。
from sklearn.model_selection import cross_val_score# 使用交叉验证评估模型性能使用 5 折交叉验证
scores cross_val_score(knn, X, y, cv5)
print(fCross-validation scores: {scores})
print(fAverage score: {scores.mean()})9. 模型调参
在实际应用中找到最优的超参数组合非常重要。Scikit-learn 提供了 GridSearchCV 和 RandomizedSearchCV 来进行超参数调优。
9.1 网格搜索Grid Search
from sklearn.model_selection import GridSearchCV# 定义参数网格
param_grid {n_neighbors: [3, 5, 7],weights: [uniform, distance]
}# 进行网格搜索
grid_search GridSearchCV(KNeighborsClassifier(), param_grid, cv5)
grid_search.fit(X_train, y_train)# 输出最佳参数
print(fBest parameters: {grid_search.best_params_})9.2 随机搜索Randomized Search
from sklearn.model_selection import RandomizedSearchCV# 定义随机搜索参数
param_distributions {n_neighbors: [3, 5, 7],weights: [uniform, distance]
}# 随机搜索
random_search RandomizedSearchCV(KNeighborsClassifier(), param_distributions, cv5, n_iter10)
random_search.fit(X_train, y_train)# 输出最佳参数
print(fBest parameters: {random_search.best_params_})10. 管道 (Pipeline)
Pipeline 是 scikit-learn 中的一个非常有用的工具它将多个步骤组合在一起形成一个工作流。通过 Pipeline我们可以将数据预处理和模型训练整合为一个过程方便进行交叉验证和超参数调优。
10.1 创建管道
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC# 创建一个包含标准化和 SVM 分类器的管道
pipeline Pipeline([(scaler, StandardScaler()), # 数据标准化(svc, SVC()) # 支持向量机分类器
])# 使用管道进行训练和预测
pipeline.fit(X_train, y_train)
y_pred pipeline.predict(X_test)# 评估模型
print(fAccuracy: {accuracy_score(y_test, y_pred)})10.2 在管道中使用网格搜索
你可以在 Pipeline 中使用超参数调优调整管道中的每个步骤的参数。
from sklearn.model_selection import GridSearchCV# 定义参数网格
param_grid {svc__C: [0.1, 1, 10],svc__kernel: [linear, rbf]
}# 使用管道进行网格搜索
grid_search GridSearchCV(pipeline, param_grid, cv5)
grid_search.fit(X_train, y_train)# 输出最佳参数
print(fBest parameters: {grid_search.best_params_})# 使用最佳模型进行预测
best_pipeline grid_search.best_estimator_
y_pred best_pipeline.predict(X_test)# 评估结果
print(fAccuracy: {accuracy_score(y_test, y_pred)})11. 特征选择
在机器学习中特征选择是非常重要的一步。通过去除无用或冗余的特征可以提升模型的性能。scikit-learn 提供了多种特征选择的方法。
11.1 使用 SelectKBest 进行特征选择
SelectKBest 是一种常见的特征选择方法它根据某种评分标准如 f_classif选择前 K 个最重要的特征。
from sklearn.feature_selection import SelectKBest, f_classif# 使用 SelectKBest 选择前 2 个最重要的特征
selector SelectKBest(f_classif, k2)
X_new selector.fit_transform(X_train, y_train)# 打印被选择的特征
print(X_new.shape)11.2 在管道中使用特征选择
你可以将特征选择步骤集成到 Pipeline 中以便与其他步骤如标准化和模型训练一起进行处理。
from sklearn.feature_selection import SelectKBest
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline# 创建一个包含特征选择、标准化和 SVM 分类器的管道
pipeline Pipeline([(select, SelectKBest(f_classif, k2)), # 特征选择(scaler, StandardScaler()), # 标准化(svc, SVC()) # 支持向量机
])# 训练模型
pipeline.fit(X_train, y_train)# 预测结果
y_pred pipeline.predict(X_test)
print(fAccuracy: {accuracy_score(y_test, y_pred)})12. 聚类
scikit-learn 提供了多种聚类算法。聚类是无监督学习中的一种任务目标是将数据划分为多个组簇其中同一簇的对象相似度较高。
12.1 K-means 聚类
K-means 是一种经典的聚类算法它通过最小化簇内的方差将数据划分为 K 个簇。
from sklearn.cluster import KMeans# 创建 K-means 模型指定 3 个簇
kmeans KMeans(n_clusters3, random_state42)# 训练模型
kmeans.fit(X)# 预测簇标签
y_kmeans kmeans.predict(X)# 打印每个样本所属的簇
print(y_kmeans)12.2 层次聚类 (Agglomerative Clustering)
层次聚类通过不断合并最近的簇来构建层次树结构。你可以指定合并停止的簇数量。
from sklearn.cluster import AgglomerativeClustering# 创建层次聚类模型
agg_clustering AgglomerativeClustering(n_clusters3)# 训练模型
y_agg agg_clustering.fit_predict(X)# 打印簇标签
print(y_agg)13. 降维
降维技术用于将高维数据映射到低维空间减少维度同时尽可能保留原始数据的信息量。常见的降维方法有主成分分析PCA和线性判别分析LDA。
13.1 PCA 降维
主成分分析PCA是一种线性降维技术找到数据的主要方向最大限度地保留数据的方差。
from sklearn.decomposition import PCA# 创建 PCA 模型指定主成分数量为 2
pca PCA(n_components2)# 使用 PCA 进行降维
X_pca pca.fit_transform(X)# 打印降维后的数据形状
print(X_pca.shape)13.2 LDA 降维
线性判别分析LDA是一种监督学习的降维方法通常用于分类任务。
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA# 创建 LDA 模型
lda LDA(n_components2)# 使用 LDA 进行降维
X_lda lda.fit_transform(X, y)# 打印降维后的数据形状
print(X_lda.shape)14. 模型持久化
在完成模型训练后你可以使用 joblib 或 pickle 将模型保存为文件之后可以加载该模型进行预测而无需重新训练。
14.1 保存模型
import joblib# 保存模型到文件
joblib.dump(knn, knn_model.pkl)14.2 加载模型
# 从文件中加载模型
loaded_model joblib.load(knn_model.pkl)# 使用加载的模型进行预测
y_pred loaded_model.predict(X_test)
print(fAccuracy: {accuracy_score(y_test, y_pred)})15. 自定义估计器
除了使用 scikit-learn 提供的标准模型外你还可以通过继承 BaseEstimator 和 ClassifierMixin 自定义自己的估计器。
from sklearn.base import BaseEstimator, ClassifierMixin
import numpy as npclass CustomClassifier(BaseEstimator, ClassifierMixin):def __init__(self, threshold0.5):self.threshold thresholddef fit(self, X, y):self.mean_ np.mean(X, axis0)return selfdef predict(self, X):return (np.mean(X, axis1) self.threshold).astype(int)# 创建并使用自定义分类器
clf CustomClassifier(threshold0.6)
clf.fit(X_train, y_train)
y_pred clf.predict(X_test)
print(fAccuracy: {accuracy_score(y_test, y_pred)})16. 完整示例分类任务
下面是一个完整的例子展示了如何加载数据、进行预处理、构建管道、训练模型、进行网格搜索、评估模型性能并将模型保存。
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, classification_report
from sklearn.pipeline import Pipeline
import joblib# 加载数据集
iris load_iris()
X iris.data
y iris.target# 数据划分
X_train, X_test, y_train, y_test train_test_split(X, y, test_size0.2, random_state42)# 构建管道
pipeline Pipeline([(scaler, StandardScaler()), # 标准化(knn, KNeighborsClassifier()) # KNN 分类器
])# 定义参数网格
param_grid {knn__n_neighbors: [3, 5, 7],knn__weights: [uniform, distance]
}# 网格搜索
grid_search GridSearchCV(pipeline, param_grid, cv5)
grid_search.fit(X_train, y_train)# 最佳模型
print(fBest parameters: {grid_search.best_params_})# 在测试集上进行预测
y_pred grid_search.predict(X_test)# 评估模型
print(fAccuracy: {accuracy_score(y_test, y_pred)})
print(classification_report(y_test, y_pred))# 保存最佳模型
joblib.dump(grid_search.best_estimator_, best_knn_model.pkl)17. 总结
通过本教程你已经了解了 Scikit-learn 的主要功能和使用方法包括数据预处理、模型训练与评估、超参数调优、管道、特征选择、聚类、降维等。Scikit-learn 提供了强大且易用的 API适合从简单的机器学习任务到更复杂的工作流构建。