模型评估实战
综合实战:完整的机器学习项目流程——数据、预处理、多模型对比、调参、保存、部署预测接口。这是把 sklearn 从入门用到实战的闭环。
项目:葡萄酒质量预测
用 sklearn 内置葡萄酒数据集,预测酒的类别。流程:划分 → 标准化 → 多模型对比 → 网格调参 → 保存 → 写预测函数。
代码示例
import joblib
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report
# 1. 数据
X, y = load_wine(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42)
# 2. 预处理
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)
# 3. 模型 + 调参
grid = GridSearchCV(
RandomForestClassifier(random_state=42),
{"n_estimators": [50, 100], "max_depth": [5, 10]},
cv=5, n_jobs=-1)
grid.fit(X_train_s, y_train)
# 4. 评估
print("最佳参数:", grid.best_params_)
print(classification_report(y_test, grid.predict(X_test_s)))
# 5. 保存整个流程(scaler + 模型)
joblib.dump({"scaler": scaler, "model": grid.best_estimator_},
"wine_model.pkl")
# 6. 预测函数
def predict_wine(features):
pkg = joblib.load("wine_model.pkl")
x = np.array(features).reshape(1, -1)
x_s = pkg["scaler"].transform(x)
return pkg["model"].predict(x_s)[0]
# 测试预测
print("预测类别:", predict_wine(X_test[0]))
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
| 写法 / 语法 | 作用 |
|---|---|
print("hello") | 输出到控制台 |
name = "张三" | 变量赋值(无需声明类型) |
if x > 0: ... | 条件判断(注意冒号和缩进) |
for i in range(10): ... | 循环(缩进是语法的一部分) |
while x < 10: ... | 条件循环 |
def fn(a, b): return a + b | 定义函数 |
class Person: ... | 定义类 |
list = [1, 2, 3] | 列表(可改) |
tuple = (1, 2) | 元组(不可改) |
dict = {"key": "value"} | 字典(键值对) |
set = {1, 2, 3} | 集合(去重) |
len(obj) | 取长度 |
str(x) / int(x) / float(x) | 类型转换 |
s.split(",") | 字符串按分隔符拆分 |
" ".join(list) | 列表拼接成字符串 |
import os | 导入模块 |
from math import sqrt | 从模块导入指定函数 |
try: ... except Exception as e: ... | 异常捕获 |
with open("a.txt", "r") as f: ... | 文件读取(自动关闭) |
f"你好 {name}" | f-string 格式化 |
lambda x: x * 2 | 匿名函数 |
list(map(fn, arr)) | 函数式处理列表 |
range(start, stop, step) | 生成数字序列 |
if __name__ == "__main__": | 主入口判断 |
pip install 包名 | 安装第三方包(命令行) |