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

2024-03-28 15:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我将使用TensorFlow 2中的tensorflow.data.experimental.CsvDataset来训练mini-batch。但是张量的形状不适合我的模型的输入形状

请让我知道通过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()返回形状为(features, batch)的a张量,但我需要它的形状为(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)>)

Tags: numpyiddatatfbatcharraydatasetlabel
1条回答
网友
1楼 · 发布于 2024-03-28 15:27:01

tf.data.experimental.CsvDataset创建一个数据集,其中数据集的每个元素对应于CSV文件中的一行,并由多个张量组成,即每个列有一个单独的张量。因此,首先需要使用dataset的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)

相关问题 更多 >