层模型需要 1 个输入,但它收到了 2 个输入张量

Layer model expects 1 input(s), but it received 2 input tensors

我正在尝试 运行 下面的简单代码。

图像生成器returns 两张图像(所以,标签也是图像)。

import numpy as np
import cv2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, Input

def load_image(file):
    image = cv2.imread(file, cv2.IMREAD_UNCHANGED)
    return image

file = './B2.jpeg'

def image_generator(image):
    i = 0
    while True:
        X = image
        y = image
        
        X = np.expand_dims(X, axis=0)
        y = np.expand_dims(y, axis=0)
        
        i = i + 1
        yield [X, y]

inputs = Input(shape=(None, None, 3))
x = Conv2D(filters=3,
           kernel_size=3,
           padding='same',
           activation='relu',
           strides=1)(inputs)

model = Model(inputs=inputs, outputs=x)
model.compile(loss='mae',
              optimizer='adam')


image = load_image(file)
model.fit(image_generator(image), epochs=1)

它给了我:

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

I am using tensorflow 2.4.1 and keras 2.4.0

我正在使用这张图片

你的情况:

image_generator(image)

return一个<generator object image_generator>。要访问资源,请使用 next(generator_object).

测试这个,为我工作:

import numpy as np
import cv2
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, Input

def load_image(file):
    image = cv2.imread(file, cv2.IMREAD_UNCHANGED)
    return image

file = './image.jpg'

def image_generator(image):
    while True:
        X = image
        y = image
        
        X = np.expand_dims(X, axis=0)
        y = np.expand_dims(y, axis=0)
        
        return (X, y)

inputs = Input(shape=(None, None, 3))
x = Conv2D(filters=3,
           kernel_size=3,
           padding='same',
           activation='relu',
           strides=1)(inputs)

model = Model(inputs=inputs, outputs=x)
model.compile(loss='mae',
              optimizer='adam')


image = load_image(file)
testx,testy = image_generator(image)
model.fit(testx,testy ,epochs=1)