pandas One-hot 编码的逻辑回归
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44308504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Logistic regression on One-hot encoding
提问by Mornor
I have a Dataframe (data
) which the head looks like the following:
我有一个 Dataframe ( data
),其头部如下所示:
status datetime country amount city
601766 received 1.453916e+09 France 4.5 Paris
669244 received 1.454109e+09 Italy 6.9 Naples
I would like to predict the status
given datetime, country, amount
and city
我想预测status
给定的datetime, country, amount
和city
Since status, country, city
are string, I one-hot-encoded them:
由于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)
I then create a simple LinearRegression model and fit my data:
然后我创建一个简单的 LinearRegression 模型并拟合我的数据:
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)
But I got the following error:
但我收到以下错误:
could not convert string to float: 'received'
无法将字符串转换为浮点数:'收到'
I have the feeling I miss something here and I would like to have some inputs on how to proceed. Thank you for having read so far!
我觉得我在这里错过了一些东西,我想就如何继续进行一些投入。感谢您阅读到目前为止!
采纳答案by MaxU
Consider the following approach:
考虑以下方法:
first let's one-hot-encode all non-numeric columns:
首先让我们对所有非数字列进行单热编码:
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
now we can use LinearRegression
classifier:
现在我们可以使用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)
回答by Will McGinnis
To do a one-hot encoding in a scikit-learn project, you may find it cleaner to use the scikit-learn-contrib project category_encoders: https://github.com/scikit-learn-contrib/categorical-encoding, which includes many common categorical variable encoding methods including one-hot.
要在 scikit-learn 项目中进行 one-hot 编码,您可能会发现使用 scikit-learn-contrib 项目 category_encoders 更简洁:https: //github.com/scikit-learn-contrib/categorical-encoding,其中包括许多常见的分类变量编码方法包括 one-hot。