swiss_roll_distribution.ipynb (Source)
In [1]:
%matplotlib notebook
In [2]:
import numpy as np
import matplotlib.pyplot as plt
import keras.backend as K
from keras.layers import Lambda, Input
from keras.models import Sequential, Model
In [3]:
np.set_printoptions(precision=2,
edgeitems=3,
linewidth=80,
suppress=True)
In [4]:
'TensorFlow version: ' + K.tf.__version__
Out[4]:
In [5]:
golden_figsize = lambda width: (width, 2. * width / (1 + np.sqrt(5)))
In [6]:
def swiss_roll(theta, a=0., b=.25):
""" Archimedean spiral. """
theta = 4. * np.pi * K.sqrt(theta)
r = a + b * theta
return K.stack([r * K.cos(theta), r * K.sin(theta)], axis=-1)
In [7]:
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(*K.eval(swiss_roll(K.constant(np.linspace(0, 1, 100)))).T)
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
plt.show()
In [8]:
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(*K.eval(swiss_roll(K.random_uniform(shape=(100,)))).T)
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
plt.show()
Within Keras layers¶
In [9]:
x = Input(shape=(16,))
eps = Input(tensor=K.random_uniform(shape=(K.shape(x)[0],)))
swiss_roll_sample = Lambda(swiss_roll)(eps)
In [10]:
m = Model([x, eps], swiss_roll_sample)
In [11]:
m.predict(np.ones((10, 16)))
Out[11]:
In [12]:
fig, ax = plt.subplots(figsize=(5, 5))
ax.scatter(*m.predict(np.ones((100, 16))).T)
ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
plt.show()