首页 > 解决方案 > tf 的示例。group_by_reducer?

问题描述

有人可以给我看一个 tf.data.experimental.group_by_reducer 的例子吗?我发现文档很棘手,无法完全理解。

如何使用它来计算平均值?

标签: pythontensorflow

解决方案


假设我们提供了一个数据集,['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 + 11 + 3.0操作finalize_func并将返回 4.0。

在 group_by_reducer 函数中,key_func是一个返回该数据行的键的函数。键应该是 Int64。在我们的例子中,我们使用 'ids' 作为我们的密钥。


推荐阅读