scikit-learn 机器学习入门实战
机器学习听起来高深,但 scikit-learn 把它变成了几行代码的事。从加载数据集、划分训练测试集,到训练一个分类模型、评估准确率,本文用一个完整的房价预测例子带你走通机器学习入门的标准流程。
一、机器学习的标准流程
不管用什么算法,机器学习项目的流程基本是固定的:加载数据 → 划分训练集和测试集 → 选择模型 → 训练 → 预测 → 评估。scikit-learn 的所有模型都遵循统一的 fit() 和 predict() 接口,学会一个就等于学会了所有。
# 安装:pip install scikit-learn pandas numpy
from sklearn.datasets import fetch_california_housing
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# 1. 加载数据
data = fetch_california_housing()
X, y = data.data, data.target
# 2. 划分训练集和测试集(80% 训练,20% 测试)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 3. 创建模型
model = LinearRegression()
# 4. 训练
model.fit(X_train, y_train)
# 5. 预测
predictions = model.predict(X_test)
# 6. 评估
mse = mean_squared_error(y_test, predictions)
print(f"均方误差: {mse:.4f}")
print(f"R² 分数: {model.score(X_test, y_test):.4f}")
核心概念:
fit() 是训练,predict() 是预测,score() 是评估。所有 scikit-learn 模型都是这个接口,换算法只需要改一行创建模型的代码。
二、分类问题:鸢尾花识别
回归预测的是连续数值(房价),分类预测的是离散类别(花的品种)。鸢尾花数据集是机器学习领域的"Hello World"。
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report
# 加载鸢尾花数据集
iris = load_iris()
X, y = iris.data, iris.target
print(iris.target_names) # ['setosa' 'versicolor' 'virginica']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 决策树分类器
clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X_train, y_train)
# 预测与评估
pred = clf.predict(X_test)
print(f"准确率: {accuracy_score(y_test, pred):.2f}")
print(classification_report(y_test, pred, target_names=iris.target_names))
三、特征预处理
真实数据往往需要预处理:数值标准化、类别编码、缺失值填充。scikit-learn 提供了完整的预处理工具。
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.impute import SimpleImputer
import numpy as np
# 数值标准化:把数据缩放到均值 0、标准差 1
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X_train)
# 缺失值填充:用中位数填补
imputer = SimpleImputer(strategy="median")
X_imputed = imputer.fit_transform(X)
# 类别编码:把文字标签转成数字
encoder = LabelEncoder()
labels = ["red", "blue", "red", "green", "blue"]
encoded = encoder.fit_transform(labels)
print(encoded) # [2 0 2 1 0]
四、模型对比与选择
同一个数据集可以试多个模型,选效果最好的那个。
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import SVC
models = {
"逻辑回归": LogisticRegression(max_iter=200),
"决策树": DecisionTreeClassifier(max_depth=5),
"随机森林": RandomForestClassifier(n_estimators=100),
"支持向量机": SVC(),
}
for name, model in models.items():
model.fit(X_train, y_train)
score = model.score(X_test, y_test)
print(f"{name}: 准确率 {score:.3f}")
通常随机森林在中小数据集上表现最稳,逻辑回归最快但精度一般。先跑一遍对比,再选最优的调参。
五、交叉验证
单次划分训练测试集有运气成分。交叉验证把数据分成多份,轮流当测试集,结果更可靠。
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(n_estimators=100)
# 5 折交叉验证:把数据分 5 份,轮流 1 份测试、4 份训练
scores = cross_val_score(model, X, y, cv=5)
print(f"5 折交叉验证得分: {scores}")
print(f"平均分: {scores.mean():.3f} ± {scores.std():.3f}")
六、模型保存与加载
训练好的模型可以保存成文件,下次直接加载使用,不用重新训练。
import joblib
# 训练模型
model = RandomForestClassifier(n_estimators=100)
model.fit(X_train, y_train)
# 保存到文件
joblib.dump(model, "iris_model.pkl")
# 下次使用时加载
loaded_model = joblib.load("iris_model.pkl")
result = loaded_model.predict(X_test[:5])
print(result)
七、总结
scikit-learn 把机器学习从学术论文变成了工程工具。统一的 fit-predict 接口让你可以快速尝试不同算法,特征预处理工具帮你处理脏数据,交叉验证让你对模型效果有信心。入门的最佳路径:先用内置数据集跑通完整流程,再换成自己的数据。