-
Notifications
You must be signed in to change notification settings - Fork 17
/
pulsar_nnetwork.py
1300 lines (1087 loc) · 42.5 KB
/
pulsar_nnetwork.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
#!/usr/bin/env python
"""
Aaron Berndsen (2012)
a neural network implementation in python, with f2py/fortran
optimizations for large data sets
"""
import numpy as np
import cPickle
import pylab as plt
from scipy import io
from scipy import mgrid
from scipy.optimize import fmin_cg
import sys
from sklearn.base import BaseEstimator
#Aaron's fortran-optimized openmp code
try:
from nnopt import sigmoid2d, matmult
_fort_opt = True
except(ImportError):
print "NeuralNetwork not using fortran-optimized code"
print "Refer to nn_optimize.f90 for tips"
print "defaulting to vectorized numpy implementation"
_fort_opt = False
#number of iterations in training
_niter = 0
def main():
""" not really used """
################
# load the data
data = handwritingpix(samples='ex4data1.mat',
thetas='ex4weights.mat'
)
################
# show some samples of the data
data.plot_samples(15)
###############
# create the neural network,
nn = NeuralNetwork(gamma=0.)
def load_pickle(fname):
"""
recover from a pickled NeuralNetwork classifier
the neural design (nfeatures, nlayers, ntargets) are
determined by the 'thetas' in the pickle
"""
d = cPickle.load(open(fname,'r'))
nlayers = d['nlayers']
gamma = d['gamma']
thetas = []
for li in range(nlayers):
thetas.append(d[li])
classifier = NeuralNetwork(gamma=gamma, thetas=thetas)
return classifier
class layer(object):
"""
a layer in the neural network. It takes
in N parameters and outputs m attributes
N and m should include the bias term (if appropriate)
output = Theta*trial_colvector
optional:
theta = the transformation matrix of size (N+1,m) (includes bias)
otherwise randomly initialize theta
we uniformly initialize theta over [-delta, delta]
where delta = sqrt(6)/sqrt(N+m), or passed as argument
shiftlayer = False. If true, we repeat the first neuron weightings, shifted.
"""
def __init__(self, n, m, theta=np.array([]), delta=0, shiftlayer=False):
#n includes bias
self.inp = n
self.output = m
self.shiftlayer = shiftlayer
if len(theta):
self.theta = theta
else:
# use random initialization
if not delta:
delta = np.sqrt(6)/np.sqrt(n + m)
self.randomize(delta)
def randomize(self, delta=None):
"""
randomize the theta's for each 'fit' call in the neural network
"""
N = self.inp
m = self.output
if not delta:
delta = np.sqrt(6)/np.sqrt( N + m)
self.theta = np.random.uniform(-delta, delta, N*m).reshape(N, m)
if self.shiftlayer:
#make sure the subsequent layers are simply a shifted copy of the first
l1 = self.theta[:,0]
dshift = N//m
for i in range(m-1):
shift = dshift * (i+1)
self.theta[:,i+1] = np.roll(l1, shift)
class NeuralNetwork(BaseEstimator):
"""
a collection of layers forming the neural network
Args:
* gamma = learning rate (regularization parameter), default = 0.
* thetas = None (initialize the NN with neurons/layers determined
by the list of internal 'Thetas'
(default = None, defers until .fit call)
* design = None (initialize the NN with neurons/layers determined
by the list of neurons per layer
Eg. desing=[25,4] = 2-layers, first with 25, second with 4
* fit_type = ['all','single'] . Fit the individual layers 'all' at once (default)
or build up the NN, fitting a 'single' layer at a time,
then adding the next layer.
* maxiter : number of iterations in self.fit's conjugate-gradient minimization
default = 100, can be overriden elsewhere (self.fit)
* shiftlayer : if not None, instead of having N independent neurons in this layer,
we reproduce the first neuron N-times, shifting the weights of the first one.
This is meant to help remove phase-dependence of the pulse.
shiftlayer in [0, 1, 2, ...] number of hidden layers
Notes:
* if design != None and thetas != None, we get shape
from the thetas
* if design = thetas = None, we determine design in fit routine
"""
def __init__(self, gamma=0., thetas=None, design=None,
fit_type='all', maxiter=None, shiftlayer=None, verbose=False):
self.gamma = gamma
self.design = design
self.fit_type = fit_type
self.nin = None
self.nout = None
if maxiter == None:
self.maxiter = 100
else:
self.maxiter = maxiter
self.shiftlayer = shiftlayer
if thetas != None:
nfeatures = thetas[0].shape[0]-1
ntargets = thetas[1].shape[1]
self.create_layers(nfeatures, ntargets, thetas=thetas, verbose=verbose,\
shiftlayer=shiftlayer)
self.verbose = verbose
self.nfit = 0 # keep track of number of times the classifier has been 'fit'
def create_layers(self, nfeatures, ntargets, design=None, gamma=None,
thetas=None, verbose=None, shiftlayer=None):
"""
This routine is called by 'fit', and adjust the network design
for varying feature and target length, as well as network design.
Args:
nfeatures: number of features
ntargets : number of target labels
design : list of neurons per layer.
Default = None, use self.design (if provided at init),
otherwise default to [16] = one layer of 16 neurons
Eg. design=[16,4] = a layer of 16 neurons, then a layer of 4 neurons
gamma : update self.gamma, the regularization parameter
thetas = None : can pass neural mappings as list of arrays (a list of thetas),
otherwise they are randomly initialized (better).
This overrides 'design'
shiftlayer = None: if not None, the theta is simply a shifted repeat of the first neuron
in this layer
"""
if design == None:
if self.design != None:
design = self.design
else:
design = [16]
if isinstance(design, type(int())):
design = [design]
if thetas != None:
design = []
for theta in thetas[:-1]:
design.append(theta.shape[1])
self.design = design
if gamma != None:
self.gamma = gamma
layers = []
nl = len(design) + 1
for idx in range(nl):
if thetas != None:
theta = thetas[idx]
else:
theta = np.array([])
# add bias to all inputs
if idx == 0:
lin = nfeatures + 1 #add bias
else:
lin = design[idx - 1] + 1
# add bias to outputs for internal/hidden layers
if idx == nl - 1:
lout = ntargets
else:
lout = design[idx]
if shiftlayer is not None:
if idx == shiftlayer:
layers.append(layer(lin, lout, theta, shiftlayer=True))
else:
layers.append(layer(lin, lout, theta, shiftlayer=False))
else:
layers.append(layer(lin, lout, theta, shiftlayer=False))
if verbose or self.verbose:
txt = "Created (network, gamma) = (%s-->" % (nfeatures)
for idx in design:
txt += "%s-->" % idx
txt += "%s, %s) " % (ntargets, self.gamma)
print(txt)
self.design = design
self.ntargets = ntargets
self.layers = layers
self.nlayers = len(layers)
def unflatten_thetas(self, thetas):
"""
in order to use scipy.fmin functions we
need to make the Theta dependance explicit.
This routine takes a flattened array 'thetas' of
all the internal layer 'thetas', then assigns them
onto their respective layers
(ordered from earliest to latest layer)
"""
bi = 0
for lv in self.layers:
shape = lv.theta.shape
ei = bi + shape[0] * shape[1]
lv.theta = thetas[bi:ei].reshape(shape)
bi = ei
def flatten_thetas(self):
"""
in order to use scipy.fmin functions we
need to make the layer's Theta dependencies explicit.
this routine returns a giant array of all the flattened
internal theta's, from earliest to latest layers
"""
z = np.array([])
for lv in self.layers:
z = np.hstack([z, lv.theta.flatten()])
return z
def costFunctionU(self, X, y, gamma=None):
"""
routine which calls costFunction, but
unwraps the internal parameters (theta's)
for you
"""
thetas = self.flatten_thetas()
return self.costFunction(thetas, X, y, gamma)
def costFunction(self, thetas, X, y, gamma=None, verbose=None):
"""
determine the cost function for this neural network
given the training data X, classifcations y,
and learning rate (regularization) lambda
Arguments:
X : num_trials x ninputs, ninputs not including bias term
return cost
y : classification label for the num_trials
gamma : regularization parameter,
default = None = self.gamma
verbose: printing out training information (cost, #iterations)
"""
global _niter
if isinstance(X, type([])):
X = np.array(X)
if gamma == None:
gamma = self.gamma
# testing: check the theta's are changing while we train: yes!
# print "CF",thetas[0:2], thetas[-5:-2]
# update the layer's theta's
self.unflatten_thetas(thetas)
# number of trials
if X.ndim == 2:
N = X.shape[0]
else:
N = 1
# propagate the input through the entire network
z, h = self.forward_propagate(X)
yy = labels2vectors(y, self.ntargets)
J = 0.
J = (-np.log(h) * yy.transpose() - np.log(1-h)*(1-yy.transpose())).sum()
J = J/N
# regularize (ignoring bias):
reg = 0.
for l in self.layers:
reg += (l.theta[1:, :]**2).sum()
J = J + gamma*reg/(2*N)
if verbose or self.verbose:
if _niter % 25 == 0:
sys.stdout.write("\r\t(fit %s) NN.fit iter %s, Cost %12.7f "
% (self.nfit,_niter, J))
sys.stdout.flush()
_niter += 1
return J
def forward_propagate(self, z, nl=100):
"""
given an array of samples [nsamples, nproperties]
propagate the sample through the neural network,
Returns:
z, a : the ouputs and activations (z(nl),acts(nl)) at layer nl
Args:
X = [nsamples, nproperties] (no bias)
nl = number of layers to propagte through
defaults to end (well, one hundred layers!)
"""
if isinstance(z, type([])):
z = np.array(z)
# number of trials
if z.ndim == 2:
N = z.shape[0]
# add bias
a = np.hstack([np.ones((N, 1)), z])
else:
N = 1
# add bias
a = np.hstack([np.ones(N), z])
final_layer = len(self.layers) - 1
for li, lv in enumerate(self.layers[0:nl]):
z = np.dot(a, lv.theta)
# add bias to input of each internal layer
if li != final_layer:
if N == 1 and z.ndim == 1:
a = np.hstack([np.ones(N), sigmoid(z)])
else:
if _fort_opt:
a = np.hstack([np.ones((N, 1)), sigmoid2d(z)])
else:
a = np.hstack([np.ones((N, 1)), sigmoid(z)])
else:
if N == 1:
a = sigmoid(z)
else:
if _fort_opt:
a = sigmoid2d(z)
else:
a = sigmoid(z)
return z, a
def gradientU(self, X, y, gamma=None, shiftlayer=None, verbose=None):
"""
Convenience function.
routine which calls gradient, but
unwraps the internal parameters (theta's)
for you.
needed for scipy.fmin functions
"""
thetas = self.flatten_thetas()
return self.gradient(thetas, X, y, gamma, verbose=verbose)
def gradient(self, thetas, X, y, gamma=None, verbose=None):
"""
compute the gradient at each layer of the neural network
Args:
X = [nsamples, ninputs]
y = [nsamples] #the training classifications
gamma : regularization parameter
default = None = self.gamma
shiftlayer : None, or the layer which
returns the gradient for the parameters of the neural network
(the theta's) unrolled into one large vector, ordered from
the first layer to latest.
"""
if isinstance(X, type([])):
X = np.array(X)
if gamma == None:
gamma = self.gamma
N = X.shape[0]
nl = len(self.layers)
# create our grad_theta arrays (init to zero):
grads = {}
for li, lv in enumerate(self.layers):
grads[li] = np.zeros_like(lv.theta)
# vectorize sample-loop
if 1:
for li in range(nl, 0, -1):
z, a = self.forward_propagate(X,li)
if li == nl:
ay = labels2vectors(y, self.ntargets).transpose()
delta = (a - ay)
else:
theta = self.layers[li].theta
aprime = np.hstack([np.ones((N,1)), sigmoidGradient(z)]) #add in bias
#use fortran matmult if arrays are large
if _fort_opt and deltan.size * theta.size > 100000:
tmp = matmult(deltan,theta.transpose())
else:
tmp = np.dot(deltan,theta.transpose())#nsamples x neurons(li)
delta = tmp*aprime
#find contribution to grad
idx = li - 1
z, a = self.forward_propagate(X,idx)
if idx in grads:
if li == nl:
grads[idx] = np.dot(a.transpose(), delta)/N
else:
#strip off bias
grads[idx] = np.dot(a.transpose(), delta[:,1:])/N
#if this is a "shift-invar" layer, find the average grad
if self.shiftlayer is not None:
if li == self.shiftlayer:
shape = self.layers[li].theta.shape
grads = grads.reshape(shape)
l1 = grads[:,0]
dshift = N//m
for i in range(m-1):
shift = -dshift * (i+1) #undo the previous shifts
self.theta[:,i+1] = np.roll(l1, shift)
grad_avg = self.theta.mean(axis=0)
grads = np.array([grad_avg for i in range(shape[1])]).flatten()
#keep this delta for the next (earlier) layer
if li == nl:
deltan = delta
else:
deltan = delta[:,1:]
#now regularize the grads (bias doesn't get get regularized):
for li, lv in enumerate(self.layers):
theta = lv.theta
grads[li][:, 1:] = grads[li][:, 1:] + gamma/N*theta[:, 1:]
#finally, flatten the gradients
z = np.array([])
for k in sorted(grads):
v = grads[k]
z = np.hstack([z, v.flatten()])
return z
def score(self, X, y):
"""Returns the mean accuracy on the given test data and labels.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training set.
y : array-like, shape = [n_samples]
Labels for X.
Returns
-------
z : float
"""
return np.mean(self.predict(X) == y)
def fit(self, X, y, design=None, gamma=None,
gtol=1e-05, epsilon=1.4901161193847656e-08, maxiter=None,
raninit=True, info=False, verbose=None, fit_type=None):
"""
Train the data.
minimize the cost function (wrt the Theta's)
(using the conjugate gradient algorithm from scipy)
This updates the NN.layers.theta's, so one can
later "predict" other samples.
** The number of input features is determined from X.shape[1],
and the number of targets from np.unique(y), so make sure
'y' spans your target space.
Args:
X : the training samples [nsamples x nproperties]
y : the sample labels [nsamples], each entry in range 0<=y<nclass
design : list of number of neurons in each layer.
Default = None, uses self.create_layers default=[16]
Eg. design=[12,3] is a neural network with 2 layers of 12, then 3 neurons
(we add bias later)
gamma : regularization parameter
default = None = self.gammas
verbose : print out layer-creation information
*for scipy.optimize.fmin_cg:
gtol
epsilon
maxiter
info : T/F, return the information from fmin_cg (Default False)
raninit : T/F randomly initialize the theta's [default = True]
(only use 'False' to continue training, not for new NN's)
"""
global _niter
_niter = 0
if gamma == None:
gamma = self.gamma
if verbose or self.verbose:
verbose = True
if fit_type == None:
fit_type = self.fit_type
if maxiter == None:
maxiter = self.maxiter
# train all layers at same time
if fit_type == 'all':
#update the NN layers (if necessary)
if raninit:
self.create_layers(X.shape[1],
np.unique(y).size,
design=design,
gamma=gamma,
verbose=verbose,
shiftlayer=self.shiftlayer)
for lv in self.layers:
lv.randomize()
thetas = self.flatten_thetas()
xopt = fmin_cg(f=self.costFunction,
x0=thetas,
fprime=self.gradient,
args=(X, y, gamma, verbose), #extra args to costFunction
maxiter=maxiter,
epsilon=epsilon,
gtol=gtol,
disp=0,
)
# build up the NN, training each layer one at a time
elif fit_type == 'single':
if design == None:
design = self.design
if self.nin == None:
self.nin = X.shape[1]
self.nout = np.unique(y).size
# train the individual layers
thetas = []
for lyr in range(len(design)):
if verbose:
print "\nTraining layer %s" % (lyr+1)
nn = NeuralNetwork(gamma = gamma,
design = design[0:lyr+1],
fit_type='all'
)
nn.create_layers(self.nin,
self.nout,
design=design[0:lyr+1],
gamma=gamma,
verbose=verbose,
shiftlayer=self.shiftlayer)
for lyri, theta in enumerate(thetas):
nn.layers[lyri].theta = theta
nn.fit(X, y,
gtol=gtol, epsilon=epsilon, maxiter=maxiter,
raninit=False, info=info, verbose=verbose)
thetas =[nn.layers[i].theta for i in range(lyr+1)]
#.append(nn.layers[lyr].theta)
#end design loop
# (diagnostics)
# if verbose:
# nn.plot_firstlayer()
# transfer the Theta's to our NN
self.create_layers(X.shape[1],
np.unique(y).size,
design=design,
gamma=gamma,
verbose=verbose,
shiftlayer=self.shiftlayer)
# for lyri, theta in enumerate(thetas):
# self.layers[lyri].theta = theta
for lyri, lyr in enumerate(nn.layers):
self.layers[lyri].theta = lyr.theta
# print "N",len(self.layers),self.layers[-1].theta[0:3,0:3]
# print "O",len(thetas),thetas[-1][0:3,0:3]
self.fit(X, y,
gtol=gtol, epsilon=epsilon, maxiter=maxiter,
raninit=False, info=info, verbose=verbose,
fit_type='all')
self.nfit += 1
if info:
print("\n")
return xopt
def predict(self, X):
"""
Given a list of samples, predict their class.
One should run nn.fit first to train the neural network.
Args:
X = [nsamples x nproperties]
returns:
y = [nsamples]
"""
if isinstance(X, type([])):
X = np.array(X)
if len(X.shape) == 2:
N = X.shape[0]
else:
N = 1
z, h = self.forward_propagate(X)
#find most-active label
if N == 1:
cls = np.array([h.argmax()])
else:
cls = h.argmax(axis=1)
return cls
def predict_proba(self, X):
"""
Compute the likehoods each possible outcomes of samples in T.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
X : array-like, shape = [n_samples, n_classes]
Returns the probability of the sample for each class in
the model, where classes are ordered by arithmetical
order.
"""
if isinstance(X, type([])):
X = np.array(X)
if len(X.shape) == 2:
N = X.shape[0]
else:
N = 1
z, h = self.forward_propagate(X)
norm = h.sum(axis=1)
for ni, nv in enumerate(norm):
h[ni] = h[ni] / nv
return h
def score_weiwei(self, X, y, verbose=None):
"""
Returns the mean accuracy on the given test data and labels
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training set.
y : array-like, shape = [n_samples]
Labels for X.
Returns
-------
z : float
"""
pred_cls = {}
true_cls = {}
for cls in range(self.ntargets):
pred_cls[cls] = set([])
true_cls[cls] = set([])
for i, s in enumerate(X):
predict = self.predict(s)[0]
true_cls[y[i]].add(i)
pred_cls[y[i]].add(i)
tot_acc = 0.
for k in range(self.ntargets):
hit = pred_cls[k] & true_cls[k]
miss = pred_cls[k] - true_cls[k]
falsepos = true_cls[k] - pred_cls[k]
precision = np.divide(float(len(hit)), len(pred_cls[k]))
recall = np.divide(float(len(hit)), len(true_cls[k]))
accuracy = (np.divide(float(len(hit)), len(true_cls[k])) * 100)
tot_acc += accuracy
if verbose or self.verbose:
print "\nClass %s:" % k
print 'accuracy: ', '%.0f%%' % (np.divide(float(len(hit)),len(true_cls[k])) * 100)
print 'miss: ', '%.0f%%' % (np.divide(float(len(miss)),len(true_cls[k])) * 100)
print 'false positives: ', '%.0f%%' % (np.divide(float(len(falsepos)),len(pred_cls[k]))* 100)
print 'precision: ', '%.0f%%' % (precision* 100)
print 'recall: ', '%.0f%%' % (recall* 100)
z = tot_acc / self.ntargets
return z
def learning_curve(self, X, y,
Xval=None,
yval=None,
gamma=None,
pct=0.6,
plot=False):
"""
returns the training and cross validation set errors
for a learning curve
(good for exploring effect of number of training samples)
Args:
X : training data
y : training value
Xval : test data
yval : test value
gamma : default None uses the objects value,
otherwise gamma=0.
pct (0<pct<1) : split the data as "pct" training, 1-pct testing
only if Xval = None
default pct = 0.6
plot : False/[True] optionally plot the learning curve
Note: if Xval == None, then we assume (X,y) is the entire set of data,
and we split them up using split_data(data,target)
returns three vectors of length(ntrials):
error_train : training error for the N=length(pct*X)
error_val : error on x-val data, when trainined on "i" samples
ntrials
error = cost_Function(lambda=0)
notes:
* a high error indicates lots of bias,
that you are probably underfitting the problem
(so add more neurons/layers, or lower regularization)
* for lots of trials, a high gap between training_error
and test_error (x-val error) indicates lots of variance
(you are over-fitting, so remove some neurons/layers,
or increase the regularization parameter)
"""
if Xval == None:
X, y, Xval, yval = split_data(X, y, pct=pct)
if gamma == None:
gamma = self.gamma
m = X.shape[0]
#need at least one training item...
stepsize = max(m/25,1)
ntrials = range(1,m,stepsize)
mm = len(ntrials)
t_error = np.zeros(mm)
v_error = np.zeros(mm)
for i, v in enumerate(ntrials):
#fit with regularization
self.fit(X[0:v+1], y[0:v+1], gamma=gamma, maxiter=50, raninit=True)
# but compute error without regularization
t_error[i] = self.costFunctionU(X[0:v+1], y[0:v+1], gamma=0.)
# use entire x-val set
v_error[i] = self.costFunctionU(Xval, yval, gamma=0.)
if plot:
plt.plot(ntrials, t_error, 'r+', label='training')
plt.plot(ntrials, v_error, 'bx', label='x-val')
plt.xlabel('training set size')
plt.ylabel('error [J(gamma=0)]')
plt.legend()
plt.show()
return t_error, v_error, ntrials
def validation_curve(self, X, y,
Xval=None,
yval=None,
gammas=None,
pct=0.6,
plot=False):
"""
use a cross-validation set to evaluate various regularization
parameters (gamma)
specifically:
train the NN, then loop over a range of regularization parameters
and select best 'gamma' (=min(costFunction(cross-val data))
Args:
X : training data
y : training value
Xval : test data
yval : test value
pct (0<pct<1) : if Xval=None, split into 'pct' training
"1-pct" testing
gammas : a *list* of regularization values to sample
default None uses
[0., 0.0001, 0.0005, 0.001, 0.05, 0.1, .5, 1, 1.5, 15]
plot : False/[True] optionally plot the validation cure
Note: if Xval == None, then we assume (X,y) is the entire set of data,
and we split them up using split_data(data,target)
Again, we train with regularization, but the erorr
is calculated without
returns:
train_error(gamma), cross_val_error(gamma), gamma, best_gamma
"""
if Xval == None:
X, y, Xval, yval = split_data(X, y, pct)
if gammas == None:
gammas = [0., 0.0001, 0.0005, 0.001, 0.05, 0.1, .5, 1., 1.5, 15.]
train_error = np.zeros(len(gammas))
xval_error = np.zeros(len(gammas))
for gi, gv in enumerate(gammas):
#train with reg.
self.fit(X, y, gamma=gv, maxiter=40, raninit=True)
#evaluate error without reg.
train_error[gi] = self.costFunctionU(X, y, gamma=0.)
xval_error[gi] = self.costFunctionU(Xval, yval, gamma=0.)
if plot:
plt.plot(gammas, train_error, label='Train')
plt.plot(gammas, xval_error, label='Cross Validation')
plt.xlabel('gamma')
plt.ylabel('Error [costFunction]')
plt.legend()
plt.show()
return train_error, xval_error, gammas, gammas[xval_error.argmin()]
def numericalGradients(self, X, y):
"""
numerically estimate the gradients using finite differences
(used to compare to 'gradient' routine)
loop over layers, perturbing each theta-parameter one at a time
* useful for testing gradient routine *
"""
from copy import deepcopy
thetas = self.flatten_thetas()
origthetas = deepcopy(thetas)
numgrad = np.zeros(thetas.size)
perturb = np.zeros(thetas.size)
delta = 1.e-4
for p in range(numgrad.size):
#set the perturbation vector
perturb[p] = delta
loss1 = self.costFunction(thetas - perturb, X, y)
loss2 = self.costFunction(thetas + perturb, X, y)
#calculat the numerical gradient
numgrad[p] = (loss2 - loss1) / (2*delta)
#reset the perturbation
self.unflatten_thetas(origthetas)
perturb[p] = 0
## OLD
# loop over layers, neurons
idx = 0
if 0:
for lv in self.layers:
theta_orig = deepcopy(lv.theta)
# perturb each neuron and calc. grad at that neuron
for pi in range(theta_orig.size): #strip bias
perturb = np.zeros(theta_orig.size)
perturb[pi] = delta
perturb = perturb.reshape(theta_orig.shape)
lv.theta = theta_orig + perturb
loss1 = self.costFunctionU(X, y)
lv.theta = theta_orig - perturb
loss2 = self.costFunctionU(X, y)
numgrad[idx] = (loss2 - loss1) / (2*delta)
idx += 1
lv.theta = theta_orig
return numgrad
def pickle_me(self, filename=''):
"""
dump the important parts of the classifier to a pickled file.
(the theta's and gamma=learning rate)
We name the file based on number of layers,
and shape of layers
args:
filename : base filename, append layer info to this
"""
for li, lv in enumerate(self.layers):
if filename:
filename += '_l%sx%s' % lv.theta.shape
else:
filename += 'l%sx%s' % lv.theta.shape
filename += '.pkl'
#create our pickle
d = {}
d['nlayers'] = len(self.layers)
for li, lv in enumerate(self.layers):
d[li] = lv.theta
d['gamma'] = self.gamma
print "pickling classifier to %s" % filename
cPickle.dump(d, open(filename, 'w'))
def write_thetas(self, basename='layer_'):
"""
Write the theta's to a file in form
basename_%s.npy % layer_number
args
basename : the base filename to write the data to
"""
for li, lv in enumerate(self.layers):
theta = lv.theta
name = "%s_%s.npy" % (basename, li)
print "Saving layer %s to %s " % (li, name)
np.save(name, theta)
def plot_firstlayer(self, imgdim=None,Nsamples=None):
"""
plot the first layer of neurons
Args:
imgdim = array [n, m] of input image dimensions
Nsamples: randomly choose Nsamples-by-Nsamples of neurons
and plot them.
default = None = plot all neurons in first layer
"""
theta = self.layers[0].theta[1:,:] #strip off bias
nimg, nneurons = theta.shape
if imgdim == None:
nx = int(np.sqrt(nimg))
ny = nx
if nx*ny < nimg:
nx += 1
else:
nx, ny = imgdim
if nx*ny != nimg:
#Assume this is a 1-d thingy
# print "image dimensions (%s,%s) don't match actual %s" % (nx,ny,nimg)
nx = nimg
ny = 1
# return
if Nsamples == None:
#plot all of them
Nsamples = int(np.sqrt(nneurons))
if Nsamples*Nsamples < nneurons: