2017-08-16 122 views
0

我試圖建立一個dcnn,但我得到這個錯誤:困難CNN在keras

ValueError: ('The specified size contains a dimension with value <= 0', (-192, 1024))

真的,我不知道這個錯誤的原因,這裏是我的代碼:

數據:

c_X = open("C:/Users/PC/Desktop/Notebooks/Isabelle/mfcc_train_I_C_I_C_2.dat", "r") 
c_y = open("C:/Users/PC/Desktop/Notebooks/Isabelle/phoneme_train_I_C_I_C_2.dat", "r") 
c_X = np.fromfile(c_X, np.dtype('float32')) 
c_y = np.fromfile(c_y, np.dtype('int8')) 
c_X = c_X.reshape(886887,1120) 
c_X = c_X.reshape(c_X.shape[0], 1, 20, 56) 
c_y = one_hot(c_y) 
#c_y = np.append(c_y, np.zeros((374975,1)), axis=1) 
X_3 = apendice(Colere_X, c_X) 
y_3 = apendice(Colere_y, c_y) 
#print(c_X.shape, c_y.shape) 
print(X_3.shape, y_3.shape) 
(1123867, 1, 20, 56) (1123867, 38) 

這是我的神經網絡實現(問題是在這裏我想):

model = Sequential() 
model.add(Conv2D(32, (3, 3), border_mode='valid', activation='relu',input_shape=(1, 20, 56))) 
model.add(Dropout(0.25)) 
model.add(Conv2D(32, (3, 3), border_mode='valid', activation='relu')) 
model.add(MaxPooling2D(pool_size=(2, 2))) 
model.add(Dropout(0.25)) 

model.add(Conv2D(32, (3, 3), border_mode='valid', activation='relu')) 
model.add(Conv2D(32, (3, 3), activation='relu')) 
model.add(MaxPooling2D(pool_size=(2, 2))) 
model.add(Dropout(0.25)) 

model.add(Flatten()) 

model.add(Dense(1024, activation='relu')) 
model.add(Dropout(0.5)) 
model.add(Dense(num_classes, activation='softmax')) 
# Compile the model 
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 
# Train the model 
start = time.time() 
model_info = model.fit(X_3, y_3, batch_size=100, \ 
         epochs=20, verbose=2, validation_data=(X_test, y_test)) 
end = time.time() 

這裏模式的總結:

_________________________________________________________________ 
Layer (type)     Output Shape    Param # 
================================================================= 
conv2d_21 (Conv2D)   (None, -1, 18, 32)  16160  
_________________________________________________________________ 
dropout_16 (Dropout)   (None, -1, 18, 32)  0   
_________________________________________________________________ 
conv2d_22 (Conv2D)   (None, -3, 16, 32)  9248  
_________________________________________________________________ 
max_pooling2d_11 (MaxPooling (None, -2, 8, 32)   0   
_________________________________________________________________ 
dropout_17 (Dropout)   (None, -2, 8, 32)   0   
_________________________________________________________________ 
conv2d_23 (Conv2D)   (None, -4, 6, 32)   9248  
_________________________________________________________________ 
conv2d_24 (Conv2D)   (None, -6, 4, 32)   9248  
_________________________________________________________________ 
max_pooling2d_12 (MaxPooling (None, -3, 2, 32)   0   
_________________________________________________________________ 
dropout_18 (Dropout)   (None, -3, 2, 32)   0   
_________________________________________________________________ 
flatten_6 (Flatten)   (None, -192)    0   
================================================================= 
Total params: 43,904 
Trainable params: 43,904 
Non-trainable params: 0 
_________________________________________________________________ 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-17-589407073ff5> in <module>() 
    13 model.add(Flatten()) 
    14 model.summary() 
---> 15 model.add(Dense(256, activation='relu')) 
    16 model.add(Dropout(0.5)) 
    17 model.add(Dense(num_classes, activation='softmax')) 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\models.py in add(self, layer) 
    467       output_shapes=[self.outputs[0]._keras_shape]) 
    468   else: 
--> 469    output_tensor = layer(self.outputs[0]) 
    470    if isinstance(output_tensor, list): 
    471     raise TypeError('All layers in a Sequential model ' 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\topology.py in __call__(self, inputs, **kwargs) 
    567           '`layer.build(batch_input_shape)`') 
    568     if len(input_shapes) == 1: 
--> 569      self.build(input_shapes[0]) 
    570     else: 
    571      self.build(input_shapes) 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\layers\core.py in build(self, input_shape) 
    823          name='kernel', 
    824          regularizer=self.kernel_regularizer, 
--> 825          constraint=self.kernel_constraint) 
    826   if self.use_bias: 
    827    self.bias = self.add_weight(shape=(self.units,), 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\legacy\interfaces.py in wrapper(*args, **kwargs) 
    85     warnings.warn('Update your `' + object_name + 
    86        '` call to the Keras 2 API: ' + signature, stacklevel=2) 
---> 87    return func(*args, **kwargs) 
    88   wrapper._original_function = func 
    89   return wrapper 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\topology.py in add_weight(self, name, shape, dtype, initializer, regularizer, trainable, constraint) 
    389   if dtype is None: 
    390    dtype = K.floatx() 
--> 391   weight = K.variable(initializer(shape), dtype=dtype, name=name) 
    392   if regularizer is not None: 
    393    self.add_loss(regularizer(weight)) 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\initializers.py in __call__(self, shape, dtype) 
    206    limit = np.sqrt(3. * scale) 
    207    return K.random_uniform(shape, -limit, limit, 
--> 208          dtype=dtype, seed=self.seed) 
    209 
    210  def get_config(self): 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\backend\theano_backend.py in random_uniform(shape, minval, maxval, dtype, seed) 
    2189   seed = np.random.randint(1, 10e6) 
    2190  rng = RandomStreams(seed=seed) 
-> 2191  return rng.uniform(shape, low=minval, high=maxval, dtype=dtype) 
    2192 
    2193 

~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\theano\sandbox\rng_mrg.py in uniform(self, size, low, high, ndim, dtype, nstreams) 
    854     raise ValueError(
    855      "The specified size contains a dimension with value <= 0", 
--> 856      size) 
    857 
    858   else: 

ValueError: ('The specified size contains a dimension with value <= 0', (-192, 256)) 

我會感謝你的幫助。 在此先感謝。

+0

你能獲得model.summary()的輸出並將它包含在你的問題中嗎? –

+0

感謝您的回答,我添加了摘要。 –

回答

0

這是一個與Keras中的頻道排序有關的問題。您可能已將image_dim_orderingimage_data_format parameter中的~/.keras/keras.json設置爲tfchannels_last,具體取決於您正在使用的Keras版本。問題是您提供的input_shape處於thchannels first的順序,這會擾亂維度的解釋方式併產生負的維度大小。

如果您第一次使用Keras和TensorFlow,然後切換到Theano,會發生這種情況。

解決的辦法很簡單,你可以在keras.json配置文件中相應的參數設置爲thchannels_first所以它匹配您的文件,或者你改變你的數據的input_shape(20, 56, 1)。這兩種解決方案都應該可以工作,並且您應該更喜歡您正在使用的後端的本地通道順序(因爲它稍微快一些)。

+0

是的,我通過修改image_dim_ordering參數糾正了錯誤。非常感謝! –