Idea
To compute pairwise op you can do the following trick: expand the vector to two 2-dimensional vectors: [n, 1]
and [1, n]
, and apply the op to them. Due to broadcasting it will produce the [n, n]
matrix filled with op results for all pairs inside the vector.
In your case, an op is a comparison, but it can be any binary operation.
Tensorflow
For illustration, here are two one-liners. The first one produces the boolean pairwise matrix, the second one - the matrix of -1
and 1
(what you asked).
import tensorflow as tf
tf.InteractiveSession()
v = tf.constant([1, 2, 3, 4, 1])
x = tf.equal(v[:, tf.newaxis], v[tf.newaxis, :])
print(x.eval())
x = 1 - 2 * tf.cast(x, tf.float32)
print(x.eval())
Result:
[[ True False False False True]
[False True False False False]
[False False True False False]
[False False False True False]
[ True False False False True]]
[[ 1 -1 -1 -1 1]
[-1 1 -1 -1 -1]
[-1 -1 1 -1 -1]
[-1 -1 -1 1 -1]
[ 1 -1 -1 -1 1]]
Numpy
The same in numpy is even simpler using np.where
:
import numpy as np
v = np.array([1, 2, 3, 4, 1])
x = v[:, np.newaxis] == v[np.newaxis, :]
print(x)
x = np.where(x, 1, -1)
print(x)
Output is the same:
[[ True False False False True]
[False True False False False]
[False False True False False]
[False False False True False]
[ True False False False True]]
[[ 1 -1 -1 -1 1]
[-1 1 -1 -1 -1]
[-1 -1 1 -1 -1]
[-1 -1 -1 1 -1]
[ 1 -1 -1 -1 1]]