【问题标题】:Logistic regression on One-hot encodingOne-hot 编码的逻辑回归
【发布时间】:2017-11-02 15:49:38
【问题描述】:

我有一个数据框 (data),其头部如下所示:

          status      datetime    country    amount    city  
601766  received  1.453916e+09    France       4.5     Paris
669244  received  1.454109e+09    Italy        6.9     Naples

我想预测给定datetime, country, amountcitystatus

由于status, country, city 是字符串,我对它们进行了单热编码:

one_hot = pd.get_dummies(data['country'])
data = data.drop(item, axis=1) # Drop the column as it is now one_hot_encoded
data = data.join(one_hot)

然后我创建一个简单的线性回归模型并拟合我的数据:

y_data = data['status']
classifier = LinearRegression(n_jobs = -1)
X_train, X_test, y_train, y_test = train_test_split(data, y_data, test_size=0.2)
columns = X_train.columns.tolist()
classifier.fit(X_train[columns], y_train)

但我收到以下错误:

无法将字符串转换为浮点数:'received'

我觉得我在这里错过了一些东西,我想就如何继续进行一些输入。 感谢您到目前为止的阅读!

【问题讨论】:

  • 试试y_data = data['status'] == 'received',我很确定LinearRegression在这里期待一个数字/布尔变量。

标签: python pandas machine-learning regression one-hot-encoding


【解决方案1】:

考虑以下方法:

首先让我们对所有非数字列进行一次热编码:

In [220]: from sklearn.preprocessing import LabelEncoder

In [221]: x = df.select_dtypes(exclude=['number']) \
                .apply(LabelEncoder().fit_transform) \
                .join(df.select_dtypes(include=['number']))

In [228]: x
Out[228]:
        status  country  city      datetime  amount
601766       0        0     1  1.453916e+09     4.5
669244       0        1     0  1.454109e+09     6.9

现在我们可以使用LinearRegression分类器:

In [230]: classifier.fit(x.drop('status',1), x['status'])
Out[230]: LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)

【讨论】:

  • 非常感谢!你介意解释一下为什么我最初的解决方案没有成功吗?
  • @Mornor,不客气。我猜X_train[columns] 和/或y_data 有一些string 列,因此could not convert string to float: 'received'
  • 我想补充一点,您的回答部分正确。实际上,它只对字符串进行 LabelEncode,而不是 one_hot 对它们进行编码。这将产生错误的结果,因为某些字符串的价值会比其他字符串“更多”。
  • 如果有人想知道 Mornor 是什么意思,这是因为标签编码将是数值。例如:法国 = 0,意大利 = 1,等等。这意味着一些城市比其他城市更有价值。使用 one-hot 编码,每个城市都有相同的值:例如:法国 = [1, 0],意大利 = [0,1]。也不要忘记虚拟变量陷阱algosome.com/articles/dummy-variable-trap-regression.html
【解决方案2】:

要在 scikit-learn 项目中进行 one-hot 编码,您可能会发现使用 scikit-learn-contrib 项目 category_encoders:https://github.com/scikit-learn-contrib/categorical-encoding 更简洁,其中包括许多常见的分类变量编码方法,包括 one-hot。

【讨论】:

    猜你喜欢
    • 2021-04-17
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-14
    • 2020-09-18
    • 2019-07-14
    • 2019-11-18
    • 2020-02-08
    相关资源
    最近更新 更多