One-hot编码的逻辑回归

Logistic regression on One-hot encoding

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

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

我想预测 status 给定 datetime, country, amountcity

由于 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)

但是我得到以下错误:

could not convert string to float: 'received'

我觉得我在这里遗漏了一些东西,我想就如何继续进行提供一些意见。 感谢您到目前为止的阅读!

考虑以下方法:

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

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)

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