CIFAR-10 尺寸误差 Keras

Posted

技术标签:

【中文标题】CIFAR-10 尺寸误差 Keras【英文标题】:CIFAR-10 Dimension Error Keras 【发布时间】:2018-03-26 07:22:50 【问题描述】:

我正在尝试在我机器的 GPU 中运行 Cifar-10 CNN 代码,但我遇到了以下问题:

维度 (-1) 必须在 [0, 2) 范围内,其中 2 是输入中的维度数。对于具有输入形状的“metrics/acc/ArgMax”(操作:“ArgMax”):[?,?], []。

这是我的代码:

import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=cuda0,floatX=float32,lib.cnmem=1"
import theano
from __future__ import print_function
import keras
from keras.datasets import cifar10
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

[名称:“/cpu:0” 设备类型:“CPU” 内存限制:268435456 地点 化身:5668889307863094193 , 名称: "/gpu:0" 设备类型:“GPU” 内存限制:1563603763 地点 bus_id: 1 化身:18418621293925924623 物理设备描述:“设备:0,名称:GeForce GTX 960M,pci 总线 ID:0000:01:00.0” ]

import os
import pickle
import numpy as np

batch_size = 32
num_classes = 10
epochs = 200
data_augmentation = True
num_predictions = 20
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'

# The data, shuffled and split between train and test sets:
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
#x_train = x_train.reshape(50000, 3072)
#x_test = x_test.reshape(10000, 3072)
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

x_train 形状:(50000, 32, 32, 3) 50000 个训练样本 10000个测试样本

# 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)
model = Sequential()

model.add(Conv2D(32, (3, 3), padding='same',
                 input_shape=x_train.shape[1:]))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))

model.summary()

Layer (type)                 Output Shape              Param #   

conv2d_1 (Conv2D)            (None, 32, 32, 32)        896       
_________________________________________________________________
activation_1 (Activation)    (None, 32, 32, 32)        0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 30, 30, 32)        9248      
_________________________________________________________________
activation_2 (Activation)    (None, 30, 30, 32)        0         
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 15, 15, 32)        0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 15, 15, 32)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 15, 15, 64)        18496     
_________________________________________________________________
activation_3 (Activation)    (None, 15, 15, 64)        0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 13, 13, 64)        36928     
_________________________________________________________________
activation_4 (Activation)    (None, 13, 13, 64)        0         
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 6, 6, 64)          0         
_________________________________________________________________
dropout_2 (Dropout)          (None, 6, 6, 64)          0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 2304)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 512)               1180160   
_________________________________________________________________
activation_5 (Activation)    (None, 512)               0         
_________________________________________________________________
dropout_3 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 10)                5130      
_________________________________________________________________
activation_6 (Activation)    (None, 10)                0         

Total params: 1,250,858
Trainable params: 1,250,858
Non-trainable params: 0

# initiate RMSprop optimizer
opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)
# Let's train the model using RMSprop
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

在执行 RMSprop 优化器代码时,我收到以下错误:

InvalidArgumentError Traceback(最近调用 最后的) ~\Anaconda3\lib\site-packages\tensorflow\python\framework\common_shapes.py 在 _call_cpp_shape_fn_impl(op, input_tensors_needed, input_tensors_as_shapes_needed, debug_python_shape_fn, 需要_shape_fn) 第669章 --> 670 状态) 671 除了errors.InvalidArgumentError as err:

。 . . . .

ValueError: 维度 (-1) 必须在 [0, 2) 范围内,其中 2 是 输入中的维数。对于'metrics/acc/ArgMax'(操作: 'ArgMax') 输入形状:[?,?], []。

查看其他线程后,我尝试了两种不同的解决方案,但问题仍然存在。 建议的第一个解决方案是更新 Tensorflow。 第二种解决方案是将训练和测试数据从 x_train shape: (50000, 32, 32, 3) 重塑为 x_train shape: (50000, 3072),但随后面临的错误出现在模型 Conv2D 层中,其中重塑了数据无法使用。

谁能帮我解决这个问题?任何帮助表示赞赏。

【问题讨论】:

你能打印出model.summary()吗? @MarcinMożejko 我编辑了我的帖子。你可以看看 什么是y_train 形状? @MarcinMożejko y_train 形状:(50000, 10) @MarcinMożejko 重新安装 anaconda、keras 和 tensorflow 后,我的问题全部解决了 【参考方案1】:

在我重新安装 Anaconda、Tensorflow 和 Keras 后,我的问题得到了解决

【讨论】:

以上是关于CIFAR-10 尺寸误差 Keras的主要内容,如果未能解决你的问题,请参考以下文章

Pytorch&Keras CIFAR10图像分类(详情介绍以及汇总所有博客)

Pytorch&Keras CIFAR10图像分类(详情介绍以及汇总所有博客)

Keras CIFAR-10图像分类 GoogleNet 篇

Keras CIFAR-10图像分类 GoogleNet 篇

Keras CIFAR-10图像分类 AlexNet篇

Keras CIFAR-10分类 LeNet-5篇