使用Keras训练CIFAR-10数据集

我在使用Keras训练一个模型来识别CIFAR-10数据集中的某些类别,但我只想使用其中的一些类别,而不是全部,所以我编写了以下代码:

selected_classes = [2, 3, 5, 6, 7]print('train\n', x_train.shape, y_train.shape)x = [ex for ex, ey in zip(x_train, y_train) if ey in selected_classes]y = [ey for ex, ey in zip(x_train, y_train) if ey in selected_classes]x_train = np.stack(x)y_train = np.stack(y).reshape(-1,1)print(x_train.shape, y_train.shape)print('test\n', x_test.shape, y_test.shape)x = [ex for ex, ey in zip(x_test, y_test) if ey in selected_classes]y = [ey for ex, ey in zip(x_test, y_test) if ey in selected_classes]x_test = np.stack(x)y_test = np.stack(y).reshape(-1,1)print(x_test.shape, y_test.shape)num_classes = len(selected_classes)

但我一直遇到以下错误:

IndexError                                Traceback (most recent call last)<ipython-input-8-d53a2cf8bdf8> in <module>() # Convert class vectors to binary class matrices. y_train = keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test, num_classes) ~\Anaconda3\lib\site-packages\keras\utils\np_utils.py in to_categorical(y,  num_classes)      n = y.shape[0]      categorical = np.zeros((n, num_classes))      categorical[np.arange(n), y] = 1      output_shape = input_shape + (num_classes,)      categorical = np.reshape(categorical, output_shape) IndexError: index 6 is out of bounds for axis 1 with size 5

我查看了Keras的源代码,发现:y 类别向量将被转换成矩阵(整数从0到num_classes)。4

当我将num_classes定义为8左右时,它确实能工作,但是我只有5个类别…


回答:

你需要重新命名你的目标。我建议将你的目标转换为字符串,然后进行标签编码,最后转换为分类数据。

from keras.utils import to_categoricalfrom sklearn.preprocessing import LabelEncodery= [2, 3, 5, 6, 7]y=[str(x) for x in y] #as stringsle = LabelEncoder()le.fit(y)y_transformed=le.transform(y)y_train=to_categorical(y_transformed)

要将你的预测结果转换为类别,你可以使用le.classes_来找出哪个类别对应哪个结果。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注