Last active
August 29, 2015 14:25
-
-
Save lucastheis/5a698344e2a8366d52c2 to your computer and use it in GitHub Desktop.
Gram matrix in Theano
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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