【问题标题】:one-hot encoding more than 1 value in each feature categorical dataone-hot 在每个特征分类数据中编码超过 1 个值
【发布时间】:2018-08-08 15:50:54
【问题描述】:

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

我的第一种方法是先将其转换为带有标签编码器的整数,然后再转换为 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 列指的是“酒精”特征,接下来的 6 列指的是烟草,最后 2 列指的是发作特征。

但是,让我们假设一个示例在一项功能中可能具有多个值。假设一个示例从酒精功能中获得“暴饮暴食”和“重度饮酒”。然后,如果你 OHE ([0,1],2,0) 你会得到:

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

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

我知道可能有更好的方法来编码“酒精”、“烟草”和“发作”,因为它们是序数值(然后每个特征中的每个值都与同一特征中的另一个值相关。因此我可以给它们贴上标签,然后对其进行规范化。但是让我们假设它们是具有独立关系的分类变量。

【问题讨论】:

  • 您需要为此使用 MultiLabelBinarizer。
  • 谢谢!这有助于解决问题! @VivekKumar

标签: python machine-learning scikit-learn data-science categorical-data


【解决方案1】:

我终于用 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)

【讨论】:

    猜你喜欢
    • 2017-11-06
    • 2020-03-18
    • 2017-04-23
    • 1970-01-01
    • 2016-03-02
    • 2020-10-25
    • 2019-05-17
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多