如何使用 tensorflow.data.experimental.CsvDataset 与模型的输入形状兼容来创建小批量?

How to create mini-batches using tensorflow.data.experimental.CsvDataset compatible with model's input shape?

我打算在 TensorFlow 2 中使用 tensorflow.data.experimental.CsvDataset 训练小批量。但是 Tensor 的形状不适合我模型的输入形状。

请告诉我什么是通过 TensorFlow 数据集进行小批量训练的最佳方法。

我试过如下:

# I have a dataset with 4 features and 1 label
feature = tf.data.experimental.CsvDataset(['C:/data/iris_0.csv'], record_defaults=[.0] * 4, header=True, select_cols=[0,1,2,3])
label = tf.data.experimental.CsvDataset(['C:/data/iris_0.csv'], record_defaults=[.0] * 1, header=True, select_cols=[4])
dataset = tf.data.Dataset.zip((feature, label))

# and I try to minibatch training:
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(4,))])
model.compile(loss='mse', optimizer='sgd')
model.fit(dataset.repeat(1).batch(3), epochs=1)

我收到一个错误:

ValueError: Error when checking input: expected dense_6_input to have shape (4,) but got array with shape (1,)

因为:CsvDataset() returns 形状为 (features, batch) 的张量,但我需要它的形状为 (batch, features).

参考代码:

for feature, label in dataset.repeat(1).batch(3).take(1):
    print(feature)

# (<tf.Tensor: id=487, shape=(3,), dtype=float32, numpy=array([5.1, 4.9, 4.7], dtype=float32)>, <tf.Tensor: id=488, shape=(3,), dtype=float32, numpy=array([3.5, 3. , 3.2], dtype=float32)>, <tf.Tensor: id=489, shape=(3,), dtype=float32, numpy=array([1.4, 1.4, 1.3], dtype=float32)>, <tf.Tensor: id=490, shape=(3,), dtype=float32, numpy=array([0.2, 0.2, 0.2], dtype=float32)>)

tf.data.experimental.CsvDataset 创建一个数据集,其中数据集的每个元素对应于 CSV 文件中的一行,并由多个张量组成,即每列一个单独的张量。因此,首先你需要使用数据集的 map 方法将所有这些张量堆叠成一个张量,以便它与模型期望的输入形状兼容:

def map_func(features, label):
    return tf.stack(features, axis=1), tf.stack(label, axis=1)

dataset = dataset.map(map_func).batch(BATCH_SIZE)