python - 从 tensorflow 中的向量创建二进制张量

标签 python numpy tensorflow

我从一个包含 N 个整数条目的一维 numpy 数组 x(或 tensorflow 张量)开始。每个条目都小于或等于 N。 我现在想创建一个张量 Y 形状为 (N,N)(即 NxN 矩阵),其中 Y[i,j]=0 如果 x[i]!=x[j]Y[i,j]=1 如果 x[i]==x[j].

使用 numpy 的例子:

import numpy as np
x=np.array([1,2,1,2,3,4,2])
Y=np.zeros((x.shape[0],x.shape[0]))
for i in range(x.shape[0]):
    for j in range(x.shape[0]):
        if x[i]==x[j]:
            Y[i,j]=1

输出

array([[ 1.,  0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  1.,  0.,  0.,  1.],
       [ 1.,  0.,  1.,  0.,  0.,  0.,  0.],
       [ 0.,  1.,  0.,  1.,  0.,  0.,  1.],
       [ 0.,  0.,  0.,  0.,  1.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  1.,  0.],
       [ 0.,  1.,  0.,  1.,  0.,  0.,  1.]])

如何在纯 tensorflow 代码中高效地创建相同的函数?

并且:如果我有一个额外的批处理维度,那么输入 x 的形状为 (B,N) 并且我期望输出 Y 形状为 (B,N,N)。这些批处理都是相互独立的。

最佳答案

x reshape 为两种不同的形状,(B, 1, N)(B, N, 1) 这样它们就可以正确广播,然后比较这两个张量,结果将是您需要的 1True0False:

import tensorflow as tf    
import numpy as np
x=np.array([1,2,1,2,3,4,2])

t = tf.constant(x)

r = tf.cast(
  tf.equal(
    tf.reshape(t, (-1, 1, t.shape[-1].value)), 
    tf.reshape(t, (-1, t.shape[-1].value, 1))
  ), tf.int8)

sess = tf.Session()

sess.run(r)
#array([[[1, 0, 1, 0, 0, 0, 0],
#        [0, 1, 0, 1, 0, 0, 1],
#        [1, 0, 1, 0, 0, 0, 0],
#        [0, 1, 0, 1, 0, 0, 1],
#        [0, 0, 0, 0, 1, 0, 0],
#        [0, 0, 0, 0, 0, 1, 0],
#        [0, 1, 0, 1, 0, 0, 1]]], dtype=int8)

关于python - 从 tensorflow 中的向量创建二进制张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47816231/

相关文章:

python - 使 numpy.savez 具有确定性

python - tensorflow 中两个点云之间的倒角距离

python 多个输出变量作为输入

python - 从哪里获取 Werkzeug 的 send_file 的 'environ' 参数?

python - pyodbc 错误 : 'pyodbc.Cursor' object has no attribute 'commit'

python - 使用 pdb 附加进程

python - 以有效的方式用大小为 (k,m) 的 n 矩阵构建大小为 (n*k, m) 的数组

python - Python 的 Numpy 库中的复合赋值运算符

tensorflow - Tensorflow 的 PTB LSTM 示例中批处理是如何迭代的?

python-3.x - Tensorflow 命令 tf.test.is_gpu_available() 返回 False