Skip to content

Instantly share code, notes, and snippets.

@lucastheis
Last active August 29, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucastheis/5a698344e2a8366d52c2 to your computer and use it in GitHub Desktop.
Save lucastheis/5a698344e2a8366d52c2 to your computer and use it in GitHub Desktop.
Gram matrix in Theano
import theano as th
import theano.tensor as tt
def gaussian_kernel(x, y, sigma=1.):
return tt.exp(-tt.sum(tt.square(x - y)) / sigma**2)
def gram_matrix(X, Y, kernel):
M = X.shape[0]
N = Y.shape[0]
R, _ = th.scan(
fn=lambda k: kernel(X[k // N], Y[k % N]),
sequences=[tt.arange(M * N)])
return R.reshape([M, N])
X = tt.dmatrix('X')
Y = tt.dmatrix('Y')
K = gram_matrix(X, Y, gaussian_kernel)
f = th.function([X, Y], [tt.sum(K), tt.grad(tt.sum(K), X)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment