異なる型の列
CoddyのMachine Learningジャーニー「教師あり学習」セクションの一部。レッスン 46/58。
ほとんどの表には文字列と数値が混在しており、それぞれに専用の処理ステップが必要です。ColumnTransformerは各列を対応するステップに渡し、結果を結合します:
レコードショップの場合、コードでは次のようになります。
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列が割り当てられます。
チャレンジ
中級チェスクラブは、試合前に各プレイヤーの勝つ確率を知りたいと考えています。スターターコードはchess.csvを分割し、今夜の試合のデータを読み込みます。
openingとcolorをエンコードし、rating_gapとminutesをスケーリングして、訓練データの行から作られる列数を出力します。- ロジスティック回帰とつなげて学習し、テスト精度を出力します。
- 今夜の試合で勝つ確率を出力します。
別のクラブ、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)
# 今夜の対局。同じ列を持つ 1 行
game = pd.DataFrame({"opening": [input()], "color": [input()],
"rating_gap": [int(input())], "minutes": [int(input())]})
# 以下にコードを書いてください
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
教師あり学習のすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ