对时间序列数据使用 tf.data.experimental.make_csv_dataset

Using tf.data.experimental.make_csv_dataset for time series data

如何将 tf.data.experimental.make_csv_dataset 用于包含时间序列数据的 CSV 文件?

building_dataset = tf.data.experimental.make_csv_dataset(file_pattern=csv_file,
                                                        batch_size=5,num_epochs=1, shuffle=False,select_columns=feature_columns)

假定 CSV 文件已经排序 w.r.t。时间。首先,使用以下命令读取 CSV 文件:

building_dataset = tf.data.experimental.make_csv_dataset(file_pattern=csv_file,
                                                        batch_size=5,num_epochs=1, shuffle=False,select_columns=feature_columns)

然后定义一个 pack_features_vector 以转换为特征向量并使用 flat_map() 取消批处理。张量也转换为 float32。

def pack_features_vector(features):
    """Pack the features into a single array."""
    
    features = tf.stack([tf.cast(x,tf.float32) for x in list(features.values())], axis=1)
    return features

   
building_dataset = building_dataset.map(pack_features_vector)
building_dataset = building_dataset.flat_map(lambda x: tf.data.Dataset.from_tensor_slices(x))
for feature in building_dataset.take(1):
    print('Stacked tensor:',feature)

然后使用window和平面图方法。

building_dataset = building_dataset.window(window_size, shift=1, drop_remainder=True)
building_dataset = building_dataset.flat_map(lambda window: window.batch(window_size))

然后使用map方法分离特征和标签。

building_dataset = building_dataset.map(lambda window: (window[:,:-1], window[-1:,-1]))
for feature, label in building_dataset.take(5):
    print(feature.shape)
    print('feature:',feature[:,0:4])
    print('label:',label)

最后使用 batch() 创建批次并用作模型训练的输入。

building_dataset = building_dataset.batch(32)