假设我有一个张量 y
,形状为 (batch_size, n)
,其中包含整数。我正在寻找一个从输入y
创建两个新张量的tensorflow函数。
第一个返回值w1
应具有形状(batch_size, n)
并包含在位置b,i
,超过数量y[b,i]
中的整数出现在 y[b]
中的次数。如果 y[b,i] 为零,则 w1[b,i]=0 也为零。示例:
第二个返回值 w2
应仅包含 y
每批(或行)中不同整数(0 除外)数量的 1。
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做到这一点呢?
最佳答案
您可以使用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]
关于python - 计算 tensorflow 中每个维度的元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50715065/