-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuncertainty_task_example.py
178 lines (134 loc) · 3.58 KB
/
uncertainty_task_example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.15.1
# kernelspec:
# display_name: Python 3.9 (uncertainty)
# language: python
# name: uncertainty
# ---
# %%
# %load_ext autoreload
# %autoreload 2
# %%
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
# %%
import matplotlib.pyplot as plt
import seaborn as sns
# %%
# when running on CPU, I found that performance is pretty much the same as with many cores
torch.set_num_threads(1)
# %% [markdown]
# # Create task and RNN
# %%
from modular_rnn.connections import ConnectionConfig
from modular_rnn.models import MultiRegionRNN
from modular_rnn.loss_functions import TolerantLoss
# %% [markdown]
# Set parameters
# %%
# time constant of each neuron's the dynamics
tau = 100
# timestep of the simulation
dt = 5
# need this
alpha = dt / tau
# tolerance in degrees in Dekleva et al 2016's uncertainty task
tolerance = 5.
# noise in the dynamics
noise = 0.05
# activation function of the neurons
nonlin_fn = F.relu
# %%
# length of each trial
L = 1200
# number of trials in a batch
batch_size = 64
# special loss for the uncertainty task
loss_fn = TolerantLoss(tolerance, 'hand')
# %% [markdown]
# Create task
# %%
from modular_rnn.tasks import CossinUncertaintyTaskWithReachProfiles
task = CossinUncertaintyTaskWithReachProfiles(dt, tau, L, batch_size)
# %% [markdown]
# Create RNN
# %%
# dictionary defining the modules in the RNN
# here we'll have a single region called motor_cortex
regions_config_dict = {
'motor_cortex' : {
'n_neurons' : 50,
'alpha' : alpha,
'p_rec': 1.,
'rec_rank' : 1,
'dynamics_noise' : noise,
}
}
# name and dimensionality of the outputs we want the RNN to produce
output_dims = task.output_dims
# name and dimensionality of the inputs we want the RNN to receive
input_dims = task.input_dims
# %%
rnn = MultiRegionRNN(
input_dims,
output_dims,
alpha,
nonlin_fn,
regions_config_dict,
connection_configs = [],
input_configs = [
ConnectionConfig('cue_slices_cossin', 'motor_cortex'),
ConnectionConfig('go_cue', 'motor_cortex'),
],
output_configs = [
ConnectionConfig('motor_cortex', 'hand'),
],
feedback_configs = []
)
# %% [markdown]
# # Train
# %%
from modular_rnn.training import train
losses = train(rnn, task, 500, loss_fn)
plt.plot(losses[10:]);
# %% [markdown]
# # Test the model's behavior on some test trials
# %% [markdown]
# Run a few batches of test trials
# %%
from modular_rnn.testing import run_test_batches
test_df = run_test_batches(10, rnn, task)
# %% [markdown]
# Produced reach direction vs. target direction
# %%
ax = sns.scatterplot(x = 'target_dir', y = 'endpoint_location', hue = 'cue_kappa', data = test_df, palette = 'tab10', alpha = 0.2)
ax.plot([0+0.5, np.pi-0.5], [0+0.5, np.pi-0.5], color = 'black', linestyle = '--', alpha = 0.5)
ax.set_aspect('equal')
# %% [markdown]
# Produced "hand" trajectories
# %%
fig, ax = plt.subplots()
for arr in test_df.hand_model_output.values[:100]:
ax.scatter(*arr.T, alpha = 0.1, color = 'tab:blue')
ax.set_title('model output')
ax.set_xlabel('x')
ax.set_ylabel('y')
# %% [markdown]
# Ratio of successful trials
# %%
np.mean(np.abs(test_df.endpoint_location - test_df.target_dir) < np.deg2rad(tolerance))
# %% [markdown]
# Rank of the recurrent weight matrix
# %%
torch.linalg.matrix_rank(rnn.regions['motor_cortex'].W_rec)
# %%