使用 sklearn.preprocessing.OneHotEncoder 的 active_features_、feature_indices_ 和 n_values_ 属性,按“位置”排序的分类特征向量one-hot数组中的创建方式如下:
import numpy as np
from sklearn import preprocessing
enc = preprocessing.OneHotEncoder()
enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])
enc.active_features_ - np.repeat(enc.feature_indices_[:-1], enc.n_values_)
# array([0, 1, 0, 1, 2, 0, 1, 2, 3], dtype=int64)
另外,可以从 one-hot 数组中返回原始数据,如下所示:
x = enc.transform([[0, 1, 1], [1, 2, 3]]).toarray()
# array([[ 1., 0., 0., 1., 0., 0., 1., 0., 0.],
# [ 0., 1., 0., 0., 1., 0., 0., 0., 1.]])
cond = x > 0
[enc.active_features_[c.ravel()] - enc.feature_indices_[:-1] for c in cond]
# [array([0, 1, 1], dtype=int64), array([1, 2, 3], dtype=int64)]