如何用多个图像训练序列模型

问题描述 投票:0回答:1

传递多个图像进行训练时出现错误。但是当只传递一张图像时就很好了。图像大小相同。

这是代码:

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers, datasets, models

# Load the template image
template_image = tf.keras.preprocessing.image.load_img('Template.jpg')
template_array = tf.keras.preprocessing.image.img_to_array(template_image)

# Load the actual image
actual_image = tf.keras.preprocessing.image.load_img('Actual.jpg')
actual_array = tf.keras.preprocessing.image.img_to_array(actual_image)

# Create a model
model = tf.keras.Sequential([
  layers.InputLayer(input_shape=(template_array.shape)),
  layers.Conv2D(16, (3, 3), activation='relu'),
  layers.MaxPooling2D((2, 2)),
  layers.Conv2D(32, (3, 3), activation='relu'),
  layers.MaxPooling2D((2, 2)),
  layers.Flatten(),
  layers.Dense(64, activation='relu'),
  layers.Dense(2, activation='softmax'),
])

# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
for layer in model.layers:
    print(layer.output_shape)

template_array = template_array.reshape((1, 549, 549, 3))
actual_array = actual_array.reshape((1, 549, 549, 3))
train_x = [template_array, actual_array]
y_train = np.array([1,0])
y_train = y_train.reshape(1,2)
train_y = [y_train, y_train]

print("X shape is: ")
print(template_array.shape)
print("Y shape is: ")
print(y_train)

# Train the model
model.fit(x=train_x, y=train_y, epochs=10)

# Make predictions
predictions = model.predict([actual_array])

# Check for incorrect or missing parts
for i in range(len(predictions)):
  if predictions[i][0] > predictions[i][1]:
    print('Part {} is missing or incorrect'.format(i))

收到错误:

ValueError: Layer "sequential_28" expects 1 input(s), but it received 2 input tensors. Inputs received: 
[<tf.Tensor 'IteratorGetNext:0' shape=(None, 549, 549, 3) dtype=float32>, 
<tf.Tensor 'IteratorGetNext:1' shape=(None, 549, 549, 3) dtype=float32>]

如果我传递 x=template_array 和 y = y_train 它运行良好。但这意味着我只使用一张图像进行训练。

我是否无法使我的图像数组和相应的分类数组一次性全部通过?我如何立即传递所有列车数据?

python tensorflow machine-learning classification
1个回答
0
投票

实际上,您将两个输入传递给模型,而不是两个样本。如果要输入两个样本,则 train_x 的形状必须为 [2, 549, 549, 3]。 要实现此目的,您需要从第一个轴连接 template_array 和actual_array。

train_x = np.concatenate([template_array, actual_array], axis=0)

© www.soinside.com 2019 - 2024. All rights reserved.