首页 > 解决方案 > 如何修复“ValueError:检查目标时出错:预期的 dense_39 有 4 个维度,但得到了形状为 (10, 2) 的数组”?

问题描述

我是迁移学习和 Cnn 的新手,只是在玩 cnn 并得到了这个错误。尝试了很多解决方案,但没有一个有效。

import numpy as np
import keras
from keras import backend as k
from keras.layers.core import Dense
from keras.layers import Flatten
from keras.layers import GlobalMaxPooling2D
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing import image
from keras.models import Model
from keras.applications import imagenet_utils
from sklearn.metrics import confusion_matrix
import itertools
import matplotlib.pyplot as plt
%matplotlib inline

mobile = keras.applications.mobilenet.MobileNet()

#mobile.summary()
train_path = 'chest_xray/train'
val_path = 'chest_xray/val'
test_path = 'chest_xray/test'

train_batch = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet.preprocess_input).flow_from_directory(
              train_path,
              target_size = (224,224),
              batch_size = 10)
test_batch = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet.preprocess_input).flow_from_directory(
              test_path,
              target_size = (224,224),
              batch_size = 10,
              shuffle = False)
val_batch = ImageDataGenerator(preprocessing_function=keras.applications.mobilenet.preprocess_input).flow_from_directory(
              val_path,
              target_size = (224,224),
              batch_size = 10)

def prepare_image(file):
  image_path = ''
  img = image.load_img(image_path+file,target_size = (224,224))
  img_array = image.img_to_array(img)
  img_array_dims = np.expand_dims(img_array,axis = 0)
  return keras.applications.mobilenet.preprocess_input(img_array_dims)


x = mobile.layers[-60].output
predictions = Dense(1,activation='softmax')(x)

model = Model(inputs = mobile.input,outputs = predictions)
print(mobile.input)
#model.summary()

for layer in model.layers[:-5]:
  layer.trainable = False

model.compile(Adam(lr=.0001),loss='categorical_crossentropy',metrics=['accuracy'])

model.fit_generator(train_batch,
                    steps_per_epoch=4,
                    validation_data=val_batch,
                    validation_steps=2,
                    epochs = 30)

我正在使用 mobilenet 进行迁移学习,每次都会发现错误。似乎没有一个解决方案有效。尝试使用 Flatten() 然后 2dmaxpooling() 但没有结果。

错误:

ValueError Traceback (most recent call last)
<ipython-input-187-08820ea8d15a> in <module>()
      3                     validation_data=val_batch,
      4                     validation_steps=2,
----> 5                     epochs = 30)

值错误:检查目标时出错:预期 dense_39 有 4 个维度,但得到的数组形状为 (10, 2)

标签: deep-learningconv-neural-network

解决方案


MobileNet您要切割 (-60)的层是conv_dw_5_relu具有输出尺寸(None, 28, 28, 256)的。因此,在将 Dense 层连接到它之前,您必须将其展平。

工作代码

mobile = keras.applications.mobilenet.MobileNet()

x = mobile.layers[-60].output
x = Flatten()(x)
predictions = Dense(2,activation='softmax')(x)

model = Model(inputs = mobile.input,outputs = predictions)
#model.summary()

model.compile(Adam(lr=.0001),loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(np.random.rand(10, 224, 224, 3), np.random.rand(10,2))

推荐阅读