gpt4 book ai didi

python - 如何在 Scikit-Learn 中重用 LabelBinarizer 进行输入预测

转载 作者:太空狗 更新时间:2023-10-30 02:54:15 26 4
gpt4 key购买 nike

我使用 Scikit-Learn 训练了一个分类器。我正在加载输入以从 CSV 训练我的分类器。我的某些专栏(例如“城镇”)的值是规范的(例如可以是“纽约”、“巴黎”、“斯德哥尔摩”……)。为了使用这些规范列,我正在使用 Scikit-Learn 的 LabelBinarizer 进行一次性编码

这是我在训练前转换数据的方式:

import pandas as pd
from sklearn.preprocessing import LabelBinarizer

headers = [
'Ref.', 'Town' #,...
]

df = pd.read_csv("/path/to/some.csv", header=None, names=headers, na_values="?")

lb = LabelBinarizer()
lb_results = lb.fit_transform(df['Town'])

但是,我不清楚如何使用 LabelBinarizer 来使用我要对其进行预测的新输入数据创建特征向量。特别是,如果新数据包含一个可见的城镇(例如纽约),则需要在与训练数据中的同一城镇相同的位置对其进行编码。

标签二值化应该如何重新应用于新的输入数据?

(我对 Scikit-Learn 没有强烈的感觉,如果有人知道如何使用 Pandas 的 get_dummies 方法也很好。)

最佳答案

只需对已训练的 lb 模型使用 lb.transform()

演示:

假设我们有以下火车 DF:

In [250]: df
Out[250]:
Town
0 New York
1 Munich
2 Kiev
3 Paris
4 Berlin
5 New York
6 Zaporizhzhia

一步适应(训练)和变换(二值化):

In [251]: r1 = pd.DataFrame(lb.fit_transform(df['Town']), columns=lb.classes_)

产量:

In [252]: r1
Out[252]:
Berlin Kiev Munich New York Paris Zaporizhzhia
0 0 0 0 1 0 0
1 0 0 1 0 0 0
2 0 1 0 0 0 0
3 0 0 0 0 1 0
4 1 0 0 0 0 0
5 0 0 0 1 0 0
6 0 0 0 0 0 1

lb 现在针对我们在 df

中的那些城镇进行训练

现在我们可以使用经过训练的 lb 模型(使用 lb.transform() )对新数据集进行二值化:

In [253]: new
Out[253]:
Town
0 Munich
1 New York
2 Dubai # <--- new (not trained) town

In [254]: r2 = pd.DataFrame(lb.transform(new['Town']), columns=lb.classes_)

In [255]: r2
Out[255]:
Berlin Kiev Munich New York Paris Zaporizhzhia
0 0 0 1 0 0 0
1 0 0 0 1 0 0
2 0 0 0 0 0 0

关于python - 如何在 Scikit-Learn 中重用 LabelBinarizer 进行输入预测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46656327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com