sklearn.linear_model.RandomizedLogisticRegression:处理分类值

时间:2015-04-01 02:28:56

标签: python scikit-learn regression

我想使用RandomizedLogisticRegression为我的数据集选择变量。但问题是,我的数据集中的一个功能是性别。所以它的值是'F'或'M'而不是数值。结果我得到了以下错误:

Traceback (most recent call last):
  File "main.py", line 84, in Customer_Acquisition_Binary_Logistics
    self.randomized_Logistic_regression()
  File "main.py", line 92, in randomized_Logistic_regression randomized_logistic.fit(X,y)
  File "C:\Python27\lib\site-packages\sklearn\linear_model\randomized_l1.py", line 91, in fit
    X = as_float_array(X, copy=False)
  File "C:\Python27\lib\site-packages\sklearn\utils\validation.py", line 112, in as_float_array
    return X.astype(np.float32 if X.dtype == np.int32 else np.float64) ValueError: could not convert string to float: F

如何处理非数字的分类值?谢谢。

1 个答案:

答案 0 :(得分:0)

您必须将str值编码为数值,为此您可以使用LabelEncoder

In [33]:

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
print(le.fit(["paris", "paris", "tokyo", "amsterdam"]))
​
print(list(le.classes_))
​
print(le.transform(["tokyo", "tokyo", "paris"]) )
​
print(list(le.inverse_transform([2, 2, 1])))
​
LabelEncoder()
['amsterdam', 'paris', 'tokyo']
[2 2 1]
['tokyo', 'tokyo', 'paris']