Python 使用BatchDataset和numpy数组类型的混合输入拟合keras模型

Python 使用BatchDataset和numpy数组类型的混合输入拟合keras模型,python,numpy,tensorflow,machine-learning,keras,Python,Numpy,Tensorflow,Machine Learning,Keras,我制作了一个接收两个输入的模型。当我用两个numpy阵列来匹配模型时,它就工作了。下面是一个例子: model.fit(x=[image_input, other_features], y = y, epochs=epochs) 但是,我的问题是其他\u功能是一个numpy数组,图像\u输入使用tf.keras.preprocessing.image\u dataset\u从\u目录加载kera。我面临的问题是: 如何从图像\u输入中正确给出y?当我只使用一个输入对模型进行训练时,image\

我制作了一个接收两个输入的模型。当我用两个numpy阵列来匹配模型时,它就工作了。下面是一个例子:

model.fit(x=[image_input, other_features], y = y, epochs=epochs)
但是,我的问题是
其他\u功能
是一个numpy数组,
图像\u输入
使用
tf.keras.preprocessing.image\u dataset\u从\u目录
加载kera。我面临的问题是:

  • 如何从
    图像\u输入中正确给出y?当我只使用一个输入对模型进行训练时,
    image\u输入
    y
    被打包在模型中,因此我不必在其他参数中指定它
  • 如何使用
    numpy.array
    放置
    BatchDataset
    ?无论如何,当我这样做时,我收到了错误:
  • ValueError:找不到可以处理输入的数据适配器:(包含类型为{“”“”}的值),
    
    好的,我能解决它。我将写详细的解决方案,因为我看到类似的问题张贴了很多次没有答案。这是混合输入,解决方案是依赖自定义生成器

    第一步是制作自定义生成器。您必须返回输入+输出的列表/目录。以下是我的生成器的示例代码:

    def generator(subset, batch_size=256):
        i = 0
        DIR = f"data/{subset}"
        image_files = pd.read_csv(f"{DIR}.csv")
        while True:
            batch_x = [list(), list()] # I have two input: image + feature vector
            batch_y = list() # output
            for b in range(batch_size):
                if i == len(image_files):
                    i = 0
                filename = image_files.loc[i, "filename"]
                label = image_files.loc[i, "Class"]
                image_file_path = f'{DIR}/{label}/{filename}'
                i += 1
                image = cv2.imread(image_file_path, 0)
                batch_x[0].append(image)
                feat = get_feature_vector(filename)
                batch_x[1].append(feat)
                batch_y.append(one_hot(label))
    
            batch_x[0] = np.array(batch_x[0])  # convert each list to array
            batch_x[1] = np.array(batch_x[1])
            batch_y = np.array(batch_y)
            yield batch_x, batch_y
    
    然后,利用泛函张量流建立模型。拟合数据后,使用所需的参数调用生成器:

    history = model.fit(generator('train'),
                                 validation_data = generator('validate'))
    
    history = model.fit(generator('train'),
                                 validation_data = generator('validate'))