我收到以下错误:

  **File "C:\Users\sergi\Anaconda3\envs\tensorpy36gpu\lib\site-packages\keras\engine\training_utils.py", line 131, in standardize_input_data
    'with shape ' + str(data_shape))

ValueError: Error when checking target: expected activation_32 to have 4 dimensions, but got array with shape (4, 4)**


当我运行fit_generator时:

fit = model.fit_generator(trainX, steps_per_epoch=len(trainX) // batch_size, validation_data=trainY,
                          validation_steps=len(trainY) // batch_size, epochs=10, verbose=2)


代码完成:

 def model(rows, cols, channels): #channels_last

   model = Sequential()
   model.add(Conv2D(32, (3, 3), padding='same', input_shape=(rows, cols, channels)))
   model.add(Activation('relu'))
   model.add(MaxPooling2D(pool_size=(2,2)))
   model.add(Conv2D(64, (5, 5), padding='same'))
   model.add(Activation('relu'))
   model.add(MaxPooling2D(pool_size=(2,2)))
   model.add(Conv2D(128, (5, 5), padding='same'))
   model.add(Activation('relu'))
   model.add(MaxPooling2D(pool_size=(2,2)))
   model.add(Dense(4))
   model.add(Activation('softmax'))

   return model

def summarize_diagnostics(history):
    # plot loss
    plt.subplot(211)
    plt.title('Cross Entropy Loss')
    plt.plot(history.history['loss'], color='blue', label='train')
    plt.plot(history.history['val_loss'], color='orange', label='test')
    # plot accuracy
    plt.subplot(212)
    plt.title('Classification Accuracy')
    plt.plot(history.history['acc'], color='blue', label='train')
    plt.plot(history.history['val_acc'], color='orange', label='test')
    plt.show()

opt = SGD(lr=0.001)

model = model(196, 196, 3)
model.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])

datagen = ImageDataGenerator(validation_split=0.30)

batch_size = 16

trainX = datagen.flow_from_directory("./Train/", batch_size=16, target_size=(196, 196), subset='training',
                                     class_mode = 'categorical')
trainY = datagen.flow_from_directory("./Train/", batch_size=16, target_size=(196, 196), subset='validation',
                                     class_mode = 'categorical')

fit = model.fit_generator(trainX, steps_per_epoch=len(trainX) // batch_size, validation_data=trainY,
                          validation_steps=len(trainY) // batch_size, epochs=10, verbose=2)

最佳答案

您必须在Conv层和Dense层之间展平数据
image

   model.add(Conv2D(128, (5, 5), padding='same'))
   model.add(Activation('relu'))
   model.add(MaxPooling2D(pool_size=(2,2)))

   model.add(Flatten())

   model.add(Dense(4))
   model.add(Activation('softmax'))

关于python - Keras fit_generator:检查目标时出错:预期activation_32具有4个维,但数组的形状为(4,4),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57945364/

10-10 19:00