dp.py 32.9 KB
Newer Older
Christian's avatar
Christian committed
1
"""
Klaus Strohmenger's avatar
Klaus Strohmenger committed
2
3
4
5
6
7
8
9
10
11
12
dp library

The dp library is a simple numpy based library with the purpose of teaching about
computational graphs, automatic differentiation, backpropagation, simple neural network and optimizer.
The library allows to build simple computional grahps up to more complex neural networks all based on 
a set of implementet basic matrix operations. It also includes different initializer to set up
the networks and different optimizer to train them. 




13
MIT licence 
Christian's avatar
Christian committed
14

Christian's avatar
Christian committed
15
16
Copyright 2019 Christian Herta

Klaus Strohmenger's avatar
Klaus Strohmenger committed
17
18
19
20
21
Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the “Software”), to deal in the 
Software without restriction, including without limitation the rights to use, copy, 
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Christian's avatar
Christian committed
22

Klaus Strohmenger's avatar
Klaus Strohmenger committed
23
24
The above copyright notice and this permission notice shall be included in all copies 
or substantial portions of the Software.
Christian's avatar
Christian committed
25

Klaus Strohmenger's avatar
Klaus Strohmenger committed
26
27
28
29
30
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Christian's avatar
Christian committed
31
"""
32

Klaus Strohmenger's avatar
Klaus Strohmenger committed
33
34
 

35
36
37
38
39
import numpy as np

import uuid
import numbers
import operator
Klaus Strohmenger's avatar
Klaus Strohmenger committed
40
import copy 
41
42
43
44
45
46
47
48
49
50
51
52
53

from types import SimpleNamespace
from collections import namedtuple


# if there are multiple path to a node
# we must add the grad values 
def combine_dicts(a, b, op=operator.add):
    x = (list(a.items()) + list(b.items()) +
        [(k, op(a[k], b[k])) for k in set(b) & set(a)])
    return {x[i][0]: x[i][1] for i in range(0, len(x))}

class Node(object):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    """
    The Node class represents a single neuron, smallest unit in a computional 
    graph. For the purpose of teaching this libary only works with 2D arrays, matrices
    as neurons.
    
    Each node comprises a name, a value and a gradient function, which is key for 
    the ability of automatic differentiation of this class.
    
    The Node class also contains a set of basic operations for node objects. Each operation leads to a new node with a certain value and gradiant 
    function depending on the nodes given and the type of operation.
    
    The Node class alone can be used to teach and learn about computational graphs and backpropagation.
    
    """
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    
    NodeStore = dict()

    def _set_variables(self, name, value):
        self.value = value
        self.shape = value.shape
        self.dtype = value.dtype
        self.name = name
        self.uuid = uuid.uuid4()
        if name:
            self.grad = lambda g: {name: g}
            self._register()
        else:
            self.grad = lambda g: {}

    def _test_shape(self):
        # only 2D-Arrays are supported at moment
        assert len(self.shape) == 2


    def __init__(self, value, name=None):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
89
90
91
92
93
94
        
        """
        Node object initializer. It will initialize a node object by setting value , name and 
        gradient function and also adjusts the shape to a 2D array if necessary.
        """
        
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
        if isinstance(value, numbers.Number):
            value = np.array([[value]])
        assert isinstance(value, np.ndarray)
        if len(value.shape) == 1:
            value = value.reshape(-1, 1)

        self._set_variables(name, value)
        self._test_shape()

    def _register(self):
        Node.NodeStore[self.name] = self

    @staticmethod
    def get_param():
        param = dict()
        for n in Node.NodeStore:
            param[n] = Node.NodeStore[n].value
        return param

    @staticmethod
    def set_param(param):
        for n in Node.NodeStore:
            Node.NodeStore[n].value = param[n]
        
    def _broadcast_g_helper(o, o_):# broadcasting make things slightly more complicated
        if o_.shape[0] > o.shape[0]:
            o_ = o_.sum(axis=0).reshape(1,-1)
        if o_.shape[1] > o.shape[1]:
            o_ = o_.sum(axis=1).reshape(-1,1)
        return o_    
                  
    def _set_grad(self_, g_total_self, other, g_total_other):
        g_total_self = Node._broadcast_g_helper(self_, g_total_self)
        x = self_.grad(g_total_self)
        g_total_other = Node._broadcast_g_helper(other, g_total_other)
        x = combine_dicts(x, other.grad(g_total_other))
        return x
                
    def __add__(self, other):
        if isinstance(other, numbers.Number):
            other = Node(np.array([[other]]))
        ret = Node(self.value + other.value)
        def grad(g):
            g_total_self = g
            g_total_other = g
            x = Node._set_grad(self, g_total_self, other, g_total_other)
            return x
        ret.grad = grad
        return ret
    
    def __radd__(self, other):
        return Node(other) + self
    
    def __sub__(self, other):
        if isinstance(other, numbers.Number):
            other = Node(other)
        ret = self + (other * -1.)   
        return ret
    
    def __rsub__(self, other):
        if isinstance(other, numbers.Number):
            other = Node(other) 
            return other - self
        raise NotImplementedError()
        
    def __mul__(self, other):
        if isinstance(other, numbers.Number) or isinstance(other, np.ndarray):
            other = Node(other)           
        ret = Node(self.value * other.value) 
        def grad(g):
            g_total_self = g * other.value
            g_total_other = g * self.value
            x = Node._set_grad(self, g_total_self, other, g_total_other)
            return x
        ret.grad = grad
        return ret      
    
    def __rmul__(self, other):
        if isinstance(other, numbers.Number):
            return Node(other) * self
        raise NotImplementedError()

    def concatenate(self, other, axis=0):
        assert axis in (0,1) # TODO
        ret = Node(np.concatenate((self.value, other.value), axis=axis))
        def grad(g):
            if axis == 0: 
                g_total_self = g[:self.shape[0]] 
                g_total_other = g[self.shape[0]:]
            elif axis == 1:
                g_total_self = g[:, :self.shape[1]] 
                g_total_other = g[:, self.shape[1]:]
            x = Node._set_grad(self, g_total_self, other, g_total_other)
            return x
        ret.grad = grad
        return ret
    
    # slicing
    def __getitem__(self, val):
         raise NotImplementedError()

        
    def __truediv__(self, other):
        if isinstance(other, numbers.Number):
            other = Node(np.array([[other]]))
        ret = Node(self.value / other.value)

        def grad(g):
            g_total_self = g / other.value
            g_total_other = -1. * self.value * g / (other.value**2)
            x = Node._set_grad(self, g_total_self, other, g_total_other)
            return x
        ret.grad = grad
        return ret
    
    def __rtruediv__(self, other):
        if isinstance(other, numbers.Number):
            other = Node(other)
            return other/self
        raise NotImplementedError()
        
    def __neg__(self):
        return self * -1.
    
    def dot(self, other):
        ret = Node(np.dot(self.value, other.value))    
        def grad(g):
            g_total_self = np.dot(g, other.value.T)
            g_total_other = np.dot(self.value.T, g)
            x = Node._set_grad(self, g_total_self, other, g_total_other)
            return x
        ret.grad = grad
        return ret
    
    def transpose(self):
        ret = Node(self.value.T)
        def grad(g):
            x = self.grad(g.T)
            return x
        ret.grad = grad
        return ret    

    T = transpose

    def exp(self):
        ret = Node(np.exp(self.value))
        def grad(g):
            assert self.shape == g.shape
            x = self.grad(np.exp(self.value) * g)
            return x
        ret.grad = grad
        return ret    
    
    def log(self):
        ret = Node(np.log(self.value))
        def grad(g):
            assert self.shape == g.shape
            x = self.grad(1./self.value * g)
            return x
        ret.grad = grad
        return ret     
       
    def square(self):
        ret = Node(np.square(self.value))
        def grad(g):
            assert self.shape == g.shape
            x = self.grad(2 * self.value * g)
            return x
        ret.grad = grad
        return ret       
         
    def sqrt(self):
        ret = Node(np.sqrt(self.value))
        def grad(g):
            assert self.shape == g.shape
            x = self.grad(0.5 * (1/np.sqrt(self.value)) * g)
            return x
        ret.grad = grad
        return ret     
274
275
276
277
278
279
280
281
282
283
    
    def tanh(self):
        ret = Node(np.tanh(self.value))
        def grad(g):
            assert self.shape == g.shape
            x = self.grad((1 - np.square(np.tanh(self.value))) * g)
            return x
        ret.grad = grad
        return ret
    
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
    def sum(self, axis=None):
        if axis is None:
            return self._sum_all()
        assert axis in (0,1)
        return self._sum(axis)
        
    def _sum_all(self):
        ret = Node(np.sum(self.value).reshape(1,1))
        def grad(g):
            x = self.grad(np.ones_like(self.value) * g)
            return x
        ret.grad = grad
        return ret
    
    def _sum(self, axis):
        ret = self.value.sum(axis=axis)
        if axis==0: 
            ret = ret.reshape(1, -1)
        else:
            ret = ret.reshape(-1, 1)
        ret = Node(ret)
        def grad(g):
            x = self.grad(np.ones_like(self.value) * g)
            return x
        ret.grad = grad
        return ret  
    
    def relu(self):
        self.mask = self.value > 0.
        ret = Node(self.mask * self.value)
        def grad(g):
            assert self.shape == g.shape
            x = self.grad(self.mask * g)
            return x
        ret.grad = grad
        return ret    
    
Klaus Strohmenger's avatar
Klaus Strohmenger committed
321
322
323
324
325
326
327
328
329
330
    def leaky_relu(self, slope = 0.01):
        self.mask = self.value>0.
        ret = Node(self.mask*self.value + slope*(self.value - self.value*self.mask))
        def grad(g):
            assert self.shape == g.shape
            x = self.grad(self.mask * g + (slope*(g - self.mask*g )))
            return x
        ret.grad = grad
        return ret
    
331
332
333
334
335
    def softmax(self):
        ret = self.exp() / self.exp().sum(axis=1)
        np.testing.assert_almost_equal(ret.value.sum(axis=1), 1.)
        return ret
    
Klaus Strohmenger's avatar
Klaus Strohmenger committed
336
337
    def sigmoid(self):# bug
        return 1./(1. + self.__neg__().exp())
338
339
340
341
342
343
344
345
346
347

    def reshape(self, shape):
        ret = Node(self.value.reshape(shape))
        def grad(g):
            x = self.grad(g.reshape(self.shape))
            return x
        ret.grad = grad
        return ret

class NeuralNode(object):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
348
349
350
351
352
353
354
    """
    The NeuralNode class initializes a set of parameters (Node objects) which represent  
    a layer in the neural network. Basically the class initializes weights W and biases b
    which are the building blocks for a linear transformation via Wx+b in the provided linear layer. 
    For the initialisation the class provides a ....  Xavier and pure uniform initialisation.
    
    """
355
356
357
358
359
360
361
362
363
364
365
366
     
    _sep = "_"
    #param = dict()
    #def register():
    #    NeuralNode.param = Node.get_param()

    @staticmethod
    def _get_fullname(name, suffix):
        return NeuralNode._sep.join([name, suffix])

    @staticmethod
    def _initialize_W(fan_in, fan_out):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
367
368
369
370
371
372
373
374
375
376
377
        """
        This function performs a default initialisation for the weights.
        
        Args: 
            fan_in:     number of layer inputs
            fan_out:    number of layer outputs
            
        Returns:
            initial_W:  initial weights         
        """
        
378
379
380
        gain = np.sqrt(2)
        std = gain / np.sqrt(fan_in)
        bound = np.sqrt(3) * std 
Klaus Strohmenger's avatar
Klaus Strohmenger committed
381
382
        initial_W = np.random.uniform(-bound, bound, size=(fan_in, fan_out))
        return initial_W
383
384
385

    @staticmethod
    def _initialize_b(fan_in, fan_out):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
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
        """
        This function performs a default initialisation for the diases.
        
        Args: 
            fan_in:     number of layer inputs
            fan_out:    number of layer outputs
            
        Returns:
            initial_b:  initial weights         
        """
        bound = 1 / np.sqrt(fan_in)
        initial_b = np.random.uniform(-bound, bound, size=(1, fan_out))  
        return initial_b
    
    # --------------------------- Other initialization methods -------------------
    @staticmethod
    def Xavier(fan_in, fan_out):
        """
        This function performs a Xavier initialisation for the weights and biases.
        
        Args: 
            fan_in:     number of layer inputs
            fan_out:    number of layer outputs
            
        Returns:
            initial_W:  initial weights 
            initial_b:  initial biases 
        """
        
        gain=np.sqrt(2)
        bound = gain * np.sqrt(6/(fan_in+fan_out))
        inital_W = np.random.uniform(-bound, bound, size=(fan_in, fan_out))     
418
        bound = 1 / np.sqrt(fan_in)
Klaus Strohmenger's avatar
Klaus Strohmenger committed
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
        inital_b = np.random.uniform(-bound, bound, size=(1, fan_out))
         
        return inital_W, inital_b
    
    
    @staticmethod
    def NormalInitializer(fan_in, fan_out):
        """
        This function performs a normal value initialisation for the weights and biases.
        Drawn from a uniform distribution. 
        
        Args: 
            fan_in:     number of layer inputs
            fan_out:    number of layer outputs
            
        Returns:
            initial_W:  initial weights 
            initial_b:  initial biases 
        """
        
        bound = 1/np.sqrt(fan_in)
        inital_W = np.random.uniform(-bound, bound, size=(fan_in, fan_out))
        inital_b = np.random.uniform(-bound, bound, size=(1, fan_out))
         
        return inital_W, inital_b
    

    
    # ------------------------------------------------------------------------
448
449
450
451
452
453
454

    @staticmethod
    def get_name_and_set_param(param, layer_name, ext_name):
        node_name = NeuralNode._get_fullname(layer_name, ext_name)
        node_value = param.get(node_name)
        return node_name, node_value

Klaus Strohmenger's avatar
Klaus Strohmenger committed
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
    
    def _Linear_Layer(fan_in, fan_out, name=None, param=dict(), initializer=None):
        """
        This functions initialises weights and biases and performs an affine transformation 
        on the input. Represents a pure linear layer in a neural network.
        
        Args:
            fan_in:         number of layer inputs
            fan_out:        number of layer outputs
            initializer:    initializer used for the initialization of weights and biases
        
        Kwargs:
            name:           name of the layer, used for the parameter dictionary
            param:          parameter dictionary, includes all weights and biases 
        
        Returns:
            lambda X:       function representing the affine transformation
            param:          dictionary consisting of all parameters in the neural net
            nodes:          dictionary consisting of all weight and biases for this specific linear layer
        
        """
        
477
478
479
480
481
482
        assert isinstance(name, str) 
        weight_name, W_value = NeuralNode.get_name_and_set_param(param, name, "weight")
        bias_name, b_value = NeuralNode.get_name_and_set_param(param, name, "bias")
        
        assert (W_value is None and b_value is None) or (W_value is not None and b_value is not None)
        if W_value is None:
Klaus Strohmenger's avatar
Klaus Strohmenger committed
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
           
            if initializer is None:
                W_value = NeuralNode._initialize_W(fan_in, fan_out)
                b_value = NeuralNode._initialize_b(fan_in, fan_out)
            
            if initializer == "Xavier":
                W_value, b_value = NeuralNode.Xavier(fan_in, fan_out)
                
            if initializer == "NormalInitializer":
                W_value, b_value = NeuralNode.NormalInitializer(fan_in,fan_out)
                
            # fall-through
            if W_value is None and b_value is None:
                print("WARNING: Unrecognized initializer '{}'. Using 'Xavier' instead.".format(initializer))
                W_value, b_value = NeuralNode.Xavier(fan_in, fan_out)

499
500
501
502
503
504
505
506
507
508
            param[weight_name] = W_value
            param[bias_name] = b_value
            
        W = Node(W_value, weight_name)
        b = Node(b_value, bias_name)
        nodes = dict()  # type: Dict[str, Node]
        nodes[weight_name] = W
        nodes[bias_name] = b
        return lambda X: (X.dot(W) + b), param, nodes
    
Klaus Strohmenger's avatar
Klaus Strohmenger committed
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
    def _ReLu_Layer(fan_in, fan_out, name=None, param=dict(), initializer=None):
        """
        This functions builds a Relu layer for a neural network by setting up an linar layer and
        connecting it with a relu function.
        
        Args:
            fan_in:         number of layer inputs
            fan_out:        number of layer outputs
            initializer:    initializer used for the initialization of weights and biases
        
        Kwargs:
            name:           name of the layer, used for the parameter dictionary
            param:          parameter dictionary, includes all weights and biases 
        
        Returns:
            f:              function representing the affine transformation connected with a relu function
            param:          dictionary consisting of all parameters in the neural net
            nodes:          dictionary consisting of all weight and biases for this specific linear layer
        
        """
        
530
531
532
533
534
535
536
537
538
        ll, param, nodes = NeuralNode._Linear_Layer(fan_in, fan_out, name, param)
        f = lambda X: ll(X).relu()
        return f, param, nodes

# short namespace name        
nn = NeuralNode 


class Model(object):  
Klaus Strohmenger's avatar
Klaus Strohmenger committed
539
540
541
542
        """
        Model is the parent class for designing our neural net.
        
        """
543
544
545
546
547
548
549
550
        # nodes are neural nodes
        _NNode = namedtuple("NNode", ['layer_type', 'param', 'nodes'])  # type: Type[NNode]
        
        def __init__(self):
            self.neural_nodes = dict()
            
        # params are not structured in nodes
        def get_param(self):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
551
552
553
554
555
556
            """
            Retruns a dictionary of all parameters (weights and bias) used in the network.
            
            Returns:
                A dictionary
            """
557
558
559
560
561
            param = dict()
            for node_name, node_value in self.neural_nodes.items():
                param = {**param, **node_value.param} # merge dicts
            return param
        
Klaus Strohmenger's avatar
Klaus Strohmenger committed
562
       
563
        def set_param(self, param):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
564
565
566
567
568
569
570
571
572
            """
            Sets the values of parameters used in the neural network. New values are given by 
            the param dictinary.
            
            Args:
                param:    dictionary, contains new parameter values
            
        
            """
573
574
575
576
577
            for node_name, node_value in self.neural_nodes.items():
                for param_name in node_value.param:
                    node_value.param[param_name] = param[param_name]
            
        def get_grad(self, x, y):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
578
579
580
581
582
583
584
585
586
587
588
            """
            Calculates and returns the current gradient and value of the loss function .
            
            Args:
                x:    x training data (features)
                y:    y data (prediction) 
                    
            Returns:
                loss_grad(g):   current model gradient
                loss_:          current loss value
            """
589
590
591
592
593
            loss_ = self.loss(x, y)
            g = np.ones_like(loss_.value)
            return loss_.grad(g), loss_
        
        
Klaus Strohmenger's avatar
Klaus Strohmenger committed
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
        def _set_layer(self, fan_in, fan_out, name, layer_type, initializer=None):
            """
            Adds a layer to the neural network.
            
            Args:
                fan_in:         number of layer inputs
                fan_out:        number of layer outputs
                name:           String, name of the layer
                layer_type:     layer type defined in the NeuralNode class
                 
            Kwargs:
                initializer:    initializer used for the initialization of weights and biases
            
            Returns:
                lambda x: f(x)         function represented by the layer
            """
610
611
            assert isinstance(name, str)
            assert name not in self.neural_nodes.keys()
Klaus Strohmenger's avatar
Klaus Strohmenger committed
612
            f, param, nodes = layer_type(fan_in, fan_out, name=name, initializer=initializer, param=dict())
613
614
615
            self.neural_nodes[name] = Model._NNode(layer_type=layer_type, param=param, nodes=nodes)
            return lambda x: f(x)

Klaus Strohmenger's avatar
Klaus Strohmenger committed
616
617
618
619
620
        def ReLu_Layer(self, fan_in, fan_out, name=None, initializer=None):
            """
            Adds a Relu layer to the neural network.
            """
            return self._set_layer(fan_in, fan_out, name, NeuralNode._ReLu_Layer, initializer)
621
        
Klaus Strohmenger's avatar
Klaus Strohmenger committed
622
623
624
625
626
627
        def Linear_Layer(self, fan_in, fan_out, name=None, initializer=None ):
            """
            Adds a Linear layer to the neural network.
            """
            return self._set_layer(fan_in, fan_out, name, NeuralNode._Linear_Layer, initializer)
    
628
629
630
631
632
633
634
635
636
        
        def _add_to_params(self, p):
            assert p.keys().isdisjoint(self.params.keys())
            self.param = {**self.param, **p} # merge dicts
 
        # following methods     
        # must be implemented by subclasses
        
        def forward(self, x):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
637
638
639
640
            """
            Has to be implemented when setting up the neural network. Calculates the forward pass
            defined by the neural network.
            """
641
642
643
            raise NotImplementedError()
    
        def loss(self, x, y):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
644
645
646
647
            """
            Loss function which should be optimized by the neural network.
            Has to be implemented when setting up the neural network. 
            """
648
            raise NotImplementedError()
649
650
651
652
653
654
655
656
657
658
659
            
        # example: cross entropy 
        # y should be one hot encoded
        #def loss(self, x, y=None):
        #    n = x.shape[0]
        #    logits = self.logits(x) # has be be defined
        #    # numeric stable max sum exponent   
        #    max_logit = Node(np.max(logits.value, axis=1))
        #    log_softmax = logits - max_logit - (logits - max_logit).exp().sum(axis=1).log()
        #    loss = - y * log_softmax
        #    return loss.sum()/n
660
661
662
663
664

##################################################################################################


class Optimizer(object):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
665
666
667
668
    """
    The class Optimizer works as a parent class for all specialized types of Optimizers 
    and provides the basic methods for training the network using an optimizer.
    """
669
670
    
    def __init__(self, model, x_train=None, y_train=None, hyperparam=dict(), batch_size=128):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
671
672
673
674
675
676
677
678
679
680
681
682
683
        """
        Initializes an optimizer.
        
        Args:
            model:          neural network which should be optimized
           
        Kwargs:
            x_train:        training data, features
            y_train:        training data
            hyperparam:     dictionary of hyperparameters used be the optimizer
            batch_size:     batch size for neural network training
            
        """
684
685
686
687
688
689
        self.model = model
        self.x_train = x_train
        self.y_train = y_train
        self.batch_size=batch_size
        self.hyperparam = hyperparam
        self._set_param()
Klaus Strohmenger's avatar
Klaus Strohmenger committed
690
691
692
        self.grad_stores = []  # list of dicts for momentum, etc. 
        self.loss_hist = []    # list for the documentation of loss history
        self.para_hist = []    # list for the documentation of parameter/network development
693
694
        
    def random_batch(self):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
695
696
697
698
699
700
701
        """
        Samples a random batch from the given training data.
        
        Returns:
            Random training batch
            
        """
702
703
704
705
706
707
708
        n = self.x_train.shape[0]
        indices = np.random.randint(0, n, size=self.batch_size)
        return Node(self.x_train[indices]), Node(self.y_train[indices])

    def train(self, steps=1000, print_each=100):
        raise NotImplementedError()

Klaus Strohmenger's avatar
Klaus Strohmenger committed
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
    def _train(self, steps=1000, num_grad_stores=0, print_each=100,hist=False):
        """
        This function performs the training loop, which optimizes the paramters of the 
        model.
        
        Kwargs:
            steps:              number of epochs
            num_grad_stores:    number of gradients stored for momentum approaches
            print_each:         number of epochs after which the lost is printed
            hist:               bool, for TRUE parameter and loss history are returned
            
        Returns:
            if hist=True:
                loss.value:     loss function value from last step
                loss_hist:      loss function value history from training
                para_hist:      history of model parameter development

        """
727
728
729
730
731
        assert num_grad_stores in (0,1,2)
        model = self.model
        if num_grad_stores>0:
            x, y = self.random_batch()
            grad, loss = model.get_grad(x, y)
Klaus Strohmenger's avatar
Klaus Strohmenger committed
732
            self.grad_stores = [dict() for _ in range(num_grad_stores)]
733
734
735
736
737
        for grad_store in self.grad_stores:
            for g in grad:
                grad_store[g] = np.zeros_like(grad[g])
                
        param = model.get_param()
Klaus Strohmenger's avatar
Klaus Strohmenger committed
738
        
739
740
741
742
        print("iteration\tloss")    
        for i in range(1, steps+1):
            x, y = self.random_batch()
            grad, loss = model.get_grad(x, y)
Klaus Strohmenger's avatar
Klaus Strohmenger committed
743
744
745
746
747
748
  
            self.loss_hist.append(loss.value[0,0])
            
            para_item = model.get_param()
            self.para_hist.append(copy.deepcopy(para_item))
            
749
            if i%print_each==0 or i==1:
Klaus Strohmenger's avatar
Klaus Strohmenger committed
750
751
                print(i, "\t",loss.value[0,0])   
                #print(para_item)
752
753
754
755
756
757
758
759
                
            for g in grad:
                #assert param[g].shape == self.grad_stores[0][g].shape
                #param[g] =
                self._update(param, grad, g, i)
            
            model.set_param(param)
        
Klaus Strohmenger's avatar
Klaus Strohmenger committed
760
761
762
763
764
765
        if hist==True:
            print('wiht hist')
            return loss.value, self.loss_hist, self.para_hist
        
        if hist==False:
            return loss.value
766
767
768
769
770




class SGD(Optimizer):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
771
772
773
    """
    This class sets up a simple Stochastic Gradient Descent optimizer.
    """
774
775
    
    def __init__(self, model, x_train=None, y_train=None, hyperparam=dict(), batch_size=128):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
776
        super(SGD, self).__init__(model, x_train, y_train, hyperparam, batch_size)
777
778
        
    def _set_param(self):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
779
780
781
782
        """
        Sets the hyperparameters used by this optimizer.
        """
        ## Learning rate 
783
        self.alpha = self.hyperparam.get("alpha", 0.001)
Klaus Strohmenger's avatar
Klaus Strohmenger committed
784
        
785
786

    def _update(self, param, grad, g, i):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
787
788
789
790
791
792
793
794
795
        """
        Update rule for a simple Stochastic Gradient Descent (SGD) training.
        
        Args:
            param:       dictionary containing the model parameters
            grad:        dictionary containing the gradients of model parameters
            g:           name of actual parameter to optimize
            i:           actual traning epoch
        """
796
797
        param[g] -= self.alpha * grad[g]    
             
Klaus Strohmenger's avatar
Klaus Strohmenger committed
798
799
800
801
802
803
    def train(self, steps=1000, print_each=100,err_hist=False):
        """
        Starts the training using the method Optimizer._train and the update rule defined 
        in SGD._update.
        """
        return self._train(steps, num_grad_stores=1, print_each=print_each,hist=err_hist)
804
805
806
807
808

optimizer = SimpleNamespace()
optimizer.SGD = SGD
     
class SGD_Momentum(Optimizer):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
809
810
811
812
    """
    This class sets up a Stochastic Gradient Descent optimizer with momentum.
    """
    
813
814
    
    def __init__(self, model, x_train=None, y_train=None, hyperparam=dict(), batch_size=128):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
815
        super(SGD_Momentum, self).__init__(model, x_train, y_train, hyperparam, batch_size)
816
817
        
    def _set_param(self):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
818
819
820
821
        """
        Sets the hyperparameters used by this optimizer.
        """
        ## Learning rate
822
        self.alpha = self.hyperparam.get("alpha", 0.001)
Klaus Strohmenger's avatar
Klaus Strohmenger committed
823
        ## beta for momentum term 
824
825
826
        self.beta = self.hyperparam.get("beta", 0.9) 
    
    def _update(self, param, grad, g, i):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
827
828
829
830
831
832
833
834
835
836
837
        """
        Update rule for a Stochastic Gradient Descent with momentum training.
        
        Args:
            param:       dictionary containing the model parameters
            grad:        dictionary containing the gradients of model parameters
            g:           name of actual parameter to optimize
            i:           actual traning epoch
            
        """
        
838
839
840
841
842
843
        gradients = self.grad_stores[0]
        gradients[g] = self.beta * gradients[g] + (1-self.beta) * grad[g]
        #gradients[g] /= (1. - self.beta**i) # bias correction
        param[g] -= self.alpha * gradients[g]    
        #return param[g]
    
Klaus Strohmenger's avatar
Klaus Strohmenger committed
844
845
846
847
848
849
    def train(self, steps=1000, print_each=100,err_hist=False):
        """
        Starts the training using the method Optimizer._train and the update rule defined 
        in SGD_Momentum._update.
        """
        return self._train(steps, num_grad_stores=1, print_each=print_each,hist=err_hist)
850
851
852
853
854
    

optimizer.SGD_Momentum = SGD_Momentum

class RMS_Prop(Optimizer):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
855
856
857
    """
    This class sets up a RMSProp (Root Mean Square Propagation) optimizer .
    """
858
859
    
    def __init__(self, model, x_train=None, y_train=None, hyperparam=dict(), batch_size=128):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
860
        super(RMS_Prop, self).__init__(model, x_train, y_train, hyperparam, batch_size)
861
862
    
    def _set_param(self):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
863
864
865
        """
        Sets the hyperparameters used by this optimizer.
        """
866
867
868
869
870
        self.alpha = self.hyperparam.get("alpha", 0.001)
        self.beta2 = self.hyperparam.get("beta2", 0.99) 
        self.epsilon = self.hyperparam.get("epsilon", 10e-8) 
    
    def _update(self, param, grad, g, i):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
871
872
873
874
875
876
877
878
879
880
        """
        Update rule for a RMSProp training.
        
        Args:
            param:       dictionary containing the model parameters
            grad:        dictionary containing the gradients of model parameters
            g:           name of actual parameter to optimize
            i:           actual traning epoch
            
        """
881
882
        squared_gradients = self.grad_stores[0]
        squared_gradients[g] = self.beta2 * squared_gradients[g] + (1-self.beta2) * (grad[g])**2
Klaus Strohmenger's avatar
Klaus Strohmenger committed
883
884
        squared_gradient_corrected = squared_gradients[g]/(1. - self.beta2**i) # bias correction
        param[g] -= self.alpha * grad[g]/np.sqrt(squared_gradient_corrected+self.epsilon)   
885
886
        #return param[g]
    
Klaus Strohmenger's avatar
Klaus Strohmenger committed
887
888
889
890
891
892
    def train(self, steps=1000, print_each=100,err_hist=False):
        """
        Starts the training using the method Optimizer._train and the update rule defined 
        in RMS_Prop._update.
        """
        return self._train(steps, num_grad_stores=1, print_each=print_each,hist=err_hist)
893
894
895
896
897
898

optimizer.RMS_Prop = RMS_Prop

class Adam(Optimizer):
    
    def __init__(self, model, x_train=None, y_train=None, hyperparam=dict(), batch_size=128):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
899
        super(Adam, self).__init__(model, x_train, y_train, hyperparam, batch_size)
900
901
    
    def _set_param(self):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
902
903
904
        """
        Sets the hyperparameters used by this optimizer.
        """
905
        self.alpha = self.hyperparam.get("alpha", 0.001)
Klaus Strohmenger's avatar
Klaus Strohmenger committed
906
907
908
        self.beta = self.hyperparam.get("beta", 0.9) 
        self.beta2 = self.hyperparam.get("beta2", 0.99)
        self.epsilon = self.hyperparam.get("epsilon", 10e-8)
909
910
    
    def _update(self, param, grad, g, i):
Klaus Strohmenger's avatar
Klaus Strohmenger committed
911
912
        """
        Update rule for an Adam training.
913
        
Klaus Strohmenger's avatar
Klaus Strohmenger committed
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
        Args:
            param:       dictionary containing the model parameters
            grad:        dictionary containing the gradients of model parameters
            g:           name of actual parameter to optimize
            i:           actual traning epoch
            
        """
        velocity = self.grad_stores[0]
        squared_grads = self.grad_stores[1]
        
        # update velocity
        v = self.beta * velocity[g] + (1 - self.beta) * grad[g]
        np.copyto(velocity[g], v)
        
        # update squared grads
        sq = self.beta2 * squared_grads[g] + (1 - self.beta2) * np.square(grad[g])
        np.copyto(squared_grads[g], sq)
        
        # bias correction
        v_corrected = v/(1 - self.beta**i)
        sq_corrected = sq/(1 - self.beta2**i)
        
        # update network
        update = param[g] - self.alpha * (v_corrected/np.sqrt(sq_corrected + self.epsilon))
        np.copyto(param[g], update)
939
    
Klaus Strohmenger's avatar
Klaus Strohmenger committed
940
941
942
943
944
945
    def train(self, steps=1000, print_each=100,err_hist=False):
        """
        Starts the training using the method Optimizer._train and the update rule defined 
        in Adam._update.
        """
        return self._train(steps, num_grad_stores=2, print_each=print_each,hist=err_hist)
946
947

# not tested right now
Klaus Strohmenger's avatar
Klaus Strohmenger committed
948
optimizer.Adam = Adam
Klaus Strohmenger's avatar
Klaus Strohmenger committed
949
950
951
952
953
954
955
956
957
958
959

#####################################################################################################

class Helper():

    @staticmethod
    def one_hot_encoding(y, nb_classes):
        m = y.shape[0]
        y_ = np.zeros((m, nb_classes), dtype=int)
        y_[np.arange(m), y.astype(int)] = 1
        return y_