In [2]:
import nengo
import numpy as np
import cPickle
from nengo_extras.data import load_mnist
from nengo_extras.vision import Gabor, Mask
from matplotlib import pylab
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import scipy.ndimage
from scipy.ndimage.interpolation import rotate
Load the MNIST database
In [3]:
# --- load the data
img_rows, img_cols = 28, 28
(X_train, y_train), (X_test, y_test) = load_mnist()
X_train = 2 * X_train - 1 # normalize to -1 to 1
X_test = 2 * X_test - 1 # normalize to -1 to 1
Each digit is represented by a one hot vector where the index of the 1 represents the number
In [4]:
temp = np.diag([1]*10)
ZERO = temp[0]
ONE = temp[1]
TWO = temp[2]
THREE= temp[3]
FOUR = temp[4]
FIVE = temp[5]
SIX = temp[6]
SEVEN =temp[7]
EIGHT= temp[8]
NINE = temp[9]
labels =[ZERO,ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE]
dim =28
Load the saved weight matrices that were created by training the model
In [6]:
label_weights = cPickle.load(open("label_weights_choose_enc1000.p", "rb"))
activity_to_img_weights = cPickle.load(open("activity_to_img_weights_choose_enc1000.p", "rb"))
#rotated_clockwise_after_encoder_weights = cPickle.load(open("rotated_clockwise_after_encoder_weights_rot_enc1000.p", "r"))
rotated_counter_after_encoder_weights = cPickle.load(open("rotated_counter_after_encoder_weights_choose_enc1000.p", "r"))
#identity_after_encoder_weights = cPickle.load(open("identity_after_encoder_weights1000.p","r"))
#rotation_clockwise_weights = cPickle.load(open("rotation_clockwise_weights1000.p","rb"))
#rotation_counter_weights = cPickle.load(open("rotation_weights1000.p","rb"))
In [5]:
#Training with filters used on train images
#low_pass_weights = cPickle.load(open("low_pass_weights1000.p", "rb"))
#rotated_counter_after_encoder_weights_noise = cPickle.load(open("rotated_after_encoder_weights_counter_filter_noise5000.p", "r"))
#rotated_counter_after_encoder_weights_filter = cPickle.load(open("rotated_after_encoder_weights_counter_filter5000.p", "r"))
Functions to perform the inhibition of each ensemble
In [6]:
#A value of zero gives no inhibition
def inhibit_rotate_clockwise(t):
if t < 0.5:
return dim**2
else:
return 0
def inhibit_rotate_counter(t):
if t < 0.5:
return 0
else:
return dim**2
def inhibit_identity(t):
if t < 0.3:
return dim**2
else:
return dim**2
In [13]:
def intense(img):
newImg = img.copy()
newImg[newImg < 0] = -1
newImg[newImg > 0] = 1
return newImg
def node_func(t,x):
#clean = scipy.ndimage.gaussian_filter(x, sigma=1)
#clean = scipy.ndimage.median_filter(x, 3)
clean = intense(x)
return clean
In [14]:
#Create stimulus at horizontal
weight = np.dot(label_weights,activity_to_img_weights)
img = np.dot(THREE,weight)
img = scipy.ndimage.rotate(img.reshape(28,28),90).ravel()
pylab.imshow(img.reshape(28,28),cmap="gray")
plt.show()
In [7]:
rng = np.random.RandomState(9)
n_hid = 1000
model = nengo.Network(seed=3)
with model:
#Stimulus only shows for brief period of time
stim = nengo.Node(lambda t: THREE if t < 0.1 else 0) #nengo.processes.PresentInput(labels,1))# For cycling through input
#Starting the image at horizontal
#stim = nengo.Node(lambda t:img if t< 0.1 else 0)
ens_params = dict(
eval_points=X_train,
neuron_type=nengo.LIF(), #Why not use LIF?
intercepts=nengo.dists.Choice([-0.5]),
max_rates=nengo.dists.Choice([100]),
)
# linear filter used for edge detection as encoders, more plausible for human visual system
#encoders = Gabor().generate(n_hid, (11, 11), rng=rng)
#encoders = Mask((28, 28)).populate(encoders, rng=rng, flatten=True)
'''
degrees = 6
#must have same number of excoders as neurons (Want each random encoder to have same encoder at every angle)
encoders = Gabor().generate(n_hid/(360/degrees), (11, 11), rng=rng)
encoders = Mask((28, 28)).populate(encoders, rng=rng, flatten=True)
rotated_encoders = encoders.copy()
#For each randomly generated encoder, create the same encoder at every angle (increments chosen by degree)
for encoder in encoders:
rotated_encoders = np.append(rotated_encoders, [encoder],axis =0)
for i in range(1,59):
#new_gabor = rotate(encoder.reshape(28,28),degrees*i,reshape = False).ravel()
rotated_encoders = np.append(rotated_encoders, [rotate(encoder.reshape(28,28),degrees*i,reshape = False).ravel()],axis =0)
#rotated_encoders = np.append(rotated_encoders, [encoder],axis =0)
'''
rotated_encoders = cPickle.load(open("encoders.p", "r"))
#Num of neurons does not divide evenly with 6 degree increments, so add random encoders
extra_encoders = Gabor().generate(n_hid - len(rotated_encoders), (11, 11), rng=rng)
extra_encoders = Mask((28, 28)).populate(extra_encoders, rng=rng, flatten=True)
all_encoders = np.append(rotated_encoders, extra_encoders, axis =0)
encoders = all_encoders
#Ensemble that represents the image with different transformations applied to it
ens = nengo.Ensemble(n_hid, dim**2, seed=3, encoders=encoders, **ens_params)
#Connect stimulus to ensemble, transform using learned weight matrices
nengo.Connection(stim, ens, transform = np.dot(label_weights,activity_to_img_weights).T)
#nengo.Connection(stim, ens) #for rotated stim
#Recurrent connection on the neurons of the ensemble to perform the rotation
nengo.Connection(ens.neurons, ens.neurons, transform = rotated_counter_after_encoder_weights.T, synapse=0.1)
#nengo.Connection(ens.neurons, ens.neurons, transform = low_pass_weights.T, synapse=0.1)
#Identity ensemble
#ens_iden = nengo.Ensemble(n_hid,dim**2, seed=3, encoders=encoders, **ens_params)
#Rotation ensembles
#ens_clock_rot = nengo.Ensemble(n_hid,dim**2,seed=3,encoders=encoders, **ens_params)
ens_counter_rot = nengo.Ensemble(n_hid,dim**2,seed=3,encoders=encoders, **ens_params)
#Inhibition nodes
#inhib_iden = nengo.Node(inhibit_identity)
#inhib_clock_rot = nengo.Node(inhibit_rotate_clockwise)
#inhib_counter_rot = nengo.Node(inhibit_rotate_counter)
#Connect the main ensemble to each manipulation ensemble and back with appropriate transformation
#Identity
#nengo.Connection(ens.neurons, ens_iden.neurons,transform=identity_after_encoder_weights.T,synapse=0.1)
#nengo.Connection(ens_iden.neurons, ens.neurons,transform=identity_after_encoder_weights.T,synapse=0.1)
#Clockwise
#nengo.Connection(ens.neurons, ens_clock_rot.neurons, transform = rotated_clockwise_after_encoder_weights.T,synapse=0.1)
#nengo.Connection(ens_clock_rot.neurons, ens.neurons, transform = rotated_clockwise_after_encoder_weights.T,synapse = 0.1)
#Counter-clockwise
#nengo.Connection(ens.neurons, ens_counter_rot.neurons, transform = rotated_counter_after_encoder_weights.T, synapse=0.1)
#nengo.Connection(ens_counter_rot.neurons, ens.neurons, transform = rotated_counter_after_encoder_weights.T, synapse=0.1)
#nengo.Connection(ens_counter_rot.neurons, ens.neurons, transform = rotated_counter_after_encoder_weights_filter.T, synapse=0.1)
#nengo.Connection(ens.neurons, ens_counter_rot.neurons, transform = low_pass_weights.T, synapse=0.1)
#nengo.Connection(ens_counter_rot.neurons, ens.neurons, transform = low_pass_weights.T, synapse=0.1)
#Clean up by a node
#n = nengo.Node(node_func, size_in=dim**2)
#nengo.Connection(ens.neurons,n,transform=activity_to_img_weights.T, synapse=0.1)
#nengo.Connection(n,ens_counter_rot,synapse=0.1)
#Connect the inhibition nodes to each manipulation ensemble
#nengo.Connection(inhib_iden, ens_iden.neurons, transform=[[-1]] * n_hid)
#nengo.Connection(inhib_clock_rot, ens_clock_rot.neurons, transform=[[-1]] * n_hid)
#nengo.Connection(inhib_counter_rot, ens_counter_rot.neurons, transform=[[-1]] * n_hid)
#Collect output, use synapse for smoothing
probe = nengo.Probe(ens.neurons,synapse=0.1)
In [8]:
sim = nengo.Simulator(model)
In [9]:
sim.run(5)
In [10]:
'''Animation for Probe output'''
fig = plt.figure()
output_acts = []
for act in sim.data[probe]:
output_acts.append(np.dot(act,activity_to_img_weights))
def updatefig(i):
im = pylab.imshow(np.reshape(output_acts[i],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'),animated=True)
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=0.1, blit=True)
plt.show()
In [11]:
#ouput_acts = sim.data[probe]
plt.subplot(261)
plt.title("100")
pylab.imshow(np.reshape(output_acts[100],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(262)
plt.title("500")
pylab.imshow(np.reshape(output_acts[500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(263)
plt.title("1000")
pylab.imshow(np.reshape(output_acts[1000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(264)
plt.title("1500")
pylab.imshow(np.reshape(output_acts[1500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(265)
plt.title("2000")
pylab.imshow(np.reshape(output_acts[2000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(266)
plt.title("2500")
pylab.imshow(np.reshape(output_acts[2500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(267)
plt.title("3000")
pylab.imshow(np.reshape(output_acts[3000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(268)
plt.title("3500")
pylab.imshow(np.reshape(output_acts[3500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(269)
plt.title("4000")
pylab.imshow(np.reshape(output_acts[4000],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(2,6,10)
plt.title("4500")
pylab.imshow(np.reshape(output_acts[4500],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(2,6,11)
plt.title("5000")
pylab.imshow(np.reshape(output_acts[4999],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.show()
Pickle the probe's output if it takes a long time to run
In [ ]:
#The filename includes the number of neurons and which digit is being rotated
filename = "mental_rotation_output_ONE_" + str(n_hid) + ".p"
cPickle.dump(sim.data[probe], open( filename , "wb" ) )
In [171]:
testing = np.dot(ONE,np.dot(label_weights,activity_to_img_weights))
testing = output_acts[300]
plt.subplot(131)
pylab.imshow(np.reshape(testing,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
#Get image
#testing = np.dot(ONE,np.dot(label_weights,activity_to_img_weights))
#noise = np.random.random([28,28]).ravel()
testing = node_func(0,testing)
plt.subplot(132)
pylab.imshow(np.reshape(testing,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
#Get activity of image
_, testing_act = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=testing)
#Get encoder outputs
testing_filter = np.dot(testing_act,rotated_counter_after_encoder_weights_filter)
#Get activities
testing_filter = ens.neuron_type.rates(testing_filter, sim.data[ens].gain, sim.data[ens].bias)
for i in range(5):
testing_filter = np.dot(testing_filter,rotated_counter_after_encoder_weights_filter)
testing_filter = ens.neuron_type.rates(testing_filter, sim.data[ens].gain, sim.data[ens].bias)
testing_filter = np.dot(testing_filter,activity_to_img_weights)
testing_filter = node_func(0,testing_filter)
_, testing_filter = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=testing_filter)
#testing_rotate = np.dot(testing_rotate,rotation_weights)
testing_filter = np.dot(testing_filter,activity_to_img_weights)
plt.subplot(133)
pylab.imshow(np.reshape(testing_filter,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.show()
In [ ]:
plt.subplot(121)
pylab.imshow(np.reshape(X_train[0],(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
#Get activity of image
_, testing_act = nengo.utils.ensemble.tuning_curves(ens, sim, inputs=X_train[0])
testing_rotate = np.dot(testing_act,activity_to_img_weights)
plt.subplot(122)
pylab.imshow(np.reshape(testing_rotate,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.show()
In [ ]:
letterO = np.dot(ZERO,np.dot(label_weights,activity_to_img_weights))
plt.subplot(161)
pylab.imshow(np.reshape(letterO,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
letterL = np.dot(SEVEN,label_weights)
for _ in range(30):
letterL = np.dot(letterL,rotation_weights)
letterL = np.dot(letterL,activity_to_img_weights)
plt.subplot(162)
pylab.imshow(np.reshape(letterL,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
letterI = np.dot(ONE,np.dot(label_weights,activity_to_img_weights))
plt.subplot(163)
pylab.imshow(np.reshape(letterI,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.subplot(165)
pylab.imshow(np.reshape(letterI,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
letterV = np.dot(SEVEN,label_weights)
for _ in range(40):
letterV = np.dot(letterV,rotation_weights)
letterV = np.dot(letterV,activity_to_img_weights)
plt.subplot(164)
pylab.imshow(np.reshape(letterV,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
letterA = np.dot(SEVEN,label_weights)
for _ in range(10):
letterA = np.dot(letterA,rotation_weights)
letterA = np.dot(letterA,activity_to_img_weights)
plt.subplot(166)
pylab.imshow(np.reshape(letterA,(dim, dim), 'F').T, cmap=plt.get_cmap('Greys_r'))
plt.show()