|
| 1 | +import numpy as np |
| 2 | +from layers import * |
| 3 | + |
| 4 | + |
| 5 | +class FullyConnectedNet(object): |
| 6 | + """ |
| 7 | + A fully-connected neural network with an arbitrary number of hidden layers, |
| 8 | + ReLU nonlinearities, and a softmax loss function. This will also implement |
| 9 | + dropout and batch normalization as options. For a network with L layers, |
| 10 | + the architecture will be |
| 11 | +
|
| 12 | + {affine - [batch norm] - relu - [dropout]} x (L - 1) - affine - softmax |
| 13 | +
|
| 14 | + where batch normalization and dropout are optional, and the {...} block is |
| 15 | + repeated L - 1 times. |
| 16 | +
|
| 17 | + Similar to the TwoLayerNet above, learn-able parameters are stored in the |
| 18 | + self.params dictionary and will be learned using the Solver class. |
| 19 | + """ |
| 20 | + |
| 21 | + def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10, |
| 22 | + dropout=0, use_batchnorm=False, reg=0.0, |
| 23 | + weight_scale=1e-2, dtype=np.float32, seed=None): |
| 24 | + """ |
| 25 | + Initialize a new FullyConnectedNet. |
| 26 | +
|
| 27 | + Inputs: |
| 28 | + - hidden_dims: A list of integers giving the size of each hidden layer. |
| 29 | + - input_dim: An integer giving the size of the input. |
| 30 | + - num_classes: An integer giving the number of classes to classify. |
| 31 | + - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then |
| 32 | + the network should not use dropout at all. |
| 33 | + - use_batchnorm: Whether or not the network should use batch normalization. |
| 34 | + - reg: Scalar giving L2 regularization strength. |
| 35 | + - weight_scale: Scalar giving the standard deviation for random |
| 36 | + initialization of the weights. |
| 37 | + - dtype: A numpy data-type object; all computations will be performed using |
| 38 | + this data-type. float32 is faster but less accurate, so you should use |
| 39 | + float64 for numeric gradient checking. |
| 40 | + - seed: If not None, then pass this random seed to the dropout layers. This |
| 41 | + will make the dropout layers deterministic so we can gradient check the |
| 42 | + model. |
| 43 | + """ |
| 44 | + self.use_batchnorm = use_batchnorm |
| 45 | + self.use_dropout = dropout > 0 |
| 46 | + self.reg = reg |
| 47 | + self.num_layers = 1 + len(hidden_dims) |
| 48 | + self.dtype = dtype |
| 49 | + self.params = {} |
| 50 | + |
| 51 | + dims = [input_dim] + hidden_dims + [num_classes] |
| 52 | + for i in range(1, self.num_layers + 1): |
| 53 | + self.params['W%d' %i] = weight_scale * np.random.randn(dims[i - 1], dims[i]) |
| 54 | + self.params['b%d' %i] = np.zeros(dims[i]) |
| 55 | + if i < self.num_layers and self.use_batchnorm: |
| 56 | + self.params['gamma%d' %i] = np.ones(dims[i]) |
| 57 | + self.params['beta%d' %i] = np.zeros(dims[i]) |
| 58 | + |
| 59 | + # When using dropout we need to pass a dropout_param dictionary to each |
| 60 | + # dropout layer so that the layer knows the dropout probability and the mode |
| 61 | + # (train / test). You can pass the same dropout_param to each dropout layer. |
| 62 | + self.dropout_param = {} |
| 63 | + if self.use_dropout: |
| 64 | + self.dropout_param = {'mode': 'train', 'p': dropout} |
| 65 | + if seed is not None: |
| 66 | + self.dropout_param['seed'] = seed |
| 67 | + |
| 68 | + # With batch normalization we need to keep track of running means and |
| 69 | + # variances, so we need to pass a special bn_param object to each batch |
| 70 | + # normalization layer. You should pass self.bn_params[0] to the forward pass |
| 71 | + # of the first batch normalization layer, self.bn_params[1] to the forward |
| 72 | + # pass of the second batch normalization layer, etc. |
| 73 | + self.bn_params = [] |
| 74 | + if self.use_batchnorm: |
| 75 | + self.bn_params = [{'mode': 'train'} for i in range(self.num_layers - 1)] |
| 76 | + |
| 77 | + # Cast all parameters to the correct data-type |
| 78 | + for k, v in self.params.items(): |
| 79 | + self.params[k] = v.astype(dtype) |
| 80 | + |
| 81 | + def loss(self, X, y=None): |
| 82 | + """ |
| 83 | + Compute loss and gradient for the fully-connected net. |
| 84 | +
|
| 85 | + Input / output: Same as TwoLayerNet above. |
| 86 | + """ |
| 87 | + X = X.astype(self.dtype) |
| 88 | + mode = 'test' if y is None else 'train' |
| 89 | + |
| 90 | + # Set train/test mode for batchnorm params and dropout param since they |
| 91 | + # behave differently during training and testing. |
| 92 | + if self.use_dropout: |
| 93 | + self.dropout_param['mode'] = mode |
| 94 | + if self.use_batchnorm: |
| 95 | + for bn_param in self.bn_params: |
| 96 | + bn_param['mode'] = mode |
| 97 | + |
| 98 | + scores = None |
| 99 | + |
| 100 | + cache = {} |
| 101 | + a_cache, relu_cache, bn_cache, d_cache = {}, {}, {}, {} |
| 102 | + h = X |
| 103 | + for i in range(1, self.num_layers + 1): |
| 104 | + W, b = self.params['W%d' % i], self.params['b%d' % i] |
| 105 | + if i < self.num_layers: |
| 106 | + if self.use_batchnorm: |
| 107 | + gamma, beta = self.params['gamma%d' % i], self.params['beta%d' % i] |
| 108 | + h, a_cache[i] = affine_forward(h, W, b) |
| 109 | + h, bn_cache[i] = batchnorm_forward(h, gamma, beta, self.bn_params[i - 1]) |
| 110 | + h, relu_cache[i] = relu_forward(h) |
| 111 | + else: |
| 112 | + h, cache[i] = affine_relu_forward(h, W, b) |
| 113 | + if self.use_dropout: |
| 114 | + h, d_cache[i] = dropout_forward(h, self.dropout_param) |
| 115 | + else: |
| 116 | + scores, cache[i] = affine_forward(h, W, b) |
| 117 | + |
| 118 | + # If test mode return early |
| 119 | + if mode == 'test': |
| 120 | + return scores |
| 121 | + |
| 122 | + loss, grads = 0.0, {} |
| 123 | + |
| 124 | + loss, dscores = softmax_loss(scores, y) |
| 125 | + |
| 126 | + # backward pass |
| 127 | + dout = dscores |
| 128 | + for i in reversed(range(1, self.num_layers + 1)): |
| 129 | + if i < self.num_layers: |
| 130 | + if self.use_dropout: |
| 131 | + dout = dropout_backward(dout, d_cache[i]) |
| 132 | + if self.use_batchnorm: |
| 133 | + dout = relu_backward(dout, relu_cache[i]) |
| 134 | + dout, grads['gamma%d' % i], grads['beta%d' % i] = batchnorm_backward(dout, bn_cache[i]) |
| 135 | + dout, grads['W%d' % i], grads['b%d' % i] = affine_backward(dout, a_cache[i]) |
| 136 | + else: |
| 137 | + dout, grads['W%d' % i], grads['b%d' % i] = affine_relu_backward(dout, cache[i]) |
| 138 | + else: |
| 139 | + dout, grads['W%d' % i], grads['b%d' %i] = affine_backward(dout, cache[i]) |
| 140 | + |
| 141 | + for i in range(1, self.num_layers): |
| 142 | + W = self.params['W%d' % i] |
| 143 | + loss += 0.5 * self.reg * np.sum(W * W) |
| 144 | + grads['W%d' % i] += self.reg * W |
| 145 | + |
| 146 | + return loss, grads |
0 commit comments