-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathm4_results.py
220 lines (204 loc) · 8.21 KB
/
m4_results.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import os
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import ttest_ind
from scipy.optimize import curve_fit
# find the current path
path = os.path.dirname(os.path.abspath(__file__))
# create the folders for this folder
if not os.path.exists(f'{path}/figures'):
os.mkdir(f'{path}/figures')
# define some color
Blue = .85 * np.array([ 9, 132, 227]) / 255
Green = .85 * np.array([ 0, 184, 148]) / 255
Red = .85 * np.array([ 255, 118, 117]) / 255
Yellow = .85 * np.array([ 253, 203, 110]) / 255
Purple = .85 * np.array([ 108, 92, 231]) / 255
colors = [ Blue, Red, Green, Yellow, Purple]
sns.set_style("whitegrid", {'axes.grid' : False})
# image dpi
dpi = 250
def viz_task():
plt.figure( figsize=( 4, 4))
plt.plot( np.arange(1,91), np.ones([90])*.7,
'--', color=Blue, linewidth=2)
plt.fill_between( np.arange(1,91), np.ones([90])*1,
color=Blue, alpha=.1)
plt.vlines( x=91, ymin=.2, ymax=.7,
linestyles='dashed', color=Red, linewidth=2)
plt.plot( np.arange(91,111), np.ones([20])*.2,
'--', color=Red, linewidth=2)
plt.vlines( x=111, ymin=.2, ymax=.8,
linestyles='dashed', color=Red, linewidth=2)
plt.plot( np.arange(111,131), np.ones([20])*.8,
'--', color=Red, linewidth=2)
plt.vlines( x=131, ymin=.2, ymax=.8,
linestyles='dashed', color=Red, linewidth=2)
plt.plot( np.arange(131,151), np.ones([20])*.2,
'--', color=Red, linewidth=2)
plt.vlines( x=151, ymin=.2, ymax=.8,
linestyles='dashed', color=Red, linewidth=2)
plt.plot( np.arange(151,171), np.ones([20])*.8,
'--', color=Red, linewidth=2)
plt.vlines( x=171, ymin=.2, ymax=.8,
linestyles='dashed', color=Red, linewidth=2)
plt.plot( np.arange(171,181), np.ones([10])*.2,
'--', color=Red, linewidth=2)
plt.text( 30, .9, 'Stable', fontsize=16)
plt.text( 120, .9, 'Volatile', fontsize=16)
plt.xlabel( 'Trials', fontsize=16)
plt.xlim( [ 1, 180])
plt.ylim( [ 0, 1.05])
plt.ylabel( 'The left stimulus \nresults in reward', fontsize=14)
plt.tight_layout()
plt.savefig( f'{path}/figures/experiment_paradigm.png', dpi=dpi)
def viz_fit_goodness( outcomes, model):
data = outcomes[model]['RC-analyses']
crs = [ 'rew', 'rew_hat']
subj = [ 'human', 'model']
fig, axs = plt.subplots( 1, 2, figsize=( 6, 2.5))
for i, cr in enumerate(crs):
ax = axs[i]
sns.violinplot( x='Trial type', y=cr, data=data,
palette=[ Blue, Red], order=['Stable', 'Volatile'], ax=ax)
ax.set_xticks([0, 1,])
ax.set_xlim([-.5, 1.5])
ax.set_xlabel('')
ax.set_xticklabels( ['Stable', 'Volatile'], fontsize=14)
ax.set_ylabel( f'Avg. {subj[i]} reward', fontsize=16)
ax.set_ylim([ .2, .8])
plt.tight_layout()
para = lambda x, a, b, c: a*x**2+b*x+c
def get_para( data):
lst = []
cond = ['Stable', 'Volatile']
for cd in cond:
ind = data['Trial type'] == cd
x1 = data['pi_comp'][ind]
y1 = data['rew_hat'][ind]
(a1,b1,c1), pcov = curve_fit( para, x1, y1)
lst.append( para( np.arange( 0, 1,.05), a1, b1, c1))
return lst
def viz_RC_anlyses(outcomes, model):
'''Show the rate-distortion curve
'''
data = outcomes[model]['RC-analyses']
#para1, para2 = get_para(data)
opt_stab_comp, opt_vol_comp = outcomes['opt_stab_comp'], outcomes['opt_vol_comp']
opt_stab_rew, opt_vol_rew = outcomes['opt_stab_rew'], outcomes['opt_vol_rew']
fig, axs = plt.subplots( 2, 2, figsize=( 6, 5))
# rate distortion curve
ax = axs[ 0, 0]
sns.scatterplot(x='pi_comp', y='EQ', data=data,
palette=[ Blue, Red],
s=90, hue='Trial type',
legend=True, ax=ax)
#ax.legend( title='block type', labels=['Stable', 'Volatile'], fontsize=10)
ax.set_xlabel('Avg. policy complexity', fontsize=16)
ax.set_ylabel('Avg. expected reward', fontsize=16)
ax.set_ylim([ .2, .65])
# human rew
ax = axs[ 0, 1]
sns.scatterplot(x='pi_comp', y='rew_hat', data=data,
palette=[ Blue, Red],
s=90, hue='Trial type',
legend=False, ax=ax)
ax.plot( opt_stab_comp, opt_stab_rew,
color='k', linewidth=2)
ax.plot( opt_vol_comp, opt_vol_rew, '--',
color='k', linewidth=2)
#ax.legend( title='block type', labels=['Stable', 'Volatile'], fontsize=10)
ax.set_xlabel('Avg. policy complexity', fontsize=16)
ax.set_ylabel('Avg. actual reward', fontsize=16)
ax.set_ylim([ .2, .65])
# policy complexity
ax = axs[ 1, 0]
sns.violinplot( x='Trial type', y='pi_comp', data=data,
palette=[ Blue, Red],
order=[ 'Stable', 'Volatile'],
ax=ax)
ax.set_xticks([0, 1,])
ax.set_xlim([-.5, 1.5])
ax.set_xticklabels( ['Stable', 'Volatile'], fontsize=14)
ax.set_xlabel('')
ax.set_ylabel( 'Avg. policy complexity', fontsize=16)
#print( f'{mode} policy complexity ttest: {ttest_ind( d_lst[0], d_lst[1])}')
# expected reward
ax = axs[ 1, 1]
sns.violinplot( x='Trial type', y='rew_hat', data=data,
palette=[ Blue, Red],
order=[ 'Stable', 'Volatile'],
ax=ax)
ax.set_xticks([0, 1,])
ax.set_xlim([-.5, 1.5])
ax.set_xticklabels( ['Stable', 'Volatile'], fontsize=14)
ax.set_xlabel('')
ax.set_ylabel( 'Avg. actual reward', fontsize=16)
#print( f'{mode} expected reward ttest: {ttest_ind( d_lst[0], d_lst[1])}')
plt.tight_layout()
def viz_params( outcomes, model):
'''Show the parameters summary
'''
data = outcomes[ model]['params']
params = [ 'alpha_s', 'alpha_a', 'beta']
params_name = [ r'$\alpha_s$', r'$\alpha_a$', r'$\beta$']
fig, axs = plt.subplots( 2, 2, figsize=( 6, 5))
for i, param in enumerate(params):
ax = axs[i//2, i%2]
sns.violinplot( x='Trial type', y=param, data=data,
palette=[ Blue, Red],
order=[ 'Stable', 'Volatile'],
ax=ax)
ax.set_xticks([0, 1,])
ax.set_xlim([-.5, 1.5])
ax.set_xticklabels( ['Stable', 'Volatile'],fontsize=14)
ax.set_xlabel('')
ax.set_ylabel( params_name[i],fontsize=16)
ax = axs[ 1, 1]
ax.set_axis_off()
fig.tight_layout()
def ttest( data, col, name):
d1 = data[col][data['Trial type']=='Stable']
d2 = data[col][data['Trial type']=='Volatile']
res = ttest_ind( d1, d2)
print( f'T test for {name}: t={res[0]:.3f}, p={res[1]:.3f}')
def t_tests( outcomes, model):
data = outcomes[model]
## Test for figure 1
cols = ['rew', 'rew_hat']
names = [ 'human reward', 'model reward']
for col, name in zip( cols, names):
ttest( data['RC-analyses'], col, name)
## Test for figure 2
cols = ['alpha_s', 'alpha_a', 'beta']
names = cols
for col, name in zip( cols, names):
ttest( data['params'], col, name)
## Test for figure 3
if model != 'model11':
cols = [ 'pi_comp', 'rew_hat']
names = [ 'policy complexity', 'actual reward']
for col, name in zip( cols, names):
ttest( data['RC-analyses'], col, name)
if __name__ == '__main__':
## Show experiment paradigm
#viz_task()
## Analyze the data
datasets = ['exp1_rew']
models = ['RDModel2_exp']
for dataset in datasets:
for model in models:
fname = f'{path}/analyses/analyses-{dataset}.pkl'
with open( fname, 'rb')as handle:
outcomes = pickle.load( handle)
viz_fit_goodness( outcomes, model)
plt.savefig( f'{path}/figures/fit_validate-{dataset}-model={model}.png', dpi=500)
viz_params( outcomes, model)
plt.savefig( f'{path}/figures/param_smary-{dataset}-model={model}.png', dpi=500)
if model != 'model11':
viz_RC_anlyses( outcomes, model)
plt.savefig( f'{path}/figures/RD_curves-{dataset}-model={model}.png', dpi=500)
t_tests( outcomes, model)