在每个特征分类数据中一次性编码超过 1 个值

one-hot encoding more than 1 value in each feature categorical data

我是 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"]

我的第一种方法是先将其转换为带有标签enconder的整数,然后再转换为one-hot-coding方法:

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())

所以最终如果你 OHE (4,2,0) 你会得到:

[[0. 0. 0. 0. 1. 0. 0. 1. 0. 0. 0. 1. 0.]]

这是我想要的,因为前 5 列指的是 "alcohol" 特征,接下来的 6 列指的是烟草,最后 2 列指的是起始特征。

但是,我们假设一个示例在一个特征中可能有多个值。假设一个例子从酒精特征中得到 "Binge drinking" 和 "Heavy drinking"。然后,如果你 OHE ([0,1],2,0) 你会得到:

[[1. 1. 0. 0. 0. 0. 0. 1. 0. 0. 0. 1. 0.]]

这最后一步我不知道如何用 sklearn.preprocessing.OneHotEncoder 编码。我的意思是,如何在每个示例的一个特征中编码 2 个值?

我知道可能有更好的方法来编码 "alcohol"、"tobacco" 和 "onset",因为它们是序数值(然后每个特征中的每个值都与同一特征中的其他值。因此我可以只标记它们然后归一化 it.But 让我们假设这些是具有独立关系的分类变量。

我终于使用 MultilabelBinarizer 解决了它,正如@VivekKumar 所建议的:

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 like
dataMatrix = mlb.fit_transform(headings.split(', ') for headings in l1)

print("My Classes: ")
print(mlb.classes_)
print(dataMatrix)