管道
本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 45 课,共 58 课。
真实的数据表往往有缺失值、文本和不同的量纲。本章会创建一个既能清理数据又能进行预测的对象,也就是流水线:
从简单的开始:make_pipeline 将缩放器和模型串联起来:
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(StandardScaler(), KNeighborsClassifier())
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test))对于 200 个测试焊缝,无论强弱,缩放后都会输出 0.86,未缩放时为 0.74。
fit 从训练行中学习缩放方式,然后进行训练。之后的每一行都会自动按相同的方式缩放。
挑战
中等一家热气球公司每天晚上都会决定明天是否适合飞行。初始代码手动进行缩放:测试准确率不错,但天气预报数据从未进行缩放,因此无论天气如何,它都会输出 yes。
- 将它替换为一个流水线,先进行缩放,再使用 k-NN,并用训练行进行拟合。
- 输出它的测试准确率,并用它判断天气预报。
另一家公司的某天数据:20、32、7000、9:
Test accuracy: 0.880
Flying day: no亲手试试
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import make_pipeline
# 热气球公司过去每天的记录:适合飞行(1)或不适合飞行(0)
days = pd.read_csv("balloons.csv")
X = days[["wind_kmh", "gusts_kmh", "visibility_m", "passengers"]].to_numpy()
y = days["flying_day"].to_numpy()
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# 明天的天气预报:风速、阵风风速、能见度,以及已预订的乘客人数
day = np.array([[float(input()), float(input()), float(input()), float(input())]])
# 手动进行标准化:评分看起来不错,但预测数据始终没有经过标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
model = KNeighborsClassifier()
model.fit(X_train_scaled, y_train)
print(f"Test accuracy: {model.score(X_test_scaled, y_test):.3f}")
if model.predict(day)[0] == 1:
print("Flying day: yes")
else:
print("Flying day: no")
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
监督学习中的所有课
自己练习: Python 在线编译器