CIFAR-10尺寸误差Keras

时间:2017-10-14 07:33:34

标签: deep-learning keras gpu keras-layer

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

尺寸(-1)必须在[0,2]范围内,其中2是输入中的尺寸数。对于具有输入形状的'metrics / acc / ArgMax'(op:'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())

[name:“/ cpu:0” device_type:“CPU” memory_limit:268435456 地方{ } 化身:5668889307863094193 ,名称:“/ gpu:0” device_type:“GPU” memory_limit:1563603763 地方{   bus_id:1 } 化身:18418621293925924623 physical_device_desc:“device:0,name:GeForce GTX 960M,pci bus 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 \站点包\ tensorflow \ python的\框架\ common_shapes.py   在_call_cpp_shape_fn_impl中(op,input_tensors_needed,   input_tensors_as_shapes_needed,debug_python_shape_fn,   require_shape_fn)       669 node_def_str,input_shapes,input_tensors,input_tensors_as_shapes,    - > 670状态)       671除了errors.InvalidArgumentError为错误:

。 。 。 。

  

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

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

任何人都可以帮我解决这个问题吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

重新安装Anaconda,Tensorflow和Keras后,我的问题得以解决