ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但接收到的输入具有形状
Posted
技术标签:
【中文标题】ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但接收到的输入具有形状【英文标题】:ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape 【发布时间】:2022-01-01 13:09:58 【问题描述】:我是该主题的新手,遇到错误,谁能帮助我?
尝试使用手工数据集识别形状。
我无法解决此错误:
ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但接收到形状为 [None, 100, 100, 1] 的输入
这是我的代码:
from keras.models import Sequential
from keras.layers import Dense, Flatten, Dropout
from keras.layers import Convolution2D, MaxPooling2D
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import load_img,img_to_array
model1 = Sequential()
model1.add(Convolution2D(32, (3,3), activation='sigmoid',input_shape=(100,100,3)))
model1.add(MaxPooling2D(pool_size=(2,2)))
model1.add(Convolution2D(32,(3,3),activation='relu'))
model1.add(MaxPooling2D(pool_size=(2,2)))
model1.add(Convolution2D(64,(3,3),activation='relu'))
model1.add(Convolution2D(64,(3,3),activation='relu'))
model1.add(MaxPooling2D(pool_size=(2,2)))
model1.add(Flatten())
model1.add(Dense(64,activation='relu'))
model1.add(Dropout(0.2))
model1.add(Dense(1,activation='sigmoid'))
model1.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model1.summary()
train_datagen = ImageDataGenerator(
width_shift_range=0.2, height_shift_range=0.2,
rotation_range=40,
zoom_range=0.2,
horizontal_flip=True,
rescale=1/255,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(
rescale=0.1,
fill_mode='nearest')
# trainning
train_generator = train_datagen.flow_from_directory(
'data/train',
target_size=(100, 100),
batch_size=16,
class_mode='binary')
validation_generator = validation_datagen.flow_from_directory(
'data/validation',
target_size=(100, 100),
batch_size=16,
class_mode='binary')
h = model1.fit_generator(
train_generator,
epochs=10,
validation_data=validation_generator)
img = load_img('img.jpeg', color_mode="grayscale", target_size=(100, 100))
img = img_to_array(img)
img = img.reshape((1, img.shape[0], img.shape[1], img.shape[2]))
prediction = model1.predict(img)
'The output:'
Traceback (most recent call last):
/custom_train.py", line 68, in <module>
prediction = model1.predict(img)
\lib\site-packages\tensorflow\python\keras\engine\training.py", line 130, in _method_wrapper
return method(self, *args, **kwargs)
\lib\site-packages\tensorflow\python\keras\engine\training.py", line 1599, in predict
tmp_batch_outputs = predict_function(iterator)
\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__
result = self._call(*args, **kwds)
\lib\site-packages\tensorflow\python\eager\def_function.py", line 823, in _call
self._initialize(args, kwds, add_initializers_to=initializers)
\lib\site-packages\tensorflow\python\eager\def_function.py", line 696, in _initialize
self._stateful_fn._get_concrete_function_internal_garbage_collected( # pylint: disable=protected-access
\lib\site-packages\tensorflow\python\eager\function.py", line 2855, in _get_concrete_function_internal_garbage_collected
graph_function, _, _ = self._maybe_define_function(args, kwargs)
\lib\site-packages\tensorflow\python\eager\function.py", line 3213, in _maybe_define_function
graph_function = self._create_graph_function(args, kwargs)
\lib\site-packages\tensorflow\python\eager\function.py", line 3065, in _create_graph_function
func_graph_module.func_graph_from_py_func(
\lib\site-packages\tensorflow\python\framework\func_graph.py", line 986, in func_graph_from_py_func
func_outputs = python_func(*func_args, **func_kwargs)
\lib\site-packages\tensorflow\python\eager\def_function.py", line 600, in wrapped_fn
return weak_wrapped_fn().__wrapped__(*args, **kwds)
\lib\site-packages\tensorflow\python\framework\func_graph.py", line 973, in wrapper
raise e.ag_error_metadata.to_exception(e)
ValueError: in user code:
\lib\site-packages\tensorflow\python\keras\engine\training.py:1462 predict_function *
return step_function(self, iterator)
\lib\site-packages\tensorflow\python\keras\engine\training.py:1452 step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1211 run
return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2585 call_for_each_replica
return self._call_for_each_replica(fn, args, kwargs)
\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2945 _call_for_each_replica
return fn(*args, **kwargs)
\lib\site-packages\tensorflow\python\keras\engine\training.py:1445 run_step **
outputs = model.predict_step(data)
\lib\site-packages\tensorflow\python\keras\engine\training.py:1418 predict_step
return self(x, training=False)
\lib\site-packages\tensorflow\python\keras\engine\base_layer.py:975 __call__
input_spec.assert_input_compatibility(self.input_spec, inputs,
\lib\site-packages\tensorflow\python\keras\engine\input_spec.py:212 assert_input_compatibility
raise ValueError(
ValueError: Input 0 of layer sequential is incompatible with the layer: expected axis -1 of input shape to have value 3 but received input with shape [None, 100, 100, 1]
``
【问题讨论】:
【参考方案1】:模型的输入形状有100x100x3
的图像。所以这意味着图像有3个通道(RGB图像)。
但是,在这一行中:
img = load_img('img.jpeg', color_mode="grayscale", target_size=(100, 100))
您以灰度格式加载了 img,这意味着图像形状将是 (100x100x1),这意味着只有一个通道。
尝试将该行更改为:
img = load_img('img.jpeg', color_mode="rgb", target_size=(100, 100))
Keras documentation 表示:
color_mode:“灰度”、“rgb”、“rgba”之一。默认值:“RGB”。图像是否将转换为 1、3 或 4 通道。
【讨论】:
好的,非常感谢,问题解决了!以上是关于ValueError:层顺序的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 3,但接收到的输入具有形状的主要内容,如果未能解决你的问题,请参考以下文章
ValueError:层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]
ValueError:层顺序的输入0与层不兼容::预期的min_ndim = 4,发现ndim = 2。收到的完整形状:(无,1024)
ValueError: 层 lstm_12 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=4
ValueError: 层序号_29 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:[无,22]
ValueError: 层 lstm_21 的输入 0 与层不兼容:预期 ndim=3,发现 ndim=2。收到的完整形状:(无,546)