python - 计算 tensorflow 中每个维度的元素数量

标签 python tensorflow

假设我有一个张量 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/

相关文章:

python - 欧拉计划 92

python - 如何在 Sklearn 中 reshape 我的测试数据? (特征选择)

python - 将类型实例转换为字典

tensorflow - run_inference_for_single_image(image, graph) - Tensorflow,对象检测

tensorflow - 图像分类迁移学习需要负例吗?

python - 使用 Matplotlib 自定义 X 轴日期范围

python - 如何转置 Pandas.Groupby 的结果

regex - 使用正则表达式从 Tensorflow 2 中的 tf.Tensor 中提取字符串?

python - Tensorflow:如何在调用 tf.reduce_sum 时忽略数组的一部分

machine-learning - 如何使卷积神经网络接受可变大小的输入?