检查目标期望的密集_2有形状(13)但得到形状的数组(40)时出错

时间:2018-05-23 11:24:09

标签: python neural-network keras anaconda artificial-intelligence

你好我正在写一个神经元来确定计算数字

def get_image_size():
    img = cv2.imread('gestures/0/100.jpg', 0)
    return img.shape // 50*50

def get_num_of_classes():
    return len(os.listdir('gestures/')) //13classes

image_x, image_y = get_image_size()

CNN模型

def cnn_model():
    num_of_classes = get_num_of_classes()
    model = Sequential()
    model.add(Conv2D(32, (5,5), input_shape=(image_x, image_y, 1), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))
    model.add(Conv2D(64, (5,5), activation='relu'))
    model.add(MaxPooling2D(pool_size=(5, 5), strides=(5, 5), padding='same'))
    model.add(Flatten())
    model.add(Dense(1024, activation='relu'))
    model.add(Dropout(0.4))
    model.add(Dense(num_of_classes, activation='softmax'))
    sgd = optimizers.SGD(lr=1e-4)
    model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])
    filepath="cnn_model_keras2.h5"
    checkpoint1 = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max')
    #checkpoint2 = ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')
    callbacks_list = [checkpoint1]
    return model, callbacks_list

题库

def train():
    with open("train_images", "rb") as f:
        train_images = np.array(pickle.load(f))
    with open("train_labels", "rb") as f:
        train_labels = np.array(pickle.load(f), dtype=np.int32)

    with open("test_images", "rb") as f:
        test_images = np.array(pickle.load(f))
    with open("test_labels", "rb") as f:
        test_labels = np.array(pickle.load(f), dtype=np.int32)

    train_images = np.reshape(train_images, (train_images.shape[0], image_x, image_y, 1))
    test_images = np.reshape(test_images, (test_images.shape[0], image_x, image_y, 1))
    train_labels = np_utils.to_categorical(train_labels)
    test_labels = np_utils.to_categorical(test_labels)

    model, callbacks_list = cnn_model()
    model.fit(train_images, train_labels, validation_data=(test_images, test_labels), epochs=50, batch_size=100, callbacks=callbacks_list)
    scores = model.evaluate(test_images, test_labels, verbose=0)
    print("CNN Error: %.2f%%" % (100-scores[1]*100))

但是我收到了这个错误:ValueError: Error when checking target: expected dense_1 to have shape (13,) but got array with shape (40,)我搜索了一些解决方案,但没有任何效果,如果有人知道如何解决它,请

1 个答案:

答案 0 :(得分:0)

错误表示您用于培训的标签数量与您预测的不同。查看代码,看起来像num_of_classes != train_labels.shape[1]。如果您只有[3, 7, 1]等类别标签的向量,那么您可以使用loss='sparse_categorical_crossentropy'来为您训练时对目标进行编码。