deep-learning - 如何修复“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)
解决方案
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))
推荐阅读
- java - 如何使用 api Graphstream 在 android studio 中通过触摸创建节点?
- gtk - monodevelop gtk-sharp 中的 MDI 形式
- java - [TreeMap]:在一个类中创建和加载 TreeMap,并从几个单独/不同的类中访问该 Tmap
- javascript - 如何在不占用空间的情况下隐藏 html 元素 x 时间?
- python-3.x - Mac终端flake8 --version在pip3下载后找不到flake8
- c# - List<>.Append 不适用于公共、静态和初始化字段
- r - R - ggplot2:基于数据类别的曲线下的阴影区域
- algorithm - 如何证明一般多项式情况下的 Big-omega?
- c++ - 相同的未更改代码是否有可能有时运行而有时不运行?
- node.js - 无法使用 ssl 和 apache 连接到 websocket