Menu
CoddyTech

混合列

本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 46 课,共 58 课。

大多数表格都混合了文字和数字,每种数据都需要单独处理。ColumnTransformer 会将每一列传给对应的处理步骤,并合并结果:

一张标题为输入 4 列,输出 7 列的图。三张黑胶唱片包含流派、成色、价格和年份。流派和成色经过 OneHotEncoder 转换为 5 列 0/1 数据:爵士、摇滚、良好、崭新、磨损。价格和年份经过 StandardScaler 转换为 2 列缩放后的数据

对于一家唱片店,在代码中:

from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder

prep = ColumnTransformer([
    ("words", OneHotEncoder(), ["genre", "condition"]),
    ("numbers", StandardScaler(), ["price", "year"]),
])
pipe = make_pipeline(prep, LogisticRegression(max_iter=1000))

每个条目都包含一个名称、一个步骤及其列。与 get_dummies 不同,编码器会记住训练数据中的类别,因此新记录也会得到相同的 7 列。

challenge icon

挑战

中等

一个国际象棋俱乐部想在比赛开始前了解每位棋手的获胜概率。起始代码会拆分 chess.csv 并读取今晚的比赛数据。

  1. 对 opening 和 color 进行编码,对 rating_gap 和 minutes 进行缩放,然后打印训练行处理后得到的列数。
  2. 将它与逻辑回归串联起来,进行拟合,并打印测试准确率。
  3. 打印今晚的获胜概率。

另一个俱乐部,三个开局,以及 sicilian、black、50、15:

Columns after preparing: 7
Test accuracy: 0.805
Win chance: 0.66

亲手试试

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

# 国际象棋俱乐部的对局:开局、棋手执棋的颜色、棋手等级分减去
# 对手等级分的差值、棋钟剩余分钟数,以及棋手是否获胜(获胜为 1,未获胜为 0)
games = pd.read_csv("chess.csv")
X = games[["opening", "color", "rating_gap", "minutes"]]
y = games["won"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)

# 今晚的对局,用一行数据表示,列与之前相同
game = pd.DataFrame({"opening": [input()], "color": [input()],
                     "rating_gap": [int(input())], "minutes": [int(input())]})

# 在下方编写你的代码
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

监督学习中的所有课

自己练习: Python 在线编译器