In [1]:
# Import here
%matplotlib inline
import matplotlib.pylab as pylab
import matplotlib.pyplot as plt
import numpy as np
import theano
import theano.tensor as T
pylab.rcParams['figure.figsize'] = (9.0, 6.0)
In [2]:
def fourier_coeffs(x, n_max=8):
n = np.arange(n_max).reshape((n_max, 1)) + 1.
phase = 2. * np.pi * n * x
c_sin = np.sin(phase)
c_cos = np.cos(phase)
return np.concatenate((c_sin, c_cos), axis=0)
In [3]:
t_x, t_y, t_nu = T.fmatrices('x', 'y', 'nu')
t_A = T.fmatrix(name='A')
t_a = T.fscalar(name='a')
t_xhat = T.dot(t_A, t_y + t_nu) + t_a
cost = T.mean((t_xhat - t_x) ** 2)
t_dA = T.grad(cost, t_A)
t_da = T.grad(cost, t_a)
f = theano.function(inputs=[t_x, t_y, t_nu, t_A, t_a],
outputs=[cost, t_xhat, t_dA, t_da])
In [32]:
n_max = 64
dim_fourier = 2 * n_max
A = np.ones((1, dim_fourier), dtype=np.float32) / dim_fourier
a = np.float32(0.)
In [33]:
sigma = 0.0
dim_batch = 1024
eta = np.float32(0.01)
for t in range(1000):
x = 1.0 * np.random.uniform(size=(1, dim_batch)).astype(np.float32)
y = fourier_coeffs(x, n_max=n_max).astype(np.float32)
nu = sigma * np.random.randn(dim_fourier, dim_batch).astype(np.float32)
cost, xhat, dA, da = f(x, y, nu, A, a)
if (t + 1) % 100 == 0:
print (t + 1), ':', cost
A -= eta * dA
a -= eta * da
In [34]:
plt.plot(A.reshape(dim_fourier))
Out[34]:
In [ ]: