如何在 tf.Dataset 上创建添加列(即特征)?

How to create add columns (i.e., features) on a tf.Dataset?

问题

很多时候,人们想用派生的特征来丰富原始数据集。即,需要从现有列创建新列。如何以高效(最好是就地)方式使用tf.Dataset做到这一点?

PS:我试过 tf.data.Dataset.map()tf.data.Dataset.apply()tf.map(),但找不到正确的语法来执行我在下面说明的内容.

最小工作示例

为了显示我想要做什么,我将使用 pandas' apply()。例如,我正在尝试添加一个特征,该特征是泰坦尼克号数据集中 embark_town 特征的长度。

import pandas as pd
import tensorflow as tf # v. 2.0+

# Load the Titanic dataset
source = tf.keras.utils.get_file(
    "train.csv", 
    "https://storage.googleapis.com/tf-datasets/titanic/train.csv")

# Only select two features and one target for this example.
dataset = tf.data.experimental.make_csv_dataset(
    source, batch_size=5, label_name="survived", 
    select_columns=["embark_town", "age", "survived"],
    num_epochs=1, ignore_errors=True, shuffle=False)

# Add the derived feature `embark_town_len` via pandas.
batch, _ = next(iter(dataset))
batch = pd.DataFrame(batch)

print("Raw data:")
print(batch)

batch['embark_town_len'] = batch.apply(lambda x: len(x["embark_town"]), axis=1)

print("\nEnriched data:")
print(batch)

产生

Raw data:
    age     embark_town
0  22.0  b'Southampton'
1  38.0    b'Cherbourg'
2  26.0  b'Southampton'
3  35.0  b'Southampton'
4  28.0   b'Queenstown'

Enriched data:
    age     embark_town  embark_town_len
0  22.0  b'Southampton'               11
1  38.0    b'Cherbourg'                9
2  26.0  b'Southampton'               11
3  35.0  b'Southampton'               11
4  28.0   b'Queenstown'               10

请注意,虽然我在这里使用 pandas' apply(),但我真正要寻找的是可以直接对整个 tf.Dataset 起作用的东西,而不仅仅是一批其中。

假设tensorflow 2.0

import tensorflow as tf
cities_ds = tf.data.Dataset.from_tensor_slices(["Rome","Brussels"])
ages_ds = tf.data.Dataset.from_tensor_slices([5,7])
ds = tf.data.Dataset.zip((cities_ds, ages_ds)) 
ds = ds.map(lambda city, age: (city, age, tf.strings.length(city)))
for i in ds:
  print(i[0].numpy(), i[1].numpy(), i[2].numpy())