狗品种分类模型报错AxisError: axis 1超出一维数组边界
狗品种分类模型One-Hot编码解码报错:AxisError: axis 1 is out of bounds for array of dimension 1
问题描述
我正在开发一个狗品种分类模型,尝试展示标签及其对应的One-Hot编码标签示例,但运行代码时出现错误提示:
AxisError: axis 1 is out of bounds for array of dimension 1
当前代码如下:
def decode_one_hot(one_hot_encoded, labels): # 使用numpy的argmax获取每个编码列表中'1'的索引 indices = np.argmax(one_hot_encoded, axis=1) # 将索引转换回原始标签 decoded_labels = [labels[index] for index in indices] return decoded_labels print('示例:标签与对应One-Hot编码标签') train_labels = decode_one_hot(y_train, breeds) show_images(image_array= X_train, labels=train_labels, encoded_labels=y_train)
我期望实现的效果是:展示若干样本图片,同时显示对应的原始狗品种标签和其One-Hot编码形式。
问题原因与修复方案
核心问题
报错的根源是y_train并非二维的One-Hot编码数组,而是一维的类别索引数组(例如格式为[0, 5, 3, ...])。np.argmax(..., axis=1)要求输入数组至少为二维,但一维数组仅存在axis=0,因此触发轴越界错误。
修复方式
根据你的实际数据情况选择对应方案:
情况1:y_train本身是一维类别索引
无需解码,直接用索引映射原始标签即可:
# 直接通过一维索引获取原始标签 train_labels = [breeds[index] for index in y_train] print('示例:标签与对应One-Hot编码标签') show_images(image_array=X_train, labels=train_labels, encoded_labels=y_train)
情况2:需要先将一维索引转为One-Hot编码再展示
先对y_train做One-Hot编码转换,再执行解码逻辑:
from sklearn.preprocessing import OneHotEncoder import numpy as np # 将一维索引转换为二维One-Hot编码数组 encoder = OneHotEncoder(sparse_output=False) y_train_onehot = encoder.fit_transform(y_train.reshape(-1, 1)) # 保留原解码函数 def decode_one_hot(one_hot_encoded, labels): indices = np.argmax(one_hot_encoded, axis=1) decoded_labels = [labels[index] for index in indices] return decoded_labels train_labels = decode_one_hot(y_train_onehot, breeds) print('示例:标签与对应One-Hot编码标签') show_images(image_array=X_train, labels=train_labels, encoded_labels=y_train_onehot)
验证方法
先打印y_train的形状确认数据格式:
print(y_train.shape) # 输出为(n_samples,) → 一维类别索引;输出为(n_samples, n_classes) → 二维One-Hot数组
内容的提问来源于stack exchange,提问作者Jeremy Jin
相关产品推荐
相关产品推荐

