Scikit-learn基础教程
Scikit-learn是一个用于机器学习的Python库,包含了各种分类、回归和聚类算法。它建立在NumPy、SciPy和Matplotlib之上,具有简单高效的数据挖掘和数据分析工具,适用于各种机器学习任务。本文将详细介绍如何使用Scikit-learn进行数据预处理、模型训练、模型评估和模型调优。
目录
安装Scikit-learn
在使用Scikit-learn之前,首先需要安装它。可以使用以下命令进行安装:
pip install scikit-learn
数据预处理
导入数据
首先,导入必要的库和数据集。我们以著名的Iris数据集为例:
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 转换为DataFrame
df = pd.DataFrame(data=np.c_[X, y], columns=iris.feature_names + ['target'])
print(df.head())
数据标准化
标准化是将特征值转换为均值为0、方差为1的分布,这有助于提高模型的性能。
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
处理缺失值
对于有缺失值的数据,可以使用插值方法填补。
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy='mean')
X_imputed = imputer.fit_transform(X)
特征编码
对于分类特征,需要将其转换为数值形式。可以使用LabelEncoder
和OneHotEncoder
进行编码。
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.compose import ColumnTransformer
# 示例分类特征
categories = ['A', 'B', 'C', 'A', 'B', 'C']
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(categories)
# One-hot编码
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
print(onehot_encoded)
模型训练
分类算法
逻辑回归
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 训练模型
model = LogisticRegression()
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
支持向量机
from sklearn.svm import SVC
# 训练模型
model = SVC(kernel='linear')
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
回归算法
线性回归
from sklearn.linear_model import LinearRegression
# 示例回归数据集
X, y = np.arange(10).reshape(-1, 1), np.arange(10) + np.random.normal(0, 1, 10)
# 训练模型
model = LinearRegression()
model.fit(X, y)
# 预测
y_pred = model.predict(X)
决策树回归
from sklearn.tree import DecisionTreeRegressor
# 训练模型
model = DecisionTreeRegressor()
model.fit(X, y)
# 预测
y_pred = model.predict(X)
模型评估
交叉验证
交叉验证是一种评估模型稳定性的方法。
from sklearn.model_selection import cross_val_score
# 使用交叉验证评估模型
scores = cross_val_score(model, X_scaled, y, cv=5)
print("Cross-validation scores:", scores)
评估指标
对于分类任务,可以使用准确率、精确率、召回率等指标。
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred, average='macro')
recall = recall_score(y_test, y_pred, average='macro')
f1 = f1_score(y_test, y_pred, average='macro')
print(f"Accuracy: {accuracy}")
print(f"Precision: {precision}")
print(f"Recall: {recall}")
print(f"F1 Score: {f1}")
对于回归任务,可以使用均方误差、平均绝对误差等指标。
from sklearn.metrics import mean_squared_error, mean_absolute_error
mse = mean_squared_error(y, y_pred)
mae = mean_absolute_error(y, y_pred)
print(f"Mean Squared Error: {mse}")
print(f"Mean Absolute Error: {mae}")
模型调优
网格搜索
网格搜索用于系统地遍历多个参数组合,以确定最佳模型参数。
from sklearn.model_selection import GridSearchCV
# 定义参数网格
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}
# 执行网格搜索
grid_search = GridSearchCV(SVC(), param_grid, cv=5)
grid_search.fit(X_train, y_train)
print("Best parameters:", grid_search.best_params_)
随机搜索
随机搜索通过随机采样参数空间中的点来寻找最佳模型参数。
from sklearn.model_selection import RandomizedSearchCV
from scipy.stats import uniform
# 定义参数分布
param_dist = {'C': uniform(0.1, 10)}
# 执行随机搜索
random_search = RandomizedSearchCV(SVC(kernel='linear'), param_dist, n_iter=100, cv=5, random_state=42)
random_search.fit(X_train, y_train)
print("Best parameters:", random_search.best_params_)
示例项目
在这里,我们将完整示例从数据预处理到模型调优进行展示,使用鸢尾花数据集进行分类。
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# 数据标准化
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 定义参数网格
param_grid = {'C': [0.1, 1, 10], 'kernel': ['linear', 'rbf']}
# 执行网格搜索
grid_search = GridSearchCV(SVC(), param_grid, cv=5)
grid_search.fit(X_train, y_train)
# 最佳参数
best_params = grid_search.best_params_
print("Best parameters:", best_params)
# 使用最佳参数训练模型
model = SVC(**best_params)
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 评估模型
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy}")
通过这篇教程,你已经掌握了使用Scikit-learn进行数据预处理、模型训练、模型评估和模型调优的基本方法。希望这篇教程对你有所帮助!