If I multiply a vector x
(1,n) with itself tansposed, i.e. np.dot(x.T, x)
I will get a matrix in quadratic form.
If I have a matrix Xmat
(k, n), how can I efficiently compute rowwise dot product and select only upper triangular elements?
So, atm. I have the following solution:
def compute_interaction(x):
xx = np.reshape(x, (1, x.size))
return np.concatenate((x, np.dot(xx.T, xx)[np.triu_indices(xx.size)]))
Then compute_interaction(np.asarray([2,5]))
yield array([ 2, 5, 4, 10, 25])
.
And when I have a matrix I use
np.apply_along_axis(compute_interaction, axis=1, arr = np.asarray([[2,5], [3,4], [8,9]]))
which yields what I want:
array([[ 2, 5, 4, 10, 25],
[ 3, 4, 9, 12, 16],
[ 8, 9, 64, 72, 81]])
Is there any other way than to compute this using apply_along_axis
? Maybe using np.einsum
?