【问题标题】:Count number of elements in each dimension in tensorflow计算张量流中每个维度中的元素数
【发布时间】:2018-06-06 18:04:39
【问题描述】:

假设我有一个张量y,形状为(batch_size, n),其中包含整数。我正在寻找一个 tensorflow 函数,该函数从输入 y 创建两个新张量。

第一个返回值w1 的形状应为(batch_size, n),并在位置b,i 处包含y[b,i] 中的整数在y[b] 中出现的次数的一倍。如果y[b,i] 为零,那么w1[b,i]=0 也是。示例:

第二个返回值w2 应该简单地包含y 的每个批次(或行)中不同整数(0 除外)数量的一个。

y=np.array([[ 0,  0, 10, 10, 24, 24],  [99,  0,  0, 12, 12, 12]])
w1,w2= get_w(y)
#w1=[[0 , 0 , 0.5, 0.5, 0.5, 0.5],  [1, 0, 0, 0.33333333, 0.33333333, 0.33333333]]
#w2=[0.5,0.5]

那么,我怎样才能让 tensorflow 做到这一点?

【问题讨论】:

  • 整数出现的次数怎么可能是非整数?
  • 对不起,我搞砸了。它应该是计数的倒数。我修好了。

标签: python tensorflow


【解决方案1】:

你可以使用tf.unique_with_counts:

y = tf.constant([[0,0,10,10,24,24],[99,0,0,12,12,12]], tf.int32)

out_g = []
out_c = []
#for each row
for w in tf.unstack(y,axis=0):
    # out gives unique elements in w 
    # idx gives index to the input w
    # count gives the count of each element of out in w
    out,idx, count = tf.unique_with_counts(w)

    #inverse of total non zero elements in w
    non_zero_count = 1/tf.count_nonzero(out)

    # gather the inverse of non zero unique counts
    g = tf.cast(tf.gather(1/count,idx), tf.float32) * tf.cast(tf.sign(w), tf.float32)
    out_g.append(g)
    out_c.append(non_zero_count)
out_g = tf.stack(out_g)
out_c = tf.stack(out_c)

with tf.Session() as sess:
   print(sess.run(out_g))
   print(sess.run(out_c))

#Output:

#[[0.   0.    0.5   0.5        0.5        0.5       ]
#[1.    0.    0.    0.33333334 0.33333334 0.33333334]]

# [0.5 0.5]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多