python - tf 的示例。group_by_reducer?
问题描述
有人可以给我看一个 tf.data.experimental.group_by_reducer 的例子吗?我发现文档很棘手,无法完全理解。
如何使用它来计算平均值?
解决方案
假设我们提供了一个数据集,['ids', 'features']
我们希望通过添加'features'
对应的相同来对数据进行分组'ids'
。我们可以使用tf.group_by_reducer(key_func, reducer)
来实现这一点。
原始数据
ids | features
--------------
1 | 1
2 | 2.2
3 | 7
1 | 3.0
2 | 2
3 | 3
所需数据
ids | features
--------------
1 | 4
2 | 4.2
3 | 10
TensorFlow 代码:
import tensorflow as tf
tf.enable_eager_execution()
ids = [1, 2, 3, 1, 2, 3]
features = [1, 2.2, 7, 3.0, 2, 3]
# Define reducer
# Reducer requires 3 functions - init_func, reduce_func, finalize_func.
# init_func - to define initial value
# reducer_func - operation to perform on values with same key
# finalize_func - value to return in the end.
def init_func(_):
return 0.0
def reduce_func(state, value):
return state + value['features']
def finalize_func(state):
return state
reducer = tf.contrib.data.Reducer(init_func, reduce_func, finalize_func)
# Group by reducer
# Group the data by id
def key_f(row):
return tf.to_int64(row['ids'])
t = tf.contrib.data.group_by_reducer(
key_func = key_f,
reducer = reducer)
ds = tf.data.Dataset.from_tensor_slices({'ids':ids, 'features' : features})
ds = ds.apply(t)
ds = ds.batch(6)
iterator = ds.make_one_shot_iterator()
data = iterator.get_next()
print(data)
考虑 ids == 1。我们使用 将初始值设置为 0 init_func
。将reducer_func
执行0 + 1
和1 + 3.0
操作finalize_func
并将返回 4.0。
在 group_by_reducer 函数中,key_func
是一个返回该数据行的键的函数。键应该是 Int64。在我们的例子中,我们使用 'ids' 作为我们的密钥。
推荐阅读
- batch-file - 如何使用 txt 文件在批处理脚本中填充变量。然后循环使用文本文件中的所有名称作为变量,直到用尽
- microsoft-graph-api - 通过 Microsoft-Graph 获取 Shiftpreferences
- c# - 使用未定义类的 C# 互操作库调用函数
- excel - 有条件地在 VBA 中选择一个命名范围,然后复制到另一个工作表
- python - 在 Python 中使用 addfips 将 FIPS 代码添加到 csv
- arrays - 打印或保存 tp csv 带有 unicode 字符和额外字段的 json 文件
- c# - 回复地址与请求授权时提供的回复地址不符
- c++ - c ++:在if-else条件中定义数组在退出后会擦除
- javascript - 使用 Mongoose 将 ObjectId 作为字符串保存到 MongoDB 失败
- macos - 在 Ubuntu 的远程 ssh 会话上(本地是 Mac OS 计算机),为什么当我键入“bash”时颜色会出现?