【问题标题】:how to use dict in tensorflow如何在张量流中使用dict
【发布时间】:2020-08-06 14:44:42
【问题描述】:

我有一个简单的 python 程序,比如

from collections import defaultdict
import math

x = ["a", "b", "a", "c", "d"]
y = [0.1, 0.2, 0.3, 0.4, 0.5]
z = defaultdict(float)
for i in range(len(x)):
    z[x[i]] += y[i]

result = [math.log(z[c]+1) for c in z]

我想将代码重写为 tensorflow,但不知道该怎么做。请帮忙!

【问题讨论】:

    标签: python tensorflow collections tensor defaultdict


    【解决方案1】:

    我认为你可以在 tensorflow 1.8 中这样做

    import tensorflow as tf
    
    x = tf.constant(["a", "b", "a", "c", "d"])
    y = tf.constant([0.1, 0.2, 0.3, 0.4, 0.5])
    
    u, segment_ids, counts = tf.unique_with_counts(x)
    t = tf.unsorted_segment_sum(y, segment_ids, tf.shape(u)[0])
    r = tf.log(t + 1)
    
    s = tf.Session()
    print(s.run(u))
    print(s.run(t))
    print(s.run(r))
    

    输出

    [b'a' b'b' b'c' b'd']
    [0.4 0.2 0.4 0.5]
    [0.3364722 0.1823216 0.3364722 0.4054651]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-23
      • 2018-10-25
      • 2019-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-18
      • 2018-06-09
      相关资源
      最近更新 更多