我正在尝试了解如何在 TensorFlow 中使用 map 和 apply 函数。目标是在将数据读入 TensorFlow 时使用所有基本数据预处理步骤,因为 map 提供了并行化操作的选项。
a_list = [b"THis is for Testing"]
将 a_list 转换为 tf 数据集格式
a_dataset = tf.data.Dataset.from_tensors(a_list)
print(list(a_dataset.as_numpy_iterator()))
[array([b'THis is for Testing'], dtype=object)]
应用 map 计算列表的 len
a_dataset_len = a_dataset.map(lambda x: len(x))
print(list(a_dataset_len.as_numpy_iterator()))
[1]
应用映射将所有字符串转换为小写
a_dataset_lower = a_dataset.map(lambda x: x.lower())
AttributeError: 'Tensor' object has no attribute 'lower'
在 a_list 上使用 apply 函数
a_dataset.apply(lambda x:len(x))
TypeError: object of type 'TensorDataset' has no len()
请帮我理解
- 为什么我无法在 map 能够执行时使用 len(x) 使用 apply 函数?
- 如何创建自己的自定义函数并在 Dataset.map 和 Dataset.apply 期间使用预先构建的函数传递它?