python - Tensorflow ValueError:层“顺序”的输入0与层不兼容:预期形状=(无,20,20,3),发现形状=(无,20,3)
问题描述
所以我正在尝试测试我训练有素的模型(图像分类器)
tl;博士我有 2 种类型的照片(20x20 像素)。第一种是有飞机破碎的照片,第二种是没有破碎飞机的照片(从天空拍摄的照片)我得到了包含文件名和标签的 csv 文件(1 - 飞机在照片上,0 - 没有飞机)这是什么我正在做:
import tensorflow as tf
import pandas as pd
from tensorflow import keras
def read_image(image_file, label):
image = tf.io.read_file(directory+image_file)
image = tf.image.decode_image(image, channels=3, dtype=tf.float32)
return image, label
def prepare_for_test(filepath):
img_array = tf.io.read_file(filepath)
img_array = tf.image.decode_image(img_array, channels=3, dtype=tf.float32)
return img_array
这是我使用 csv 文件创建 tf 数据集的方式
directory = 'avia-train/'
df = pd.read_csv(directory+'train.csv')
df['filename'] = df['filename'].apply(lambda x: x+'.png')
filenames = df['filename'].values
signs = df['sign'].values
ds_train = tf.data.Dataset.from_tensor_slices((filenames, signs))
ds_train = ds_train.map(read_image).batch(32)
我的模型:
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(20, 20, 3)),
tf.keras.layers.MaxPooling2D(2, 2),
tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
tf.keras.layers.MaxPooling2D(2,2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
model.compile(
optimizer=keras.optimizers.Adam(),
loss=[
keras.losses.BinaryCrossentropy(),
],
metrics=['accuracy'],
)
model.fit(ds_train,
epochs=5,
verbose=1)
据我了解,培训进展顺利
这是我得到的
Epoch 1/5
972/972 - 45s - loss: 0.2656 - accuracy: 0.8853
Epoch 2/5
972/972 - 7s - loss: 0.1417 - accuracy: 0.9447
Epoch 3/5
972/972 - 7s - loss: 0.1191 - accuracy: 0.9543
Epoch 4/5
972/972 - 7s - loss: 0.1030 - accuracy: 0.9608
Epoch 5/5
972/972 - 8s - loss: 0.0921 - accuracy: 0.9657
之后我尝试使用我的模型
prediction = model.predict([prepare_for_test('avia-test/00a90c41-965e-45d0-90c2-391e20cb25b7.png')])
print(prediction)
这就是我得到的
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 20, 20, 3), found shape=(None, 20, 3)
我试图在这里找到一些东西:
ValueError:层顺序的输入0与层不兼容::预期的min_ndim = 4,发现ndim = 2。收到完整形状:[无,2584]
ValueError:层顺序的输入 0 与层不兼容::预期 min_ndim=4,发现 ndim=3。收到的完整形状:[8, 28, 28]
但对我来说没有什么有用的
解决方案
我找到了解决方案,prepare_for_test函数需要更改。
import cv2
def prepare_for_test(filepath):
IMG_SIZE = 20 # my pics are 20x20 px
#if your pics are grayscaled you should use cv2.IMREAD_GRAYSCALE
img_array = cv2.imread(filepath, cv2.IMREAD_COLOR)
new_array = cv2.resize(img_array,(IMG_SIZE,IMG_SIZE))
# if your pics are grayscaled you should use (-1, IMG_SIZE, IMG_SIZE,1)
return new_array.reshape(-1, IMG_SIZE, IMG_SIZE,3)
更改后一切正常
推荐阅读
- r - If...else error 'the condition has lenght >1...' 在每个语句中都有多个操作
- robotframework - 对机器人框架的鼻子测试
- yaml - 从 Azure 管道在本地计算机上创建 clickonce 包?
- java - Oracle JDBC Thin 驱动程序:编码问题
- python - 删除字符串中连接在一起的字符和数字的部分
- amazon-web-services - 如何提前获取自动次要版本升级通知
- flutter - Flutter 类型为 'Future 的值
' 不能从方法 '_onBackPress' 中返回,因为它的返回类型是 'Future ' - rust - 迭代器的Rust“在编译时没有已知的大小”错误?
- datadog - 如何将 Vertex AI 日志与 Datadog 集成?
- swagger - 无法在 SpringDoc OpenAPI 中为动态 URL 设置映射