In [2]:
from matplotlib import pylab
import nengo
import random
import numpy as np
import gzip as gz
import cPickle
from cPickle import load
try:
import Image
except ImportError:
from PIL import Image
from scipy.sparse.linalg import svds
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#%matplotlib inline #Makes visualizations appar inline (Commented out because animation popup as new window)
In [3]:
def load_img(path, dims):
"""Load the image at path and return an array representing the raster.
Flattens image. Shifts pixel activations such that 0 represents gray,
normalizes the output array.
Keyword arguments:
path -- str, path of the image to be loaded.
dims -- (w, h), where w,h are ints indicating dimensions of the image (in
px)."""
img = Image.open(path).resize(dims).getdata()
img.convert('L')
img = subtract(array(img).flatten(), 127.5)
return img/norm(img)
def load_data(filename):
"""Uncompress, unpickle and return a .pkl.gz file.
Keyword arguments:
filename -- str, a valid file path"""
return load(gz.open(filename))
def load_mini_mnist(option=None):
"""Load and return the first \%10 of the images in the mnist dataset.
Does not return labels. Pass in 'train', 'valid' or 'test' if you want to
load a specific subset of the dataset.
Keyword arguments:
option -- str (default=None)."""
mini_mnist = load(gz.open('./mini_mnist.pkl.gz', 'rb'))
if option == 'train':
return mini_mnist[0]
elif option == 'valid':
return mini_mnist[1]
elif option == 'test':
return mini_mnist[2]
else:
return mini_mnist
In [4]:
def rotate_img(img, degrees):
'''Rotates image the degrees passed in counterclockwise
Reshapes image to original shape
'''
original = img.shape
newImg = scipy.ndimage.interpolation.rotate(np.reshape(img, (dim,dim), 'F'),degrees,reshape=False)
newImg = np.reshape(newImg, original, 'F')
return newImg
In [49]:
conn_synapse = 0.1 #post synaptic time constant to use for filtering (pstc) - what does changing this do?
probe_synapse = 0.01 #pstc
multiplier = 2 #not used
n_neurons = 5000
direct = False #Direct - function computed explicitly instead of in neurons
stop_time = 3.0
run_time = 3.0 #in seconds
In [6]:
dim = 28 #size of the image
mnist = load_mini_mnist()
train = mnist[0] #collection of training images
img = mnist[1][0] #image to be used for testing
compress_size = 400 #?
basis, S, V = svds(train.T, k=compress_size) #Used for encoding and decoding information
#a set of vectors representing what a hand drawn number should look like?
In [7]:
#Need same number of vectors in basis as number of neurons (randomly sample from basis)
expanded_basis = np.array([np.append(random.choice(basis.T),0) for _ in range(n_neurons)])
In [8]:
def stim_func(t):
'''returns the image for first 0.1s'''
if t < 0.1:
return img
else:
return [0 for _ in range(len(img))]
In [9]:
def stim_func_rot(t):
if t < 0.1:
return 0
elif t<0.5:
return 1
else:
return 10
In [10]:
def connection_func(x):
'''takes the output from the first ensemble and rotates it degress specified by stim'''
return np.append(rotate_img(x[:-1],x[-1]) - (0.1*x[:-1]),x[-1])
In [11]:
# Interference from stimulus when trying to rotate, so tried to delay rotation function
def node_func(t,x):
'''takes the output from the first ensemble and rotates it 1 degrees'''
if t < 0.1:
return x
else:
#return rotate_img(x,10) - (x*0.1)
return rotate_img(x,1)
In [50]:
#Sprite?
with nengo.Network() as net:
if direct:
neuron_type = nengo.Direct() #function computed explicitly, instead of in neurons
else:
neuron_type = nengo.LIF() #spiking version of the leaky integrate-and-fire neuron model
#Input stimulus - provide data to the ensemble
ipt = nengo.Node(stim_func)
ipt2 = nengo.Node(stim_func_rot)
#Group of neurons that collectively represent information(vector)
ens = nengo.Ensemble(n_neurons,
dimensions=dim**2+1, #pixels of the image? 28*28
encoders=expanded_basis, #transform representational space to neuron space
eval_points=expanded_basis, #used for decoder solving, spanning interval
n_eval_points=n_neurons,
neuron_type=neuron_type)
nengo.Connection(ipt, #source nengo object
ens[:-1], #destination object
synapse=None, #pstc
transform=1) #linear transformation, what does changing this do?
nengo.Connection(ipt2,ens[-1],synapse=None,transform =1)
'''Connection has param solver - (tried to make weight stronger, for image to last longer)
solver : Solver, optional (Default: nengo.solvers.LstsqL2())
Solver instance to compute decoders or weights (see Solver). If solver.weights is True, a full
connection weight matrix is computed instead of decoders.'''
#s = nengo.solvers.LstsqL2(weights=True)
conn = nengo.Connection(ens, ens, synapse=conn_synapse,transform=1, function=connection_func)
#delaynode = nengo.Node(node_func, size_in = dim**2, size_out =dim**2) #does processing on information
#conn = nengo.Connection(ens, delaynode, synapse=conn_synapse,transform =1) #incr transform, rotates faster
#conn2 = nengo.Connection(delaynode, ens, synapse=conn_synapse, transform =1)
probe = nengo.Probe(ens, attr='decoded_output',#sample_every=0.001,
synapse=probe_synapse)
In [51]:
sim = nengo.Simulator(net)
In [52]:
sim.run(run_time)
In [14]:
pylab.imshow(np.reshape(img, (dim,dim), 'F'), cmap='Greys_r')
Out[14]:
In [15]:
'''Image at stop time'''
pylab.imshow(np.reshape([0. if x < 0.00001 else x for x in sim.data[probe][int(stop_time*1000)-1]],
(dim, dim), 'F'), cmap=plt.get_cmap('Greys_r'),animated=True)
Out[15]:
In [16]:
'''Image at start time'''
pylab.imshow(np.reshape([0. if x < 0.00001 else x for x in sim.data[probe][1]],
(dim, dim), 'F'), cmap=plt.get_cmap('Greys_r'),animated=True)
Out[16]:
In [53]:
'''Animation for Probe output'''
fig = plt.figure()
def updatefig(i):
im = pylab.imshow(np.reshape([0. if x < 0.00001 else x for x in sim.data[probe][i][:-1]],
(dim, dim), 'F'), cmap=plt.get_cmap('Greys_r'),animated=True)
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=1, blit=True)
plt.show()
In [54]:
# save the output
#cPickle.dump(sim.data[probe], open( "Buffer_rotations_with_scalar_resized_basis_direct.p", "wb" ) )
#cPickle.dump(sim.data[probe], open( "Buffer_rotations_with_scalar_resized_basis_LIF.p", "wb" ) )