I start with a 1D numpy array x (or tensorflow tensor) with N integer entries. Every entry is smaller or equal to N.
I now want to create a tensor Y of shape (N,N) (i.e. an NxN matrix) where Y[i,j]=0 if x[i]!=x[j] and Y[i,j]=1 if x[i]==x[j].
Example with 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
Output
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.]])
How do I create the same function efficiently in pure tensorflow code?
And: What if I have an extra batch dimension, so that the input x has shape (B,N) and I expect as an ouput Y with shape (B,N,N). The batches are all independent of each other.