如何在张量流中压缩或减少地图数据集的尺寸

How to squeeze or reduce dimensions of a mapdataset in tensorflow

我有一个具有以下维度的 mapdataset 元素:

MapDataset element_spec=(TensorSpec(shape=(None, 1, 24), dtype=tf.float32, name=None), TensorSpec(shape=(None, 1, 24), dtype=tf.float32, name=None))

我想创建一个函数 api 如下:

input_ = keras.layers.Input(shape=24)
hidden1 = keras.layers.Dense(30, activation="relu")(input_)
hidden2 = keras.layers.Dense(30, activation="relu")(hidden1)
concat = keras.layers.concatenate([input_, hidden2])
output = keras.layers.Dense(1)(concat)
model = keras.models.Model(inputs=[input_], outputs=[output])

我收到以下错误

ValueError: Input 0 of layer "model_3" is incompatible with the layer: expected shape=(None, 24), found shape=(None, 1, 24)

如何减少地图数据集中的维度?我尝试了 [:, -1:, :]tf.squeeze() 方法,但它没有用。

您可以将另一个 map 函数应用于您的数据集以减少维度,然后再将您的数据集提供给您的模型:

def prepare_data(x):
  return tf.random.normal((samples, 1, 24)), tf.random.normal((samples, 1, 24))

def reduce_dimension(x, y):
  return tf.squeeze(x, axis=1), tf.squeeze(y, axis=1)

samples = 50
dataset = tf.data.Dataset.range(samples)

dataset = dataset.map(prepare_data)
print('Before reducing dimension: ', dataset.element_spec)

dataset = dataset.map(reduce_dimension)
print('After reducing dimension: ', dataset.element_spec)
Before reducing dimension:  (TensorSpec(shape=(50, 1, 24), dtype=tf.float32, name=None), TensorSpec(shape=(50, 1, 24), dtype=tf.float32, name=None))
After reducing dimension:  (TensorSpec(shape=(50, 24), dtype=tf.float32, name=None), TensorSpec(shape=(50, 24), dtype=tf.float32, name=None))

根据您的用例,您还可以简单地减少第一个 map 函数中的维度。在这里,我假设您的 MapDataset 已经存在。