【问题标题】:CIFAR-10 Dataset using Keras使用 Keras 的 CIFAR-10 数据集
【发布时间】:2018-06-22 02:45:46
【问题描述】:

我正在使用 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 个类......

【问题讨论】:

  • 您有 5 个类,但类索引不在 [0, 4] 范围内,您必须将原始类索引转换为适合该范围的新类索引。

标签: machine-learning neural-network deep-learning keras conv-neural-network


【解决方案1】:

您需要重命名您的目标。 我建议将您的目标转换为字符串,然后标记编码,最后转向分类。

from keras.utils import to_categorical
from sklearn.preprocessing import LabelEncoder

y= [2, 3, 5, 6, 7]
y=[str(x) for x in y] #as strings
le = LabelEncoder()
le.fit(y)
y_transformed=le.transform(y)

y_train=to_categorical(y_transformed)

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

【讨论】:

  • 它仍然为我提供了数据集中的 0-4 类。
猜你喜欢
  • 2018-07-20
  • 1970-01-01
  • 2015-11-13
  • 2022-12-04
  • 2018-03-26
  • 1970-01-01
  • 2020-03-10
  • 2017-12-19
  • 1970-01-01
相关资源
最近更新 更多