如何修正one_hot函数输出以得到目标独热编码矩阵?
解决方案
问题根源
当前输出存在两个核心问题:
- 冗余维度:输入
Y是(1,5)的二维数组,直接用它索引np.eye(n_classes)会保留原维度,导致结果变成(1,5,5)的三维数组。 - 维度顺序不符:目标矩阵要求格式为
(n_classes, n_samples)(每列对应一个样本的独热编码),但当前索引得到的是(n_samples, n_classes)(每行对应一个样本)。
修改后的代码
import numpy as np def one_hot(Y, n_classes): """ Arguments: Y -- array of input labels of shape (1, n_samples) n_classes -- number of classes Returns: onehot, a matrix of labels by samples. For each column, the ith index will be "hot", or 1, to represent that index being the label; shape - (n_classes, n_samples) """ # 展平Y消除冗余维度,转置后匹配目标形状 return np.eye(n_classes)[Y.flatten()].T
输出验证
运行修改后的代码,输出与目标矩阵完全一致:
[[0. 0. 0. 0. 0.] [1. 0. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 0. 1. 0. 1.] [0. 0. 0. 1. 0.]]
关键说明
Y.flatten():将(1,5)的二维输入转为(5,)的一维数组,避免索引后产生多余维度。.T:对索引得到的(5,5)数组进行转置,将每行对应样本的格式转为每列对应样本,完全符合函数注释中(n_classes, n_samples)的输出要求。- 输入标签值(1、2、3、4)与
np.eye的索引完全匹配,无需额外调整偏移量。
内容的提问来源于stack exchange,提问作者Андрей Березюк
相关产品推荐
相关产品推荐

