问题
通常,人们希望用派生的特性丰富原始数据集。也就是说,需要从先前存在的列中创建新列。如何使用tf.Dataset以高效(最好是就地)的方式实现这一点?
PS:我试着使用tf.data.Dataset.map()、tf.data.Dataset.apply()和tf.map(),但是找不到正确的语法来完成下面的演示。
最小工作示例
为了展示我想做的事情,我将使用熊猫的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请注意,尽管我在这里使用的是熊猫的apply(),但我真正想要的是直接在整个tf.Dataset上工作的东西,而不仅仅是其中的一批。
发布于 2020-04-10 22:18:28
假设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())https://stackoverflow.com/questions/61148307
复制相似问题