scikit-learn OneHot 返回元组而不是向量

数据挖掘 机器学习 分类 scikit-学习 预处理 一热编码
2022-02-19 23:24:31

首先,我对所有作为字符串的列进行标签编码,因此它们将是数字的。之后,我只取带有标签的列,将它们转换为 np 数组,重新整形,然后将它们转换为 one-hot 编码。

“y”的大小为 900(浮点数),在调整大小时我将其更改为 (900,1),这样一个热的就可以了。

我使用 scikit-learn OneHotEncoding,在执行 fir_transform 时,结果是:

输出

细节

为什么我得到一个元组作为输出而不是 1 和 0 的向量?


    def OneHot(self,y):
        ohe = OneHotEncoder()
        y = y.reshape(len(y) , 1)
        y_hot = ohe.fit_transform(y)
        print(y_hot)
        return y_hot
1个回答

为什么我得到一个元组作为输出而不是 1 和 0 的向量?

你得到这个是因为默认情况下 OneHotEncoder() 使用稀疏矩阵表示。因此,它将 y 的元素转换为类型的元素 -

<1x3 sparse matrix of type '<class 'numpy.float64'>'
    with 1 stored elements in Compressed Sparse Row format>

如果您希望输出为向量,则只需将 sparse=False 放入 OneHotEncoder()

以下是相同的示例 -

from sklearn import datasets
from sklearn.preprocessing import OneHotEncoder

# Iris dataset
X, y = datasets.load_iris(return_X_y=True)
print("Shape of dataset - ",X.shape, y.shape)

# Your code
def OneHot(y):
    ohe = OneHotEncoder(sparse=False)
    y = y.reshape(len(y) , 1) # you can also use y = y.reshape(-1, 1) instead
    y_hot = ohe.fit_transform(y)
    return y_hot
  
y_oh = OneHot(y)

print("Shape of One Hot Encoded y - ",y_oh.shape)
print("Single element in y - ",y_oh[0])

代码生成以下输出 -

Shape of dataset -  (150, 4) (150,)
Shape of One Hot Encoded y -  (150, 3)
Single element in y -  [1. 0. 0.]