-
Notifications
You must be signed in to change notification settings - Fork 0
/
V4pyutils.py
2607 lines (2102 loc) · 94.9 KB
/
V4pyutils.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
List of utilities to make analysis of V4 data
easier and reproducible
"""
# Import dependencies
import numpy as np
import pandas as pd
from copy import deepcopy
import re
from datetime import datetime, date
# data io
import glob
import deepdish as dd
# image
#import cv2
# stats
#import pycircstat as pyc
from scipy import stats
import statsmodels.api as sm
# spykes
#from spykes.neuropop import NeuroPop
#c from spykes.neurovis import NeuroVis
# machine learning
import xgboost as xgb
from sklearn.cross_validation import KFold
from sklearn.cross_validation import LabelKFold
import keras
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD, RMSprop
from keras.layers.core import Lambda
from keras.models import model_from_json
from keras.utils.layer_utils import convert_all_kernels_in_model,convert_dense_weights_data_format
from keras.preprocessing import image
from keras.applications.vgg16 import preprocess_input
from keras import backend as K
from sklearn.linear_model import LinearRegression
from keras.regularizers import l1_l2
# visualization
import matplotlib.pyplot as plt
#---------------------------------------
# Helpers for data cleaning and merging
#---------------------------------------
def art_file_to_df(session_number, session_name, neurons=None, window=[50, 300]):
# Read in the filename
dat = dd.io.load(session_name)
# Collect features of interest into a dict
art = dict()
art['predictors.col'] = np.array([dat['eyes'][i]['col'] for i in dat['eyes']])
art['predictors.row'] = np.array([dat['eyes'][i]['row'] for i in dat['eyes']])
art['predictors.hue'] = np.array([dat['features'][i]['hue'] for i in dat['features']])
art['predictors.onset_times'] = np.array([dat['events'][i]['onset'] for i in dat['events']])
art['predictors.offset_times'] = np.array([dat['events'][i]['offset'] for i in dat['events']])
# To DataFrame
predictors_df = pd.DataFrame.from_dict(art, orient='columns', dtype=None)
# Compute more features
predictors_df['predictors.off_to_onset_times'] = \
predictors_df['predictors.onset_times']- \
np.roll(predictors_df['predictors.offset_times'], 1)
predictors_df['predictors.off_to_onset_times'][0] = -999.0
predictors_df['predictors.hue_prev'] = \
np.roll(predictors_df['predictors.hue'], 1)
predictors_df['predictors.hue_prev'][0] = -999.0
predictors_df['predictors.stim_dur'] = \
predictors_df['predictors.offset_times'] - \
predictors_df['predictors.onset_times']
# Sort columns manually
cols = ['predictors.onset_times',
'predictors.offset_times',
'predictors.col',
'predictors.row',
'predictors.hue',
'predictors.hue_prev',
'predictors.stim_dur',
'predictors.off_to_onset_times']
predictors_df = predictors_df[cols]
# Collect spike counts from neurons of interest into a dict
all_spikecounts = dict()
if neurons is None:
neurons = dat['spikes'].keys()
for neuron in neurons:
spiketimes = dat['spikes'][neuron]
if len(spiketimes) > 1:
neuron_object = NeuroVis(spiketimes,
name='spikes.'+neuron)
spikecounts = \
neuron_object.get_spikecounts(event='predictors.onset_times',
df=predictors_df,
window=window)
else:
n_samples = len(predictors_df)
spikecounts = np.zeros(n_samples)
all_spikecounts[neuron_object.name] = spikecounts
# To DataFrame
spikes_df = pd.DataFrame.from_dict(all_spikecounts, orient='columns')
spikes_df = spikes_df[np.sort(all_spikecounts.keys())]
# Store other metadata about the sessions
session_df = pd.DataFrame(columns=['session.number', 'session.name'])
session_df['session.number'] = [session_number for i in range(len(predictors_df))]
session_df['session.name'] = [session_name for i in range(len(predictors_df))]
# Merge
df = pd.merge(predictors_df, spikes_df, left_index=True, right_index=True)
df = pd.merge(df, session_df, left_index=True, right_index=True)
return df
#------------------------------------------------------------------
def art_file_to_df_ori(session_number, session_name, neurons=None, window=[50, 300]):
# Read in the filename
dat = dd.io.load(session_name)
# Collect features of interest into a dict
art = dict()
art['predictors.col'] = np.array([dat['eyes'][i]['col'] for i in dat['eyes']])
art['predictors.row'] = np.array([dat['eyes'][i]['row'] for i in dat['eyes']])
art['predictors.ori'] = np.array([dat['features'][i]['ori'] for i in dat['features']])
art['predictors.onset_times'] = np.array([dat['events'][i]['onset'] for i in dat['events']])
art['predictors.offset_times'] = np.array([dat['events'][i]['offset'] for i in dat['events']])
# To DataFrame
predictors_df = pd.DataFrame.from_dict(art, orient='columns', dtype=None)
# Compute more features
predictors_df['predictors.off_to_onset_times'] = \
predictors_df['predictors.onset_times']- \
np.roll(predictors_df['predictors.offset_times'], 1)
predictors_df['predictors.off_to_onset_times'][0] = -999.0
predictors_df['predictors.ori_prev'] = \
np.roll(predictors_df['predictors.ori'], 1)
predictors_df['predictors.ori_prev'][0] = -999.0
predictors_df['predictors.stim_dur'] = \
predictors_df['predictors.offset_times'] - \
predictors_df['predictors.onset_times']
# Sort columns manually
cols = ['predictors.onset_times',
'predictors.offset_times',
'predictors.col',
'predictors.row',
'predictors.ori',
'predictors.ori_prev',
'predictors.stim_dur',
'predictors.off_to_onset_times']
predictors_df = predictors_df[cols]
# Collect spike counts from neurons of interest into a dict
all_spikecounts = dict()
if neurons is None:
neurons = dat['spikes'].keys()
for neuron in neurons:
spiketimes = dat['spikes'][neuron]
if len(spiketimes) > 1:
neuron_object = NeuroVis(spiketimes,
name='spikes.'+neuron)
spikecounts = \
neuron_object.get_spikecounts(event='predictors.onset_times',
df=predictors_df,
window=window)
else:
n_samples = len(predictors_df)
spikecounts = np.zeros(n_samples)
all_spikecounts[neuron_object.name] = spikecounts
# To DataFrame
spikes_df = pd.DataFrame.from_dict(all_spikecounts, orient='columns')
spikes_df = spikes_df[np.sort(all_spikecounts.keys())]
# Store other metadata about the sessions
session_df = pd.DataFrame(columns=['session.number', 'session.name'])
session_df['session.number'] = [session_number for i in range(len(predictors_df))]
session_df['session.name'] = [session_name for i in range(len(predictors_df))]
# Merge
df = pd.merge(predictors_df, spikes_df, left_index=True, right_index=True)
df = pd.merge(df, session_df, left_index=True, right_index=True)
return df
#------------------------------------------------------------------
def nat_file_to_df(session_number, session_name,
in_screen_radius=200,
neurons=None, window=[50, 300]):
# Read in the file name
dat = dd.io.load(session_name)
features_nat = dat['eyes'][0].keys()
# Collect features of interest into a dict
features_dict = dict()
for feat in features_nat:
features_dict[feat] = \
np.array([dat['eyes'][fix][feat] for fix in dat['eyes']])
# Convert it into a dataframe
nat_df = pd.DataFrame.from_dict(features_dict,
orient='columns',
dtype=None)
# Add information about sessions
nat_df['session.number'] = session_number
nat_df['session.name'] = session_name
# Compute a new set of predictors
nat_df['predictors.in_sac_blink'] = nat_df['in_sac_blink'] == 1
nat_df['predictors.out_sac_blink'] = nat_df['out_sac_blink'] == 1
nat_df['predictors.fix_duration'] = \
nat_df['fix_offset'] - nat_df['fix_onset']
nat_df['predictors.next_fix_duration'] = \
np.append(nat_df['predictors.fix_duration'][1:], -999.0)
nat_df['predictors.prev_fix_duration'] = \
np.append(-999.0, nat_df['predictors.fix_duration'][0:-1])
nat_df['predictors.row_drift'] = \
nat_df['fix_offset_row'] - nat_df['fix_onset_row']
nat_df['predictors.col_drift'] = \
nat_df['fix_offset_col'] - nat_df['fix_onset_col']
nat_df['predictors.drift'] = \
np.abs(nat_df['predictors.row_drift']) + \
np.abs(nat_df['predictors.col_drift'])
# Some filters to discard bad fixations
nat_df['filters.in_screen'] = \
np.all((nat_df['col']>=1, nat_df['col']<=1024, \
nat_df['row']>=1, nat_df['row']<=768), axis=0)
nat_df['filters.badfix'] = nat_df['badfix'] == 1
R = in_screen_radius
nat_df['filters.in_screen_radius'] = (nat_df['row'] > R) & \
(nat_df['row'] < (768 - R)) & \
(nat_df['col'] > R) & \
(nat_df['col'] < (1024 - R))
# Rename some columns
nat_df.rename(columns={'trial': 'predictors.trial',
'fixation': 'predictors.fixation',
'fix_onset': 'predictors.fix_onset',
'fix_offset': 'predictors.fix_offset',
'row': 'predictors.row',
'col': 'predictors.col',
'fix_onset_row': 'predictors.fix_onset_row',
'fix_onset_col': 'predictors.fix_onset_col',
'fix_offset_row': 'predictors.fix_offset_row',
'fix_offset_col': 'predictors.fix_offset_col',
'in_sac_dur': 'predictors.in_sac_dur',
'in_sac_pkvel': 'predictors.in_sac_pkvel',
'out_sac_dur': 'predictors.out_sac_dur',
'out_sac_pkvel': 'predictors.out_sac_pkvel',
'imname': 'im.name',
'impath': 'im.path'},
inplace=True)
# Sort columns
cols = ['predictors.trial', 'predictors.fixation',
'predictors.fix_onset', 'predictors.fix_offset',
'predictors.row', 'predictors.col',
'predictors.fix_onset_row', 'predictors.fix_onset_col',
'predictors.fix_offset_row', 'predictors.fix_offset_col',
'predictors.in_sac_blink',
'predictors.in_sac_dur',
'predictors.in_sac_pkvel',
'predictors.out_sac_blink',
'predictors.out_sac_dur',
'predictors.out_sac_pkvel',
'predictors.fix_duration',
'predictors.prev_fix_duration',
'predictors.next_fix_duration',
'predictors.row_drift',
'predictors.col_drift',
'predictors.drift',
'im.path', 'im.name',
'filters.in_screen',
'filters.in_screen_radius',
'filters.badfix',
'session.number',
'session.name']
nat_df = nat_df[cols]
# Denote missing values correctly
nat_df = nat_df.fillna(-999.0);
# Collect spike counts from neurons of interest into a dict
all_spikecounts = dict()
if neurons is None:
neurons = dat['spikes'].keys()
for neuron in neurons:
spiketimes = dat['spikes'][neuron]
if len(spiketimes) > 1:
neuron_object = NeuroVis(spiketimes,
name='spikes.'+neuron)
spikecounts = \
neuron_object.get_spikecounts(event='predictors.fix_onset',
df=nat_df,
window=window)
else:
n_samples = len(nat_df)
spikecounts = np.zeros(n_samples)
all_spikecounts[neuron_object.name] = spikecounts
# To DataFrame
spikes_df = pd.DataFrame.from_dict(all_spikecounts, orient='columns')
spikes_df = spikes_df[np.sort(all_spikecounts.keys())]
# Merge
df = pd.merge(nat_df, spikes_df, left_index=True, right_index=True)
return df
# -----------------------------------------------------------------
def predict_across_sessions(df, neuron_name, Models=[], verbose=1, plot=True):
# Get the list of unique sessions
session_list = np.unique(df['session.number'].values)
cross_pred_matrix = np.zeros([np.max(session_list)+1,
np.max(session_list)+1])
# Loop through pairs of sessions
for session_i in range(np.min(session_list), np.max(session_list)+1):
for session_j in range(session_i, np.max(session_list)+1):
# Select only the pair of sessions of interest
df_pair = df.loc[df['session.number'].isin([session_i, session_j])]
# Extract spike counts
Y = df_pair[neuron_name].values
# If the neuron is missing in one of the sessions
#if(np.all(Y.notnull())):
if(np.any(np.isnan(Y)) > 0):
# Assign cross-prediction to 0
cross_pred_matrix[session_i, session_j] = 0
else:
# Extract session numbers for stratified cross-validation
labels = df_pair['session.number']
n_cv = np.size(np.unique(labels))
# Loop through models
for model_number, model in enumerate(Models):
if verbose == 1:
print 'running model %d of %d: %s' % \
(model_number + 1, len(Models), model)
print ''
# Extract predictors
X = df_pair[Models[model]['covariates']].values
if verbose == 1:
print "(", session_i, session_j, ")", \
"X", np.shape(X), "Y", np.shape(Y)
# Do cross prediction
# (across sessions, stratified by session)
if session_i != session_j:
Yt_hat, pseudo_R2 = fit_cv(X, Y,
stratify_by_labels=labels,
n_cv=n_cv,
algorithm='XGB_poisson',
verbose=2*verbose)
cross_pred_matrix[session_i, session_j] = pseudo_R2[0]
cross_pred_matrix[session_j, session_i] = pseudo_R2[1]
# Do cross-validation within session
elif session_i == session_j:
Yt_hat, pseudo_R2 = fit_cv(X, Y,
stratify_by_labels=[],
n_cv=10,
algorithm='XGB_poisson',
verbose=2*verbose)
cross_pred_matrix[session_i, session_i] = \
np.mean(pseudo_R2)
Models[model]['Yt_hat'] = Yt_hat
Models[model]['pseudo_R2'] = pseudo_R2
# Visualize fits
if plot is True:
x_data = df['predictors.hue'].values
y_data = Y
xlabel = 'hue'
plot_xy(x_data=x_data, y_data=y_data,
y_model=Models[model]['Yt_hat'],
lowess_frac=0.5,
xlabel=xlabel, model_name=model,
x_jitter_level=0., y_jitter_level=0.5)
plt.title((X[np.argmax(Models[model]['Yt_hat'])] * \
180/np.pi)[0])
plt.show()
return cross_pred_matrix
#---------------------------------------
def remove_subsets(D):
Dnew = deepcopy(D)
# For each element in D
for d1 in D:
# For all the other elements
for d2 in D:
if d2 != d1:
# If d1 is contained in d2, discard d1
if ((set(d1) | set(d2)) == set(d2)):
Dnew.discard(d1)
# If d2 is contained in d1, discard d2
elif ((set(d1) | set(d2)) == set(d1)):
Dnew.discard(d2)
return Dnew
#---------------------------------------
def find_all_blocks(S):
D = list()
N = S.shape[0]
for m in range(N+1):
for n in range(m+1, N+1):
Sblock = S[m:n,m:n]
if (Sblock.sum() == (m - n) ** 2):
D.append(tuple(range(m,n)))
return list(np.sort(list(remove_subsets(set(D)))))
#---------------------------------------
def days_between(d1, d2):
date1 = date(int(d1[0:2]), int(d1[2:4]), int(d1[4:6]))
date2 = date(int(d2[0:2]), int(d2[2:4]), int(d2[4:6]))
return abs(date2-date1).days
#---------------------------------------
def show_sessions(df, linked_lists, plot=False):
art_loc_prev = -1
nat_loc_prev = -1
art_locs = list()
nat_locs = list()
# Starting date
start_idx = df.index[0]
date0 = str(re.findall(r'\d+', \
re.split('_', df['Natural'].loc[start_idx])[0]))[3:9]
# Initialize figure
if plot:
plt.figure(figsize=(15,4))
ax = plt.subplot(111)
simpleaxis(ax)
# For each art file
art_loc_prev = -1
for art_file_number, art_file in enumerate(df.Hue.unique()):
art_date = str(re.findall(r'\d+', \
re.split('_', art_file)[0]))[3:9]
art_sess = np.int(str(re.findall(r'\d+', \
re.split('_', art_file)[-1]))[3:7])
art_loc = days_between(art_date, date0) + 0.1 * np.float(art_sess)
if plot:
plt.plot(art_loc, 1, 'ro', lw=3, ms=10)
for l in range(len(linked_lists['art'])):
if art_file_number in linked_lists['art'][l] \
and art_file_number-1 in linked_lists['art'][l]:
if plot:
plt.plot(np.linspace(art_loc_prev, art_loc, 2), \
[1, 1], 'r-', lw=3)
art_loc_prev = art_loc
art_locs.append(art_loc)
# For each nat file
nat_loc_prev = -1
for nat_file_number, nat_file in enumerate(df.Natural.unique()):
nat_date = str(re.findall(r'\d+', re.split('_', nat_file)[0]))[3:9]
nat_sess = np.int(str(re.findall(r'\d+', \
re.split('_', nat_file)[-1]))[3:7])
nat_loc = days_between(nat_date, date0) + 0.1 * np.float(nat_sess)
if plot:
plt.plot(nat_loc, 2, 'go', lw=3, ms=10)
for l in range(len(linked_lists['nat'])):
if nat_file_number in linked_lists['nat'][l] \
and nat_file_number-1 in linked_lists['nat'][l]:
if plot:
plt.plot(np.linspace(nat_loc_prev, nat_loc, 2), \
[2, 2], 'g-', lw=3)
nat_loc_prev = nat_loc
nat_locs.append(nat_loc)
# Draw vertical lines between days
if plot:
for xax in np.arange(25):
plt.plot(xax * np.ones(10,), np.linspace(0.5, 2.5, 10), 'k--')
if plot:
plt.ylim([0.5, 2.5])
plt.xlim([0, 25])
#plt.axis('off')
plt.xlabel('Days')
plt.show()
return art_locs, nat_locs
#---------------------------------------
def get_filenames(sessions, df, colname):
return list(df.loc[df.index[0] + sessions][colname])
#---------------------------------------
def sessions_to_table_entry(df, neuron_name, linked_lists):
table_entry = list()
art_locs, nat_locs = show_sessions(df, linked_lists, plot=False)
art_locs = np.array(art_locs)
nat_locs = np.array(nat_locs)
for e, l in enumerate(linked_lists['art']):
art_sessions = np.arange(l[0], l[-1]+1)
art_filenames = get_filenames(art_sessions, df, 'Hue')
nat_sessions= np.where(np.all((nat_locs > art_locs[l[0]], \
nat_locs < art_locs[l[-1]]), axis=0))[0]
nat_filenames = get_filenames(nat_sessions, df, 'Natural')
table_entry.append([neuron_name,
art_sessions,
art_filenames,
nat_sessions,
nat_filenames])
return table_entry
#---------------------------------------
# Helpers for feature extraction
#---------------------------------------
def get_firing_rate(spike_times):
if np.size(spike_times)>1:
fr = len(spike_times)/(spike_times[-1]-spike_times[0])
else:
fr = 0
return fr
#---------------------------------------
def onehothue(theta, n_bins=16):
eps = np.finfo(np.float32).eps
if theta.ndim == 0:
h = np.histogram(theta,
bins=n_bins,
range=(-np.pi-eps, np.pi+eps))[0]
elif theta.ndim == 1:
h = list()
for th in theta:
h.append(np.histogram(th,
bins=n_bins,
range=(-np.pi-eps, np.pi+eps))[0])
else:
print 'Error: theta has to be a scalar or 1-d array'
h = np.array(h)
return h
#---------------------------------------
def circkurtosis(theta):
ck = 0.5 * (stats.kurtosis(theta) + \
stats.kurtosis(np.arctan(np.sin(theta + np.pi),
np.cos(theta + np.pi))))
return ck
#---------------------------------------
# Helpers for image manipulation
#---------------------------------------
def bgr_to_rgb(I):
"""Asserts channels last"""
assert I.shape[2]==3
I_copy = I.copy()
I_copy[:,:,0] = I[:,:,2]
I_copy[:,:,2] = I[:,:,0]
return I_copy
def get_image(stimpath, impath, imname):
filename = stimpath+'/'+impath+'/'+imname
I = plt.imread(filename)
if I is not None:
# BGR to RGB
I = bgr_to_rgb(I)
return I
#------------------------------------------
def pad_image(I):
[H,W,D] = I.shape
I_pad = 128*np.ones([3*H, 3*W, D])
I_pad[H-1:2*H-1,W-1:2*W-1,0] = I[:,:,0]
I_pad[H-1:2*H-1,W-1:2*W-1,1] = I[:,:,1]
I_pad[H-1:2*H-1,W-1:2*W-1,2] = I[:,:,2]
return I_pad
#------------------------------------------
def preprocess_image(I, imsize=(224, 224)):
"""Resizes image using linear interpolation"""
I = cv2.resize(I, imsize).astype(np.float32)
#I = I.transpose((2,0,1))
return I
#------------------------------------------
def get_hue_image(I):
# Convert to Luv
# Convert to Luv
I = I.astype(np.float32)
I *= 1./255
Luv = rgb2luv(I)
# Extract hue
hue = np.arctan2(Luv[:,:,2], Luv[:,:,1])
return hue
#------------------------------------------
def get_color_stats(im, summarize='mean'):
im_scaled = 1.0/255.0 * im.astype(np.float32)
im_hsv = cv2.cvtColor(im_scaled, cv2.COLOR_BGR2HSV)
sat = im_hsv[:,:,1]
lum = im_hsv[:,:,2]
if summarize == 'median':
return np.median(sat), np.median(lum)
elif summarize == 'mean':
return np.mean(sat), np.mean(lum)
#------------------------------------------
def visualize_hue_image(I):
# Convert to Luv
I = 1.0/255.0 * I.astype(np.float32)
Luv = cv2.cvtColor(I, cv2.COLOR_RGB2LUV);
# Assign lum channel to a constant
Luv[:,:,0] = 60.0*np.ones([Luv.shape[0], Luv.shape[1]])
# Convert back to RGB just to visualize
Iviz = cv2.cvtColor(Luv, cv2.COLOR_LUV2RGB);
return Iviz
#------------------------------------------
def grid_image(I, gridshape):
"""Agnostic to shape of image I
gridshape = () 2D list or tuple of # of grids"""
R = gridshape[0]
C = gridshape[1]
dtype_ = I.dtype
b_rows = np.int(np.floor(I.shape[0]/R))
b_cols = np.int(np.floor(I.shape[1]/C))
Block = np.zeros([R * C, b_rows, b_cols, I.shape[2]])
count = 0
for i in range(R):
for j in range(C):
I_cut = I[b_rows * i:b_rows * (i+1),
b_cols * j:b_cols *(j+1), :]
Block[count] = I_cut
count += 1
Block = Block.astype(dtype_)
return Block
#------------------------------------------
def get_hue_histogram(hue, n_bins):
eps = np.finfo(np.float32).eps
h = np.histogram(hue, bins=n_bins,
range=(-np.pi-eps, np.pi+eps))[0]
return h/float(np.sum(h))
from skimage.color import luv2rgb, rgb2luv
def weighted_hue_histogram(I, n_bins):
"""Returns the hue histogram of image I, but with each pixels;s hue contribution weighted by its distance
from the LUV long axis.
Inputs:
=======
I = RGB image"""
# Convert to Luv
I = I.astype(np.float32)
I *= 1./255
Luv = rgb2luv(I)
# get hues
hue = np.arctan2(Luv[:,:,2], Luv[:,:,1])
# and "saturation": dist from the LUV central axis
saturation = np.sqrt(np.square(Luv[:,:,2]) + np.square(Luv[:,:,1]))
eps = np.finfo(np.float32).eps
h = np.histogram(hue, bins=n_bins, weights=saturation,
range=(-np.pi-eps, np.pi+eps))[0]
h = h/float(hue.size*100)
return h
def prepare_image_for_vgg(im):
"""
Be careful that input image should be BGR
"""
# 01. Cast as float 32, and resize to 224 x 224 x 3
im_for_vgg = cv2.resize(im.astype(np.float32), (224, 224))
# 02. Subtract mean
im_for_vgg[:,:,0] -= 103.939
im_for_vgg[:,:,1] -= 116.779
im_for_vgg[:,:,2] -= 123.68
# 03. Reshape to 1 x 3 x 224 x 224
im_for_vgg = im_for_vgg.transpose((2, 0, 1))
im_for_vgg = np.expand_dims(im_for_vgg, axis=0)
return im_for_vgg
from skimage.color import luv2rgb, rgb2luv
def replace_with_gray(I, hue_range, saturation = 0):
"""Replaces a range of hues with isoluminant grey. Uses the LUV color space, taking U,V to some percentage
of their original values (set with 'saturation').
Inputs:
=======
I = RGB image
hue_range = (low_lim, high_lim), tuple of hue range (in radians, [-pi, pi]) to bring to grey.
Currently no support for intervals that include 0
saturdation = [0,1] """
# Convert to Luv
I = I.astype(np.float32)
I *= 1./255
Luv = rgb2luv(I)
# Take down hue, keeping luminance
just_lum = Luv.copy()
just_lum[:,:,1:] = saturation * just_lum[:,:,1:]
# get hues
hue = np.arctan2(Luv[:,:,2], Luv[:,:,1])
in_range = ((hue > hue_range[0]) & (hue < hue_range[1]))
#take this 2d array to 3d
in_range_3d = np.broadcast_to(in_range[:,:,np.newaxis],Luv.shape)
# return [L,0,0] if in range, or original pixel if not
Luv_prime = np.where(in_range_3d,just_lum, Luv)
# Bring back to RGB
I_prime = luv2rgb(Luv_prime)*255
# scale back upwards by 256 and round to recover (mad annoying that this is the case.)
I_prime = I_prime.astype(np.uint8)
return I_prime
#-------------------------------------------
from tqdm import tqdm
def get_nat_features(df,
reject_conditions={'filters.in_screen_radius': True, 'filters.badfix' : False},
stimpath='../V4pydata',
radius=200, RF_block=14,
n_histogram_bins=16,
model_list=['histogram'],
non_image_features_list=None):
"""
This is the master function to extract image features from
a data frame that has image name and image path
"""
image_features = list() # image features
non_image_features = list() # non-image features
accepted_indices = list()
if 'vgg' in model_list:
# Instantiate vgg models
vgg_model_l8 = vgg_transfer_ari(n_pops=0)
vgg_model_l7 = vgg_transfer_ari(n_pops=1)
vgg_model_l6 = vgg_transfer_ari(n_pops=2)
vgg_model_l5 = vgg_transfer_ari(n_pops=3)
# Loop through the data frame
for fx in tqdm(df.index):
# Check for reject conditions
select = list()
for k in reject_conditions.keys():
select.append(df.loc[fx][k] == reject_conditions[k])
select = np.all(select)
prev_impath, prev_imname = None, None
if select == True:
# Open image file
impath = df.loc[fx]['im.path']
imname = df.loc[fx]['im.name']
if(impath != prev_impath or imname != prev_imname):
I = get_image(stimpath=stimpath, impath=impath, imname=imname)
prev_impath, prev_imname = impath, imname
# Check for missing image file
if I is None:
continue
# Cut relevant fixation (maybe again)
r, c = int(df.loc[fx]['predictors.row']), int(df.loc[fx]['predictors.col'])
I_fix = I[r-radius:r+radius, c-radius:c+radius, :]
# Grid image into blocks
Block = grid_image(I_fix, [4, 4])
this_image_feature = dict()
# Extract feature for desired image
if 'histogram' in model_list:
hue_image = get_hue_image(Block[RF_block])
this_image_feature['hue.histogram'] = \
list(get_hue_histogram(hue_image, n_bins=n_histogram_bins))
this_image_feature['hue.mean'] = circmean(hue_image)
this_image_feature = pd.Series(this_image_feature)
if 'vgg' in model_list:
# Prepare the image for vgg input
I_fix_resize = cv2.resize(I_fix, (224,224)).astype('float32')
I_fix_for_vgg = preprocess_input( np.expand_dims(I_fix_resize, axis=0) )
# Compute feed forward pass
this_image_feature['vgg.l8'] = np.squeeze(vgg_model_l8.predict(I_fix_for_vgg))
this_image_feature['vgg.l7'] = np.squeeze(vgg_model_l7.predict(I_fix_for_vgg))
this_image_feature['vgg.l6'] = np.squeeze(vgg_model_l6.predict(I_fix_for_vgg))
this_image_feature['vgg.l5'] = np.squeeze(vgg_model_l5.predict(I_fix_for_vgg))
# Accumulate non-image features
this_non_image_feature = df.loc[fx][non_image_features_list]
# Collect features in a list
image_features.append(this_image_feature)
non_image_features.append(this_non_image_feature)
accepted_indices.append(fx)
# Put everything into a data frame
nat_features = pd.DataFrame({'image_features': image_features,
'non_image_features': non_image_features,
'accepted_indices': accepted_indices})
return nat_features
#--------------------------------
def nat_features_to_array(nat_features_df, image_feature='hue.histogram'):
"""
Take a data frame containing features of interest
and convert to array for model fitting
"""
n_samples = len(nat_features_df)
# Image features
n_features = len(nat_features_df['image_features'][nat_features_df.index[0]][image_feature])
image_features_array = np.zeros((n_samples, n_features))
image_features_list = [nat_features_df['image_features'][k][image_feature] \
for k in nat_features_df.index]
for k in range(n_samples):
image_features_array[k, :] = image_features_list[k]
# Non-image features
n_features = np.shape(nat_features_df['non_image_features'][nat_features_df.index[0]].values)[0]
non_image_features_array = np.zeros((n_samples, n_features))
non_image_features_list = [nat_features_df['non_image_features'][k].values \
for k in nat_features_df.index]
for k in range(n_samples):
non_image_features_array[k, :] = non_image_features_list[k]
# Concatenate
return np.concatenate((image_features_array,
non_image_features_array),
axis=1)
#---------------------------------------
# Helpers for fitting models
#---------------------------------------
def poisson_pseudo_R2(y, yhat, ynull):
y = np.squeeze(y)
yhat = np.squeeze(yhat)
eps = np.spacing(1)
L1 = np.sum(y * np.log(eps + yhat) - yhat)
L1_v = y * np.log(eps + yhat) - yhat
L0 = np.sum(y * np.log(eps + ynull) - ynull)
LS = np.sum(y * np.log(eps + y) - y)
R2 = 1 - (LS - L1) / (LS - L0)
return R2
#---------------------------------------
def XGB_poisson(Xr, Yr, Xt):
param = {'eta': 0.08340648569833894,
'gamma': 0.2933105726714027,
'max_depth':3,
'num_parallel_tree': 2,
'subsample': 0.4967204175437221}
param['nthread'] = 8
param['objective']= "count:poisson"
param['eval_metric']= "logloss"
param['seed']= 2925
param['silent']= 1
param['missing']= '-999.0'
param['nthread'] = 8
param['tree_method'] = 'hist'
dtrain = xgb.DMatrix(Xr, label=Yr)
dtest = xgb.DMatrix(Xt)
num_round = 200
bst = xgb.train(param, dtrain, num_round)
Yt = bst.predict(dtest)
return Yt
#---------------------------------------
def keras_GLM(input_dim, hidden_dim, learning_rate=0.0001,l1l2 = 0.01):
model = Sequential()
# Add a dense exponential layer with hidden_dim outputs
if hidden_dim > 0:
model.add(Dense(hidden_dim, input_shape=(input_dim,), \
kernel_initializer='glorot_normal', activation='relu'))
model.add(Dropout(0.5))
# Add a dense exponential layer with 1 output
model.add(Dense(1, kernel_initializer='glorot_normal', activation='softplus', \
activity_regularizer=l1_l2(l1l2)))
else:
# Add a dense exponential layer with 1 output
model.add(Dense(1, input_shape=(input_dim,),\
kernel_initializer='glorot_normal', activation='softplus', \
activity_regularizer=l1_l2(l1l2)))
optim = RMSprop(lr=learning_rate, clipnorm=0.5)
model.compile(loss='poisson', optimizer=optim)
return model
def keras_GLM_optimized(input_dim):
dropout = 0.4803795762081918
hidden_dim1 = 56
hidden_dim2 = 8
l2 = 2.2060897095713947e-08
learning_rate = 0.0014375751342219417
model = keras.models.Sequential()
# Add a dense exponential layer with hidden_dim outputs
model.add(keras.layers.Dense(int(hidden_dim1), input_shape=(input_dim,), \
kernel_initializer='glorot_normal', activation='relu',
activity_regularizer=keras.regularizers.l2(l2)))
model.add(keras.layers.Dropout(dropout))
model.add(keras.layers.normalization.BatchNormalization())
model.add(keras.layers.Dense(int(hidden_dim2), \
kernel_initializer='glorot_normal', activation='relu'))
model.add(keras.layers.normalization.BatchNormalization())
# Add a dense exponential layer with 1 output
model.add(keras.layers.Dense(1, kernel_initializer='glorot_normal', activation='softplus', ))
optim = keras.optimizers.adam(lr=learning_rate)
model.compile(loss='poisson', optimizer=optim)
return model
#---------------------------------------
def NN_poisson(Xr, Yr, Xt, batch_size, epochs, model = None):
if model is None:
model = keras_GLM_optimized(input_dim=Xr.shape[1])
model.fit(Xr, Yr, batch_size=batch_size, epochs=epochs, verbose=False)
Yt = model.predict(Xt)