You need to enable JavaScript to run this app. 如何从Keras加载的CIFAR-10数据集中筛选8个类别解决数组变形问题
优惠活动
大模型
产品
解决方案
定价
更多

如何从Keras加载的CIFAR-10数据集中筛选8个类别解决数组变形问题

问题原因

你的代码错误出在循环赋值逻辑:每次迭代对应类别i时,你都直接将X_train/Y_train赋值为当前类别i的样本,之前类别筛选的样本会被完全覆盖,最终仅保留了range(8)最后一个类别(类别7)的少量样本,自然会出现形状异常。

正确实现代码
import numpy as np
from keras.datasets import cifar10

# 加载CIFAR-10数据集
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# 自定义要保留的8个类别ID,可按需修改为任意8个类别
selected_classes = list(range(8))

# 筛选训练集样本
train_filter = np.isin(y_train, selected_classes).flatten()
X_train = x_train[train_filter]
Y_train = y_train[train_filter]

# 筛选测试集样本
test_filter = np.isin(y_test, selected_classes).flatten()
X_test = x_test[test_filter]
Y_test = y_test[test_filter]

# 若你选择的是非连续类别,可添加以下代码将标签重映射为连续的0-7,方便后续训练分类
# class_mapping = {old_label: new_label for new_label, old_label in enumerate(selected_classes)}
# Y_train = np.vectorize(class_mapping.get)(Y_train).reshape(-1, 1)
# Y_test = np.vectorize(class_mapping.get)(Y_test).reshape(-1, 1)
效果验证

筛选后样本量为8类总和:训练集共40000张、测试集共8000张,X_train形状保持(40000, 32, 32, 3)、Y_train形状保持(40000, 1),和原始数据集维度一致,不会出现形状异常。

内容的提问来源于stack exchange,提问作者Sourabh Somvanshi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 22:24:02