我对scikitlearn还比较陌生,目前正在处理预处理阶段遇到困难。
我有以下分类特征(我解析了一个JSON文件并将其放入字典中),所以:
dct['alcohol'] = ["Binge drinking", "Heavy drinking", "Moderate consumption", "Low consumption", "No consumption"]dct['tobacco']= ["Current daily smoker - heavy", "Current daily smoker", "Current on-and-off smoker", "Former Smoker", "Never Smoked", "Snuff User"]dct['onset'] = "Gradual", "Sudden"]
我的第一种方法是先用标签编码器将其转换为整数,然后再使用一热编码方法:
OH_enc = sklearn.preprocessing.OneHotEncoder(n_values=[len(dct['alcohol']),len(dct['tobacco']),len(dct['onset'])])le_alc = sklearn.preprocessing.LabelEncoder()le_tobacco = sklearn.preprocessing.LabelEncoder()le_onset = sklearn.preprocessing.LabelEncoder()le_alc.fit(dct['alcohol'])le_tobacco.fit(dct['tobacco'])le_onset.fit(dct['onset'])list_patient = []list_patient.append(list(le_alc.transform(['Low consumption'])))list_patient.append(list(le_tobacco.transform(['Former Smoker'])))list_patient.append(list(le_onset.transform(['Sudden'])))list1 = []list1.append(np.array(list_patient).T[0][:])list1.append([1,2,0])OH_enc.fit(list1)print(OH_enc.transform([[4,2,0]]).toarray())
因此,如果你对(4,2,0)进行一热编码,最终会得到:
[[0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 1. 0.]]
这是我想要的结果,因为前5列指的是“alcohol”特征,接下来的6列指的是“tobacco”特征,最后2列指的是“onset”特征。
然而,假设一个示例可以在一个特征中具有多个值。比如,一个示例从“alcohol”特征中获得了“Binge drinking”和“Heavy drinking”。那么,如果你对([0,1],2,0)进行一热编码,你会得到:
[[1. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 1. 0.]]
最后这一步,我不知道如何用sklearn.preprocessing.OneHotEncoder来编码。我的意思是,如何在一个示例中为一个特征编码两个值呢?
我知道可能有更好的方法来编码“alcohol”、“tobacco”和“onset”,因为它们是有序值(因此每个特征中的每个值与同一特征中的其他值相关)。这样我可以只给它们打标签,然后进行归一化处理。但假设这些是具有独立关系的分类变量。
回答:
我最终通过使用MultilabelBinarizer解决了这个问题,正如@***建议的那样:
headings = dct['alcohol'] + dct['tobacco'] + dct['onset']#print('my headings:'+ str(headings))l1 = ['Heavy drinking, Low consumption, Former Smoker, Gradual', 'Low consumption, No consumption, Current on-and-off smoker, Sudden', 'Heavy drinking, Current on-and-off smoker']mlb = MultiLabelBinarizer() # pass sparse_output=True if you'd likedataMatrix = mlb.fit_transform(headings.split(', ') for headings in l1)print("My Classes: ")print(mlb.classes_)print(dataMatrix)