Keras卷积神经网络中的“未知节点”错误

时间:2019-06-13 10:07:08

标签: image-processing keras conv-neural-network tf.keras

我在Keras中具有以下(2D)卷积神经网络,用于使用二进制标签进行图像分类:

model = keras.Sequential()
model.add(Conv2D(32, kernel_size=5, activation='relu', input_shape=(128, 128, 1)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(64, kernel_size=5, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Flatten())
model.add(Dense(1024, activation="relu"))
model.add(Dense(2, activation="softmax"))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

要训练它,我有很多(.jpeg)图像文件,但是太多了,无法一次全部加载。因此,我使用以下生成器(和预处理):

def load_preprocess(path):
    img = img_to_array(load_img(path, target_size=(128, 128)))
    output = rgb_to_grayscale(img)
    output = tf.reshape(output, (-1,128, 128, 1))
    return output

def image_generator(paths, labels, batch_size=32):
    while True:
        for i in range(0, len(paths), batch_size):
            images = [load_preprocess(path) for path in paths[i:i+batch_size]]
            target = labels[i:i+batch_size]

            yield(images, target)

我尝试使用来训练网络

model.fit_generator(image_generator(train_paths, train_labels), steps_per_epoch=int(np.ceil(len(train_paths)/32)), epochs=1)

这里train_paths是路径列表,train_labels是具有两列的二进制numpy数组。

但是,这给了我以下错误:

InvalidArgumentError: Requested tensor connection from unknown node: "conv2d_input:0".

什么原因导致此错误,我该如何解决?我尝试使用Google搜索,但没有发现任何成功。

1 个答案:

答案 0 :(得分:0)

我发现了错误:图像是张量,应该转换为数组。我这样做如下:

def image_generator(paths, labels, batch_size=32):
    sess = tf.Session()
    while True:
        for i in range(0, len(paths), batch_size):
            with sess.as_default():
                images = [load_preprocess(path).eval() for path in paths[i:i+batch_size]]
            target = labels[i:i+batch_size]

            yield(np.array(images), target)