特征分类数据中每个特征编码多个值的一热编码

我对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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注