我有以下代码生成有关形状的错误:
from keras.layers import Dense, Activation
from keras import Sequential
from keras.models import load_model
from tensorflow.keras.optimizers import Adam
import tensorflow
import keras
from tensorflow.python.keras.layers import Input, Dense
from tensorflow.keras.optimizers import Adam
from keras.layers import Convolution2D, MaxPooling2D, Dropout, Flatten, Dense
def nvidia_model():
model = Sequential()
model.add(Convolution2D(24,(5,5), strides=(2, 2), input_shape=(66, 200, 3), activation='relu'))
model.add(Convolution2D(36, (5,5), strides=(2, 2), activation='relu'))
model.add(Convolution2D(48, (5,5), strides=(2, 2), activation='relu'))
model.add(Convolution2D(64, (3,3), activation='relu'))
model.add(Convolution2D(64, (3,3), activation='relu'))
model.add(Flatten())
model.add(Dense(100, activation = 'relu'))
model.add(Dense(50, activation = 'relu'))
model.add(Dense(10, activation = 'relu'))
model.add(Dense(1))
optimizer = Adam(learning_rate=1e-3)
model.compile(loss='mse', optimizer=optimizer)
return model
model = nvidia_model()
print(model.summary())
history = model.fit(X_train, y_train, epochs=30,validation_data=(X_valid,y_valid),batch_size=100,verbose=1,shuffle=1)
但是,在训练第一个纪元时,我收到下面发布的错误:
Epoch 1/30
WARNING:tensorflow:Model was constructed with shape (None, 66, 200, 3) for input KerasTensor(type_spec=TensorSpec(shape=(None, 66, 200, 3), dtype=tf.float32, name='conv2d_5_input'), name='conv2d_5_input', description="created by layer 'conv2d_5_input'"), but it was called on an input with incompatible shape (None,).
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-42-e7614c3cfda1> in <module>()
----> 1 history = model.fit(X_train, y_train, epochs=30,validation_data=(X_valid,y_valid),batch_size=100,verbose=1,shuffle=1)
1 frames
/usr/local/lib/python3.7/dist-packages/keras/engine/training.py in tf__train_function(iterator)
13 try:
14 do_return = True
---> 15 retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
16 except:
17 do_return = False
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1160, in train_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1146, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1135, in run_step **
outputs = model.train_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 993, in train_step
y_pred = self(x, training=True)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 70, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 251, in assert_input_compatibility
f'Input {input_index} of layer "{layer_name}" '
ValueError: Exception encountered when calling layer "sequential_1" " f"(type Sequential).
Input 0 of layer "conv2d_5" is incompatible with the layer: expected min_ndim=4, found ndim=1. Full shape received: (None,)
Call arguments received by layer "sequential_1" " f"(type Sequential):
• inputs=tf.Tensor(shape=(None,), dtype=string)
• training=True
• mask=None
我还将此处发布的代码添加到 Codeshare| ||,这样你就可以看到我的代码了。你能帮我了解发生了什么事吗?谢谢您的帮助。 , so you can see my code. Can you help me understand what is going on? Thanks for the help.
这个错误消息告诉你,你的模型期望输入的形状是
(None, 66, 200, 3)
,但它收到的输入形状是
(None,)
。 这意味着你正在向模型传递一个形状错误的数据。
具体来说,问题出在你的
model.fit
行:
history = model.fit(X_train, y_train, epochs=30,validation_data=(X_valid,y_valid),batch_size=100,verbose=1,shuffle=1)
你的
X_train
变量的形状似乎是
(None,)
,而它应该是
(None, 66, 200, 3)
。 这表明你的训练数据没有被正确地加载或预处理。 你的
X_train
应该是一个 4 维数组,其中:
-
第一维是样本数(
None
表示可变数量的样本)。 - 第二维是图像的高度(66)。
- 第三维是图像的宽度(200)。
- 第四维是颜色通道数(3 表示 RGB 图像)。
要解决此问题,需要:
- 检查的数据加载和预处理步骤。 确保正确加载图像并将它们转换为 NumPy 数组。
-
验证
X_train
的形状。 使用print(X_train.shape)
打印其形状。 如果它不是(None, 66, 200, 3)
,则需要重新整形的数据以匹配此形状。
以下是可能需要进行的一些调整:
- 如果是从文件中加载图像: 确保使用一个库(如 OpenCV 或 PIL)加载图像,然后将它们转换为 NumPy 数组。
-
如果的数据已经是 NumPy 数组:
使用
reshape()
函数重新整形的数据以匹配所需的形状。
例如,如果的图像存储在一个名为
images
的列表中,可以使用以下代码将它们转换为形状为
(None, 66, 200, 3)
的 NumPy 数组:
import numpy as np
X_train = np.array(images)
X_train = X_train.reshape(-1, 66, 200, 3)
进行这些更改后,请再次运行的代码。 如果仍然遇到问题,请提供有关如何加载和预处理数据的更多信息,以便我提供更具体的帮助。
标签:python,tensorflow,opencv From: 73277459