WARNING:tensorflow:Model 是用形状 (4, 112, 112, 3) 构造的输入 ...,但它是在形状不兼容的输入上调用的 ((None, 112)
WARNING:tensorflow:Model was constructed with shape (4, 112, 112, 3) for input ..., but it was called on an input with incompatible shape ((None, 112)
我训练了一个模型并将其保存为 h5 文件。当我重用模型并尝试使用图像进行预测时,它会抛出一个错误,指出它不兼容。
如何消除警告?
代码如下:
CATEGORIES = ["Tuberculosis", "Normal"]
def prepare(filepath):
IMG_SIZE = 112
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
model = tf.keras.models.load_model("tuberculosis.h5")
prediction = model.predict([prepare("test.jpg")])
print(CATEGORIES[int(prediction[0][0])])
这是它抛出的错误:
WARNING:tensorflow:Model was constructed with shape (4, 112, 112, 3) for input KerasTensor(type_spec=TensorSpec(shape=(4, 112, 112, 3), dtype=tf.float32, name='conv2d_input'), name='conv2d_input', description="created by layer 'conv2d_input'"), but it was called on an input with incompatible shape (None, 112).
ValueError
Traceback (most
recent call last)
<ipython-input-79-6d3f8245e17a> in <module>()
----> 1 prediction = model.predict([prepare("test.jpg")])
2 print(CATEGORIES[int(prediction[0][0])])
1 frames
/usr/local/lib/python3.7/dist-
packages/tensorflow/python/framework/func_graph.py in
autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-
except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1801, in predict_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1790, 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 1783, in run_step **
outputs = model.predict_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1751, in predict_step
return self(x, training=False)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, 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 228, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" '
ValueError: Exception encountered when calling layer "sequential" (type Sequential).
Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 112)
Call arguments received:
• inputs=('tf.Tensor(shape=(None, 112), dtype=uint8)',)
• training=False
• mask=None
错误是说您传递的图像形状错误,输入有 3 个通道。如果您的输入图像有 3 个通道,这可能有效:
def prepare(filepath):
IMG_SIZE = 112
img_array = cv2.imread(filepath)
img_array = cv2.cvtColor(img_array ,cv2.COLOR_BGR2RGB)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3)
这个错误来自输入的形状,你可以试试这个:
import tensorflow as tf
import cv2
IMAGE_CHANNEL = 1 # or 3
def prepare(filepath):
IMG_SIZE = 112
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, IMAGE_CHANNEL)
x = tf.keras.Input(shape=(112,112,IMAGE_CHANNEL))
y = tf.keras.layers.Dense(16, activation='softmax')(x)
model = tf.keras.Model(x, y)
model.summary()
prediction = model.predict([prepare("test.jpg")])
print(prediction)
输出:
Model: "model_11"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_17 (InputLayer) [(None, 112, 112, 1)] 0
dense_13 (Dense) (None, 112, 112, 16) 32
=================================================================
Total params: 32
Trainable params: 32
Non-trainable params: 0
_________________________________________________________________
[[[[2.40530210e-15 1.25257872e-18 2.81339079e-01 ... 1.10927344e-20
1.28210900e-22 3.45369773e-24]
[1.21484684e-15 5.40451430e-19 2.79041141e-01 ... 4.33733043e-21
4.56826763e-23 1.14132918e-24]
[3.09763760e-16 1.00567346e-19 2.74375856e-01 ... 6.62814917e-22
5.79706900e-24 1.24585123e-25]
...
我训练了一个模型并将其保存为 h5 文件。当我重用模型并尝试使用图像进行预测时,它会抛出一个错误,指出它不兼容。
如何消除警告?
代码如下:
CATEGORIES = ["Tuberculosis", "Normal"]
def prepare(filepath):
IMG_SIZE = 112
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 1)
model = tf.keras.models.load_model("tuberculosis.h5")
prediction = model.predict([prepare("test.jpg")])
print(CATEGORIES[int(prediction[0][0])])
这是它抛出的错误:
WARNING:tensorflow:Model was constructed with shape (4, 112, 112, 3) for input KerasTensor(type_spec=TensorSpec(shape=(4, 112, 112, 3), dtype=tf.float32, name='conv2d_input'), name='conv2d_input', description="created by layer 'conv2d_input'"), but it was called on an input with incompatible shape (None, 112).
ValueError
Traceback (most
recent call last)
<ipython-input-79-6d3f8245e17a> in <module>()
----> 1 prediction = model.predict([prepare("test.jpg")])
2 print(CATEGORIES[int(prediction[0][0])])
1 frames
/usr/local/lib/python3.7/dist-
packages/tensorflow/python/framework/func_graph.py in
autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-
except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise
ValueError: in user code:
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1801, in predict_function *
return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1790, 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 1783, in run_step **
outputs = model.predict_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1751, in predict_step
return self(x, training=False)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, 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 228, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" '
ValueError: Exception encountered when calling layer "sequential" (type Sequential).
Input 0 of layer "conv2d" is incompatible with the layer: expected min_ndim=4, found ndim=2. Full shape received: (None, 112)
Call arguments received:
• inputs=('tf.Tensor(shape=(None, 112), dtype=uint8)',)
• training=False
• mask=None
错误是说您传递的图像形状错误,输入有 3 个通道。如果您的输入图像有 3 个通道,这可能有效:
def prepare(filepath):
IMG_SIZE = 112
img_array = cv2.imread(filepath)
img_array = cv2.cvtColor(img_array ,cv2.COLOR_BGR2RGB)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, 3)
这个错误来自输入的形状,你可以试试这个:
import tensorflow as tf
import cv2
IMAGE_CHANNEL = 1 # or 3
def prepare(filepath):
IMG_SIZE = 112
img_array = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE, IMAGE_CHANNEL)
x = tf.keras.Input(shape=(112,112,IMAGE_CHANNEL))
y = tf.keras.layers.Dense(16, activation='softmax')(x)
model = tf.keras.Model(x, y)
model.summary()
prediction = model.predict([prepare("test.jpg")])
print(prediction)
输出:
Model: "model_11"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
input_17 (InputLayer) [(None, 112, 112, 1)] 0
dense_13 (Dense) (None, 112, 112, 16) 32
=================================================================
Total params: 32
Trainable params: 32
Non-trainable params: 0
_________________________________________________________________
[[[[2.40530210e-15 1.25257872e-18 2.81339079e-01 ... 1.10927344e-20
1.28210900e-22 3.45369773e-24]
[1.21484684e-15 5.40451430e-19 2.79041141e-01 ... 4.33733043e-21
4.56826763e-23 1.14132918e-24]
[3.09763760e-16 1.00567346e-19 2.74375856e-01 ... 6.62814917e-22
5.79706900e-24 1.24585123e-25]
...