I want to operate two matrix by rule as T.dot, like:
op( [v1, v2, v3] , [u1, u2, u3].T )
(v & u are all vectors)
and return the matrix:
[[op(v1, u1), op(v1, u2), op(v1, u3)],
[op(v2, u1), op(v2, u2), op(v2, u3)],
[op(v3, u1), op(v3, u2), op(v3, u3)]]
But, instead dot between two vectors, I want the op is the function to compute cosine similarity.
Is there any function can do this in theano?
=======
The cosine similarity function is:
import theano.tensor as T
x = T.vector()
y = T.vector()
result, _ = T.dot(x, y) / (x.norm(2) * y.norm(2))
cosine_similarity = theano.function(inputs=[x,y], outputs=[result])
You should probably do this with the matrices directly:
Define
V = (v1, v2, v3)
U = (u1, u2, u3)
Then
import theano.tensor as T
import numpy as np
U = T.fmatrix()
V = T.fmatrix()
cos_sim = T.dot(U, V.T) / (T.sqrt((U ** 2).sum(0)) * T.sqrt((V ** 2).sum(0).reshape((-1, 1))))
u = np.arange(9.).reshape(3, 3)
cos_sim.eval({U: u.astype('float32'), V: u.astype('float32')})