将多个数据集输入张量流模型

您好,我正在尝试在模型中输入多个数据集。这是我的问题的一个例子,但在我的例子中,我的模型之一有 2 个输入参数,而另一个模型有 1 个。我在我的案例中遇到的错误是:


Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'tensorflow.python.data.ops.dataset_ops.BatchDataset'>", "<class 'tensorflow.python.data.ops.dataset_ops.TakeDataset'>"}), <class 'NoneType'>

代码:


import tensorflow as tf


# Create first model

model1 = tf.keras.Sequential()

model1.add(tf.keras.layers.Dense(1))

model1.compile()

model1.build([None,3])


# Create second model

model2 = tf.keras.Sequential()

model2.add(tf.keras.layers.Dense(1))

model2.compile()

model2.build([None,3])



# Concatenate

fusion_model = tf.keras.layers.Concatenate()([model1.output, model2.output])

t = tf.keras.layers.Dense(1, activation='tanh')(fusion_model)

model = tf.keras.models.Model(inputs=[model1.input, model2.input], outputs=t)

model.compile()


#Datasets

ds1 = tf.data.Dataset.from_tensors(([1,2,3],1))

ds2 = tf.data.Dataset.from_tensors(([1,2,3], 2))


print(ds1)

print(ds2)

# Fit

model.fit([ds1,ds2])

运行此示例代码会产生:


Failed to find data adapter that can handle input: (<class 'list'> containing values of types {"<class 'tensorflow.python.data.ops.dataset_ops.TensorDataset'>"}), <class 'NoneType'>

我需要使用数据集模块,因为它们提供内置的数据延迟加载。


摇曳的蔷薇
浏览 1567回答 3
3回答

慕桂英546537

正如评论中所述,.fitTensorFlow 模型中的 TensorFlow 函数不支持数据集列表。如果您确实想使用数据集,则可以使用字典作为输入,并命名输入层以与字典匹配。操作方法如下:model1 = tf.keras.Sequential(name="layer_1")model2 = tf.keras.Sequential(name="layer_2")model.summary()ds1 = tf.data.Dataset.from_tensors(({"layer_1": [[1,2,3]],&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"layer_2": [[1,2,3]]}, [[2]]))model.fit(ds1)一个更简单的选择是简单地使用张量而不是数据集。.fit支持张量列表作为输入,因此只需使用它即可。model = tf.keras.models.Model(inputs=[model1.input, model2.input], outputs=t)model.compile(loss='mse')model.summary()a = tf.constant([[1, 2, 3]])b = tf.constant([[1, 2, 3]])c = tf.constant([[1]])model.fit([a, b], c)

qq_笑_17

如果您感兴趣,您还可以使用 tf.data.Dataset.zip() 和字典解决多输入问题。我最近遇到了一个类似的问题,我需要将图像和值向量输入到单个模型中,并在其中连接中间模型。我使用这里的tfdata_unzip()函数从最初使用该函数创建的标签张量中解压缩我的图像张量。然后,我使用 .rezip 将数据集重新压缩在一起。image_dataset_from_directory()tf.data.Dataset.zip()在定义模型时,我使用了功能 API 并为每个输入层分配了一个名称:import tensorflow as tffrom tensorflow.keras.layers import *# create input image layerin_image = Input(shape=(1305,2457,3), name='input_image')# create input vector layerin_vector = Input(shape=(1,), name='input_vector')我的完整工作流程类似于以下内容:# use tfdata_unzip() to separate input images from labelsinput_images, input_labels = tfdata_unzip(input_dat)# input vector was created using tf.data.Dataset.from_tensor_slices()# using [1,2,3,4] as a placeholder for my original vector of valuesin_vector = tf.data.Dataset.from_tensor_slices([1,2,3,4])# create a new input Dataset using .zip()# data is structured as (1) a dictionary of inputs (input_images,in_vector) and (2) their associated labels (input_labels)model_inputs = tf.data.Dataset.zip(({"input_image":input_images, "input_vector":in_vector}, input_labels))# if you then wanted to batch, cache, and/or prefetch the dataset you could do so using the followingbatchsize = 32model_inputs = model_inputs.batch(batchsize).cache().prefetch(buffer_size=tf.data.AUTOTUNE)然后,可以通过调用类似以下内容来拟合模型:model.fit(inputs=model_inputs, outputs=predicted_class)因为model_inputs是带有标签的数据集,所以您不需要y=input_labels在 model.fit() 调用中定义 a 。我还应该提到,我对验证数据进行了相同的数据重构,并通过添加将其传递给 model.fit() 函数validation_data=model_validation_data,其中“model_validation_data”类似于 model_inputs 结构。这就是我能够解决 TF 多模态模型的多个输入问题的方法。乐意讨论出现的任何问题或其他解决方案。

慕的地8271018

当我尝试使用使用 text_dataset_from_directory 函数构建的两个数据集时,我遇到了同样的问题。对我来说,连接数据集不是一个解决方案,因为每个数据集可能会通过不同的 Keras 层。所以我所做的是构建一个自定义的“fit_generator”。这会将 Dataset 对象转换为 Keras 支持多输入的数组。def fit_generator(dataset, batch_size):&nbsp; X = []&nbsp; y = []&nbsp; for string_, int_ in dataset.batch(1):&nbsp; &nbsp; for i in range(0, len(int_[0])):&nbsp; &nbsp; &nbsp; X.append(string_[0][i].numpy())&nbsp; &nbsp; &nbsp; y.append(int_[0][i].numpy())&nbsp; X_ret = pd.DataFrame(X).to_numpy()&nbsp; y_ret = pd.DataFrame(y).to_numpy()&nbsp; return X_ret, y_ret然后你可以解构数据集train_X1, train_y1 = fit_generator(train_ds_1, batch_size)train_X2, train_y2 = fit_generator(train_ds_2, batch_size)val_X1, val_y1 = fit_generator(val_ds_1, batch_size)val_X2, val_y2 = fit_generator(val_ds_2, batch_size)然后你可以用命名输入创建字典train_X = {'Input1': train_X1, 'Input2': train_X2}train_y = {'Input1': train_y1, 'Input2': train_y2}val_X = {'Input1': val_X1, 'Input2': val_X2}val_y = {'Input1': val_y1, 'Input2': val_y2}然后你可以像这样调用fit方法model.fit(x=train_X, y=train_y1, validation_data=[val_X,val_y1], batch_size=batch_size, epochs=10)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python