Problem Description
I have written Python code to compute the following function, for fixed y_i
and fixed z_i
.
In practice, I will have many different vectors x
at which I will want to evaluate this. Rather than going through a loop, I wanted to take full advantage of NumPy’s vectorization and broadcasting abilities.
Aim: Write a Python function that takes as input a matrix
X
of shape(M, p)
where each row is a different vectorx
and compute the expression above for each of these rows, thus obtaining an output of shape(M, p)
.
Single Function
def single_function(x):
"""Assumes y is a vector (n,) and Z is a matrix (n, p). These are fixed."""
return x / (sigma**2) - gamma*np.sum((np.exp(-np.logaddexp(0.0, y*np.matmul(Z, x))) * y)[:, None] * Z, axis=0)
Vectorised Function
My attempt is wrong, but I cannot tell where I am going wrong.
def vectorised(X):
return X / (sigma**2) - gamma*np.matmul(np.exp(-np.logaddexp(0.0, y[None, :] * X.dot(Z.T))) * y[None, :], Z)