ValueError:检查目标时出错:预期density_4的形状为(9,),但数组的形状为(8,)

时间:2019-03-17 19:33:35

标签: python python-3.x machine-learning keras

我正在尝试训练CNN模型以检测9种类别的图像。下面显示了X和y的形状。我已经按照here

的说明在其上应用了to_categorcial
print(X_train.shape, X_test.shape) #(19, 20, 11, 1) (5, 20, 11, 1) 
print(y_train_hot.shape, y_test_hot.shape) #(19, 9) (5, 8)

我不确定为什么错误仍然存​​在,因为最后一个Dense层应等于我的num_classes,即9。 我在Ubuntu中使用conda环境(Python 3)。 该错误如下:

  _________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 19, 10, 32)        160       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 18, 9, 64)         8256      
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 17, 8, 128)        32896     
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 8, 4, 128)         0         
_________________________________________________________________
dropout_1 (Dropout)          (None, 8, 4, 128)         0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4096)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 128)               524416    
_________________________________________________________________
dense_2 (Dense)              (None, 64)                8256      
_________________________________________________________________
dense_3 (Dense)              (None, 32)                2080      
_________________________________________________________________
dense_4 (Dense)              (None, 9)                 297       
=================================================================
Total params: 576,361
Trainable params: 576,361
Non-trainable params: 0
_________________________________________________________________
Traceback (most recent call last):
  File "train.py", line 61, in <module>
    validation_data=(X_test, y_test_hot))
  File "/home/abhishek/anaconda3/envs/conda/lib/python3.6/site-packages/keras/engine/training.py", line 972, in fit
    batch_size=batch_size)
  File "/home/abhishek/anaconda3/envs/conda/lib/python3.6/site-packages/keras/engine/training.py", line 789, in _standardize_user_data
    exception_prefix='target')
  File "/home/abhishek/anaconda3/envs/conda/lib/python3.6/site-packages/keras/engine/training_utils.py", line 138, in standardize_input_data
    str(data_shape))
ValueError: Error when checking target: expected dense_4 to have shape (9,) but got array with shape (8,)

这是我的代码:

from preprocess import *
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D
from keras.utils import to_categorical

# Second dimension of the feature is dim2
feature_dim_2 = 11

# Save data to array file first
save_data_to_array(max_len=feature_dim_2)

# # Loading train set and test set
X_train, X_test, y_train, y_test = get_train_test()

# # Feature dimension
feature_dim_1 = 20
channel = 1
epochs = 10
batch_size = 4
verbose = 1
num_classes = 9

# Reshaping to perform 2D convolution
X_train = X_train.reshape(X_train.shape[0], feature_dim_1, feature_dim_2, channel)
X_test = X_test.reshape(X_test.shape[0], feature_dim_1, feature_dim_2, channel)
y_train_hot = to_categorical(y_train)
y_test_hot = to_categorical(y_test)

def get_model():
    model = Sequential()
    model.add(Conv2D(32, kernel_size=(2, 2), activation='relu', input_shape=(20,11,1)))
    model.add(Conv2D(64, kernel_size=(2, 2), activation='relu'))
    model.add(Conv2D(128, kernel_size=(2, 2), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.5))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(64, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(9, activation='softmax'))
    model.compile(loss='categorical_crossentropy',
                  optimizer='adam',
                  metrics=['accuracy'])
    model.summary()
    return model

# Predicts one sample
def predict(filepath, model):
    sample = wav2mfcc(filepath)
    sample_reshaped = sample.reshape(1, feature_dim_1, feature_dim_2, channel)
    return get_labels()[0][
            np.argmax(model.predict(sample_reshaped))
    ]


model = get_model()
model.fit(X_train, y_train_hot, batch_size=batch_size, epochs=epochs, verbose=verbose, 
    validation_data=(X_test, y_test_hot))

0 个答案:

没有答案