-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoders.py
832 lines (588 loc) · 28.1 KB
/
decoders.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
############### IMPORT PACKAGES ##################
import numpy as np
from numpy.linalg import inv as inv #Used in kalman filter
#Import scikit-learn (sklearn) if it is installed
try:
from sklearn import linear_model #For Wiener Filter and Wiener Cascade
from sklearn.svm import SVR #For support vector regression (SVR)
except ImportError:
print("\nWARNING: scikit-learn is not installed. You will be unable to use the Wiener Filter or Wiener Cascade Decoders")
pass
#Import XGBoost if the package is installed
try:
import xgboost as xgb #For xgboost
except ImportError:
print("\nWARNING: Xgboost package is not installed. You will be unable to use the xgboost decoder")
pass
#Import functions for Keras if Keras is installed
#Note that Keras has many more built-in functions that I have not imported because I have not used them
#But if you want to modify the decoders with other functions (e.g. regularization), import them here
try:
from keras.models import Sequential
from keras.callbacks import TensorBoard
from keras.layers import Dense, LSTM, SimpleRNN, GRU, Activation, Dropout
import keras.backend as K
except ImportError:
print("\nWARNING: Keras package is not installed. You will be unable to use all neural net decoders")
pass
def modified_mse(y_true, y_pred): #### modified MSE loss function for absolute yaw data (0-360 values wrap around)
y_true = y_true * y_std + y_mean ### y_train_mean,y_train_std are GLOBALS ???
y_pred = y_pred * y_std + y_mean
mod_square = K.square(K.abs(y_pred - y_true) - 360) ### hack 2.1 = (360 - np.mean(ox)) / np.std(ox) 2.1086953197291871
raw_square = K.square(y_pred - y_true)
better = K.minimum(mod_square,raw_square)
return K.mean(better,axis=-1)
##################### DECODER FUNCTIONS ##########################
##################### WIENER FILTER ##########################
class WienerFilterDecoder(object):
"""
Class for the Wiener Filter Decoder
There are no parameters to set.
This simply leverages the scikit-learn linear regression.
"""
def __init__(self):
return
def fit(self,X_flat_train,y_train):
"""
Train Wiener Filter Decoder
Parameters
----------
X_flat_train: numpy 2d array of shape [n_samples,n_features]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
self.model=linear_model.LinearRegression() #Initialize linear regression model
self.model.fit(X_flat_train, y_train) #Train the model
def predict(self,X_flat_test):
"""
Predict outcomes using trained Wiener Cascade Decoder
Parameters
----------
X_flat_test: numpy 2d array of shape [n_samples,n_features]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
y_test_predicted=self.model.predict(X_flat_test) #Make predictions
return y_test_predicted
##################### WIENER CASCADE ##########################
class WienerCascadeDecoder(object):
"""
Class for the Wiener Cascade Decoder
Parameters
----------
degree: integer, optional, default 3
The degree of the polynomial used for the static nonlinearity
"""
def __init__(self,degree=3):
self.degree=degree
def fit(self,X_flat_train,y_train):
"""
Train Wiener Cascade Decoder
Parameters
----------
X_flat_train: numpy 2d array of shape [n_samples,n_features]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
num_outputs=y_train.shape[1] #Number of outputs
models=[] #Initialize list of models (there will be a separate model for each output)
for i in range(num_outputs): #Loop through outputs
#Fit linear portion of model
regr = linear_model.LinearRegression() #Call the linear portion of the model "regr"
regr.fit(X_flat_train, y_train[:,i]) #Fit linear
y_train_predicted_linear=regr.predict(X_flat_train) # Get outputs of linear portion of model
#Fit nonlinear portion of model
p=np.polyfit(y_train_predicted_linear,y_train[:,i],self.degree)
#Add model for this output (both linear and nonlinear parts) to the list "models"
models.append([regr,p])
self.model=models
def predict(self,X_flat_test):
"""
Predict outcomes using trained Wiener Cascade Decoder
Parameters
----------
X_flat_test: numpy 2d array of shape [n_samples,n_features]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
num_outputs=len(self.model) #Number of outputs being predicted. Recall from the "fit" function that self.model is a list of models
y_test_predicted=np.empty([X_flat_test.shape[0],num_outputs]) #Initialize matrix that contains predicted outputs
for i in range(num_outputs): #Loop through outputs
[regr,p]=self.model[i] #Get the linear (regr) and nonlinear (p) portions of the trained model
#Predictions on test set
y_test_predicted_linear=regr.predict(X_flat_test) #Get predictions on the linear portion of the model
y_test_predicted[:,i]=np.polyval(p,y_test_predicted_linear) #Run the linear predictions through the nonlinearity to get the final predictions
return y_test_predicted
##################### KALMAN FILTER ##########################
class KalmanFilterDecoder(object):
"""
Class for the Kalman Filter Decoder
Parameters
-----------
C - float, optional, default 1
This parameter scales the noise matrix associated with the transition in kinematic states.
It effectively allows changing the weight of the new neural evidence in the current update.
Our implementation of the Kalman filter for neural decoding is based on that of Wu et al 2003 (https://papers.nips.cc/paper/2178-neural-decoding-of-cursor-motion-using-a-kalman-filter.pdf)
with the exception of the addition of the parameter C.
The original implementation has previously been coded in Matlab by Dan Morris (http://dmorris.net/projects/neural_decoding.html#code)
"""
def __init__(self,C=1):
self.C=C
def fit(self,X_kf_train,y_train):
"""
Train Kalman Filter Decoder
Parameters
----------
X_kf_train: numpy 2d array of shape [n_samples(i.e. timebins) , n_neurons]
This is the neural data in Kalman filter format.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples(i.e. timebins), n_outputs]
This is the outputs that are being predicted
"""
#First we'll rename and reformat the variables to be in a more standard kalman filter nomenclature (specifically that from Wu et al, 2003):
#xs are the state (here, the variable we're predicting, i.e. y_train)
#zs are the observed variable (neural data here, i.e. X_kf_train)
X=np.matrix(y_train.T)
Z=np.matrix(X_kf_train.T)
#number of time bins
nt=X.shape[1]
#Calculate the transition matrix (from x_t to x_t+1) using least-squares, and compute its covariance
#In our case, this is the transition from one kinematic state to the next
X2 = X[:,1:]
X1 = X[:,0:nt-1]
A=X2*X1.T*inv(X1*X1.T) #Transition matrix
W=(X2-A*X1)*(X2-A*X1).T/(nt-1)/self.C #Covariance of transition matrix. Note we divide by nt-1 since only nt-1 points were used in the computation (that's the length of X1 and X2). We also introduce the extra parameter C here.
#Calculate the measurement matrix (from x_t to z_t) using least-squares, and compute its covariance
#In our case, this is the transformation from kinematics to spikes
H = Z*X.T*(inv(X*X.T)) #Measurement matrix
Q = ((Z - H*X)*((Z - H*X).T)) / nt #Covariance of measurement matrix
params=[A,W,H,Q]
self.model=params
def predict(self,X_kf_test,y_test):
"""
Predict outcomes using trained Kalman Filter Decoder
Parameters
----------
X_kf_test: numpy 2d array of shape [n_samples(i.e. timebins) , n_neurons]
This is the neural data in Kalman filter format.
y_test_predicted: numpy 2d array of shape [n_samples(i.e. timebins),n_outputs]
The actual outputs
This parameter is necesary for the Kalman filter (unlike other decoders)
because the first value is nececessary for initialization
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples(i.e. timebins),n_outputs]
The predicted outputs
"""
#Extract parameters
A,W,H,Q=self.model
#First we'll rename and reformat the variables to be in a more standard kalman filter nomenclature (specifically that from Wu et al):
#xs are the state (here, the variable we're predicting, i.e. y_train)
#zs are the observed variable (neural data here, i.e. X_kf_train)
X=np.matrix(y_test.T)
Z=np.matrix(X_kf_test.T)
#Initializations
num_states=X.shape[0] #Dimensionality of the state
states=np.empty(X.shape) #Keep track of states over time (states is what will be returned as y_test_predicted)
P_m=np.matrix(np.zeros([num_states,num_states]))
P=np.matrix(np.zeros([num_states,num_states]))
state=X[:,0] #Initial state
states[:,0]=np.copy(np.squeeze(state))
#Get predicted state for every time bin
for t in range(X.shape[1]-1):
#Do first part of state update - based on transition matrix
P_m=A*P*A.T+W
state_m=A*state
#Do second part of state update - based on measurement matrix
K=P_m*H.T*inv(H*P_m*H.T+Q) #Calculate Kalman gain
P=(np.matrix(np.eye(num_states))-K*H)*P_m
state=state_m+K*(Z[:,t+1]-H*state_m)
states[:,t+1]=np.squeeze(state) #Record state at the timestep
y_test_predicted=states.T
return y_test_predicted
##################### DENSE (FULLY-CONNECTED) NEURAL NETWORK ##########################
class DenseNNDecoder(object):
"""
Class for the dense (fully-connected) neural network decoder
Parameters
----------
units: integer or vector of integers, optional, default 400
This is the number of hidden units in each layer
If you want a single layer, input an integer (e.g. units=400 will give you a single hidden layer with 400 units)
If you want multiple layers, input a vector (e.g. units=[400,200]) will give you 2 hidden layers with 400 and 200 units, repsectively.
The vector can either be a list or an array
dropout: decimal, optional, default 0
Proportion of units that get dropped out
num_epochs: integer, optional, default 10
Number of epochs used for training
verbose: binary, optional, default=0
Whether to show progress of the fit after each epoch
"""
def __init__(self,units=400,dropout=0,num_epochs=15,verbose=1):
self.dropout=dropout
self.num_epochs=num_epochs
self.verbose=verbose
#If "units" is an integer, put it in the form of a vector
try: #Check if it's a vector
units[0]
except: #If it's not a vector, create a vector of the number of units for each layer
units=[units]
self.units=units
#Determine the number of hidden layers (based on "units" that the user entered)
self.num_layers=len(units)
def fit(self,X_flat_train,y_train):
"""
Train DenseNN Decoder
Parameters
----------
X_flat_train: numpy 2d array of shape [n_samples,n_features]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
model=Sequential() #Declare model
#Add first hidden layer
model.add(Dense(self.units[0],input_dim=X_flat_train.shape[1])) #Add dense layer
model.add(Activation('relu')) #Add nonlinear (tanh) activation
# if self.dropout!=0:
if self.dropout!=0: model.add(Dropout(self.dropout)) #Dropout some units if proportion of dropout != 0
#Add any additional hidden layers (beyond the 1st)
for layer in range(self.num_layers-1): #Loop through additional layers
model.add(Dense(self.units[layer+1])) #Add dense layer
model.add(Activation('relu')) #Add nonlinear (tanh) activation
if self.dropout!=0: model.add(Dropout(self.dropout)) #Dropout some units if proportion of dropout != 0
#Add dense connections to all outputs
model.add(Dense(y_train.shape[1])) #Add final dense layer (connected to outputs)
#Fit model (and set fitting parameters)
model.compile(loss='mse',optimizer='adam',metrics=['accuracy']) #Set loss function and optimizer
model.fit(X_flat_train,y_train,nb_epoch=self.num_epochs,verbose=self.verbose) #Fit the model
self.model=model
def predict(self,X_flat_test):
"""
Predict outcomes using trained DenseNN Decoder
Parameters
----------
X_flat_test: numpy 2d array of shape [n_samples,n_features]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
y_test_predicted = self.model.predict(X_flat_test) #Make predictions
return y_test_predicted
##################### SIMPLE RECURRENT NEURAL NETWORK ##########################
class SimpleRNNDecoder(object):
"""
Class for the simple recurrent neural network decoder
Parameters
----------
units: integer, optional, default 400
Number of hidden units in each layer
dropout: decimal, optional, default 0
Proportion of units that get dropped out
num_epochs: integer, optional, default 10
Number of epochs used for training
verbose: binary, optional, default=0
Whether to show progress of the fit after each epoch
"""
def __init__(self,units=400,dropout=0,num_epochs=10,verbose=0):
self.units=units
self.dropout=dropout
self.num_epochs=num_epochs
self.verbose=verbose
def fit(self,X_train,y_train):
"""
Train SimpleRNN Decoder
Parameters
----------
X_train: numpy 3d array of shape [n_samples,n_time_bins,n_neurons]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
model=Sequential() #Declare model
#Add recurrent layer
model.add(SimpleRNN(self.units,input_shape=(X_train.shape[1],X_train.shape[2]),dropout_W=self.dropout,dropout_U=self.dropout,activation='relu')) #Within recurrent layer, include dropout
if self.dropout!=0: model.add(Dropout(self.dropout)) #Dropout some units (recurrent layer output units)
#Add dense connections to output layer
model.add(Dense(y_train.shape[1]))
model.add(Dense(y_train.shape[1]))
#Fit model (and set fitting parameters)
model.compile(loss='mse',optimizer='rmsprop',metrics=['accuracy']) #Set loss function and optimizer
model.fit(X_train,y_train,nb_epoch=self.num_epochs,verbose=self.verbose) #Fit the model
model.summary()
TensorBoard(log_dir='./logs', histogram_freq=1, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
self.model=model
def predict(self,X_test):
"""
Predict outcomes using trained SimpleRNN Decoder
Parameters
----------
X_test: numpy 3d array of shape [n_samples,n_time_bins,n_neurons]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
y_test_predicted = self.model.predict(X_test) #Make predictions
return y_test_predicted
##################### GATED RECURRENT UNIT (GRU) DECODER ##########################
class GRUDecoder(object):
"""
Class for the gated recurrent unit (GRU) decoder
Parameters
----------
units: integer, optional, default 400
Number of hidden units in each layer
dropout: decimal, optional, default 0
Proportion of units that get dropped out
num_epochs: integer, optional, default 10
Number of epochs used for training
verbose: binary, optional, default=0
Whether to show progress of the fit after each epoch
"""
def __init__(self,units=400,dropout=0,num_epochs=10,verbose=0):
self.units=units
self.dropout=dropout
self.num_epochs=num_epochs
self.verbose=verbose
def fit(self,X_train,y_train):
"""
Train GRU Decoder
Parameters
----------
X_train: numpy 3d array of shape [n_samples,n_time_bins,n_neurons]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
model=Sequential() #Declare model
#Add recurrent layer
model.add(GRU(self.units,input_shape=(X_train.shape[1],X_train.shape[2]),dropout_W=self.dropout,dropout_U=self.dropout)) #Within recurrent layer, include dropout
if self.dropout!=0: model.add(Dropout(self.dropout)) #Dropout some units (recurrent layer output units)
#Add dense connections to output layer
model.add(Dense(y_train.shape[1]))
#Fit model (and set fitting parameters)
model.compile(loss='mse',optimizer='rmsprop',metrics=['accuracy']) #Set loss function and optimizer
model.fit(X_train,y_train,nb_epoch=self.num_epochs,verbose=self.verbose) #Fit the model
self.model=model
def predict(self,X_test):
"""
Predict outcomes using trained GRU Decoder
Parameters
----------
X_test: numpy 3d array of shape [n_samples,n_time_bins,n_neurons]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
y_test_predicted = self.model.predict(X_test) #Make predictions
return y_test_predicted
#################### LONG SHORT TERM MEMORY (LSTM) DECODER ##########################
class LSTMDecoder(object):
"""
Class for the gated recurrent unit (GRU) decoder
Parameters
----------
units: integer, optional, default 400
Number of hidden units in each layer
dropout: decimal, optional, default 0
Proportion of units that get dropped out
num_epochs: integer, optional, default 10
Number of epochs used for training
verbose: binary, optional, default=0
Whether to show progress of the fit after each epoch
"""
def __init__(self,units=15,dropout=0,num_epochs=10,verbose=1):
self.units=units
self.dropout=dropout
self.num_epochs=num_epochs
self.verbose=verbose
def get_means(self,y_train_mean,y_train_std):
global y_mean
global y_std
y_mean = y_train_mean
y_std = y_train_std
def fit(self,X_train,y_train):
"""
Train LSTM Decoder
Parameters
----------
X_train: numpy 3d array of shape [n_samples,n_time_bins,n_neurons]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
model=Sequential() #Declare model
#Add recurrent layer
model.add(GRU(self.units,activation='tanh',input_shape=(X_train.shape[1],X_train.shape[2]),dropout_W=self.dropout,dropout_U=self.dropout)) #Within recurrent layer, include dropout
if self.dropout!=0: model.add(Dropout(self.dropout)) #Dropout some units (recurrent layer output units)
# recurrent_activation='hard_sigmoid'
#model.add(Dense(10,activation='tanh')) #return_sequences=True
#model.add(Dense(64,activation='tanh')) #return_sequences=True
#model.add(Dense(4,activation = 'tanh'))
#Add dense connections to output layer
model.add(Dense(y_train.shape[1])) #,activation='relu' def don't want relu on the output
#Fit model (and set fitting parameters)
model.compile(loss='mse',optimizer='rmsprop',metrics=['accuracy']) #Set loss function and optimizer
model.fit(X_train,y_train,nb_epoch=self.num_epochs,verbose=self.verbose) #Fit the model
model.summary()
TensorBoard(log_dir='./logs', histogram_freq=1, batch_size=32, write_graph=True, write_grads=False, write_images=False, embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)
self.model=model
def predict(self,X_test):
"""
Predict outcomes using trained LSTM Decoder
Parameters
----------
X_test: numpy 3d array of shape [n_samples,n_time_bins,n_neurons]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
y_test_predicted = self.model.predict(X_test) #Make predictions
return y_test_predicted
##################### EXTREME GRADIENT BOOSTING (XGBOOST) ##########################
class XGBoostDecoder(object):
"""
Class for the XGBoost Decoder
Parameters
----------
max_depth: integer, optional, default=3
the maximum depth of the trees
num_round: integer, optional, default=300
the number of trees that are fit
eta: float, optional, default=0.3
the learning rate
gpu: integer, optional, default=-1
if the gpu version of xgboost is installed, this can be used to select which gpu to use
for negative values (default), the gpu is not used
"""
def __init__(self,max_depth=3,num_round=300,eta=0.3,gpu=-1):
self.max_depth=max_depth
self.num_round=num_round
self.eta=eta
self.gpu=gpu
def fit(self,X_flat_train,y_train):
"""
Train XGBoost Decoder
Parameters
----------
X_flat_train: numpy 2d array of shape [n_samples,n_features]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
num_outputs=y_train.shape[1] #Number of outputs
#Set parameters for XGBoost
param = {'objective': "reg:linear", #for linear output
'eval_metric': "logloss", #loglikelihood loss
'max_depth': self.max_depth, #this is the only parameter we have set, it's one of the way or regularizing
'eta': self.eta,
'seed': 2925, #for reproducibility
'silent': 1}
if self.gpu<0:
param['nthread'] = -1 #with -1 it will use all available threads
else:
param['gpu_id']=self.gpu
param['updater']='grow_gpu'
models=[] #Initialize list of models (there will be a separate model for each output)
for y_idx in range(num_outputs): #Loop through outputs
dtrain = xgb.DMatrix(X_flat_train, label=y_train[:,y_idx]) #Put in correct format for XGB
bst = xgb.train(param, dtrain, self.num_round) #Train model
models.append(bst) #Add fit model to list of models
self.model=models
def predict(self,X_flat_test):
"""
Predict outcomes using trained XGBoost Decoder
Parameters
----------
X_flat_test: numpy 2d array of shape [n_samples,n_features]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
dtest = xgb.DMatrix(X_flat_test) #Put in XGB format
num_outputs=len(self.model) #Number of outputs
y_test_predicted=np.empty([X_flat_test.shape[0],num_outputs]) #Initialize matrix of predicted outputs
for y_idx in range(num_outputs): #Loop through outputs
bst=self.model[y_idx] #Get fit model for this output
y_test_predicted[:,y_idx] = bst.predict(dtest) #Make prediction
return y_test_predicted
##################### SUPPORT VECTOR REGRESSION ##########################
class SVRDecoder(object):
"""
Class for the Support Vector Regression (SVR) Decoder
This simply leverages the scikit-learn SVR
Parameters
----------
C: float, default=3.0
Penalty parameter of the error term
max_iter: integer, default=-1
the maximum number of iteraations to run (to save time)
max_iter=-1 means no limit
Typically in the 1000s takes a short amount of time on a laptop
"""
def __init__(self,max_iter=-1,C=3.0,gamma='auto'):
self.max_iter=max_iter
self.C=C
self.gamma = gamma
return
def fit(self,X_flat_train,y_train):
"""
Train SVR Decoder
Parameters
----------
X_flat_train: numpy 2d array of shape [n_samples,n_features]
This is the neural data.
See example file for an example of how to format the neural data correctly
y_train: numpy 2d array of shape [n_samples, n_outputs]
This is the outputs that are being predicted
"""
num_outputs=y_train.shape[1] #Number of outputs
models=[] #Initialize list of models (there will be a separate model for each output)
for y_idx in range(num_outputs): #Loop through outputs
model=SVR(C=self.C, max_iter=self.max_iter,gamma=self.gamma) #Initialize SVR model
model.fit(X_flat_train, y_train[:,y_idx]) #Train the model
models.append(model) #Add fit model to list of models
self.model=models
def predict(self,X_flat_test):
"""
Predict outcomes using trained Wiener Cascade Decoder
Parameters
----------
X_flat_test: numpy 2d array of shape [n_samples,n_features]
This is the neural data being used to predict outputs.
Returns
-------
y_test_predicted: numpy 2d array of shape [n_samples,n_outputs]
The predicted outputs
"""
num_outputs=len(self.model) #Number of outputs
y_test_predicted=np.empty([X_flat_test.shape[0],num_outputs]) #Initialize matrix of predicted outputs
for y_idx in range(num_outputs): #Loop through outputs
model=self.model[y_idx] #Get fit model for that output
y_test_predicted[:,y_idx]=model.predict(X_flat_test) #Make predictions
return y_test_predicted