Scikit-learn二进制化分类数据

时间:2017-05-22 09:49:13

标签: python scikit-learn categorical-data

我一直试图通过pandas将CSV文件加载到scikit中,并将目标列设置为20个分类变量的列表。我尝试过使用label_binarize,但似乎没有做任何好事,所以经过一些阅读我已经切换到LabelEncoder但它似乎没有太大变化。

from io import StringIO
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import permutation_test_score
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc, confusion_matrix
from sklearn.model_selection import train_test_split, ShuffleSplit
from sklearn.preprocessing import label_binarize, MultiLabelBinarizer, LabelEncoder
from sklearn.multiclass import OneVsRestClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.naive_bayes import GaussianNB

#loading the data
data=pd.read_csv("data.csv")
y = data.iloc[:,19]
X = data.iloc[:,1:18+20:22]

#Binarize the output
le = LabelEncoder()
le.fit(["0-1","1-1.5","1.5-2","2-2.5","2.5-3","3-3.5","3.5-4","4-4.5","4.5-5","5-5.5","5.5-6","6-6.5","6.5-7","7-7.5","7.5-8","8-8.5","8.5-9","9-9.5","9.5-10","10+"
])
LabelEncoder()
le.transform(y)
y = label_binarize(y, le)
n_classes = y.shape[1]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5,
                                                random_state=0)

model3 = KNeighborsClassifier(n_neighbors=7)

然而当我跑步时,我得到了:

Traceback (most recent call last):
File "file, line 30, in <module>
le.transform(y)
File "C:\Anaconda3\lib\site-packages\sklearn\preprocessing\label.py", line 149, in transform
classes = np.unique(y)
File "\Anaconda3\lib\site-packages\numpy\lib\arraysetops.py", line 198, in unique
ar.sort()
TypeError: '>' not supported between instances of 'str' and 'float'

这种目标数据甚至可以用于scikit吗?

1 个答案:

答案 0 :(得分:0)

好的,为了解决这个问题,我发现你需要用这样的引号包围分类数据本身:&#34; 0-1&#34;

否则Python会把它读作0-1的长点而感到困惑。数据加载正确。