russellwang710017

Untitled

Mar 21st, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 13.50 KB | None | 0 0
  1. #### Define the quadratic and cross-entropy cost functions
  2. class QuadraticCost(object):
  3.     @staticmethod
  4.     def fn(a, y):
  5.         """Return the cost associated with an output ``a`` and desired output
  6.        ``y``.
  7.        """
  8.         return 0.5*np.linalg.norm(a-y)**2
  9.     @staticmethod
  10.     def delta(z, a, y):
  11.         """Return the error delta from the output layer."""
  12.         return (a-y) * sigmoid_prime(z)
  13. class CrossEntropyCost(object):
  14.     @staticmethod
  15.     def fn(a, y):
  16.         """Return the cost associated with an output ``a`` and desired output
  17.        ``y``.  Note that np.nan_to_num is used to ensure numerical
  18.        stability.  In particular, if both ``a`` and ``y`` have a 1.0
  19.        in the same slot, then the expression (1-y)*np.log(1-a)
  20.        returns nan.  The np.nan_to_num ensures that that is converted
  21.        to the correct value (0.0).
  22.        """
  23.         return np.sum(np.nan_to_num(-y*np.log(a)-(1-y)*np.log(1-a)))
  24.     @staticmethod
  25.     def delta(z, a, y):
  26.         """Return the error delta from the output layer.  Note that the
  27.        parameter ``z`` is not used by the method.  It is included in
  28.        the method's parameters in order to make the interface
  29.        consistent with the delta method for other cost classes.
  30.        """
  31.         return (a-y)
  32. #### Main Network class
  33. class Network(object):
  34.     def __init__(self, sizes, cost=CrossEntropyCost):
  35.         """The list ``sizes`` contains the number of neurons in the respective
  36.        layers of the network.  For example, if the list was [2, 3, 1]
  37.        then it would be a three-layer network, with the first layer
  38.        containing 2 neurons, the second layer 3 neurons, and the
  39.        third layer 1 neuron.  The biases and weights for the network
  40.        are initialized randomly, using
  41.        ``self.default_weight_initializer`` (see docstring for that
  42.        method).
  43.        """
  44.         self.num_layers = len(sizes)
  45.         self.sizes = sizes
  46.         self.default_weight_initializer()
  47.         self.cost=cost
  48.     def default_weight_initializer(self):
  49.         """Initialize each weight using a Gaussian distribution with mean 0
  50.        and standard deviation 1 over the square root of the number of
  51.        weights connecting to the same neuron.  Initialize the biases
  52.        using a Gaussian distribution with mean 0 and standard
  53.        deviation 1.
  54.        Note that the first layer is assumed to be an input layer, and
  55.        by convention we won't set any biases for those neurons, since
  56.        biases are only ever used in computing the outputs from later
  57.        layers.
  58.        """
  59.         self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
  60.         self.weights = [np.random.randn(y, x)/np.sqrt(x)
  61.                         for x, y in zip(self.sizes[:-1], self.sizes[1:])]
  62.     def large_weight_initializer(self):
  63.         """Initialize the weights using a Gaussian distribution with mean 0
  64.        and standard deviation 1.  Initialize the biases using a
  65.        Gaussian distribution with mean 0 and standard deviation 1.
  66.        Note that the first layer is assumed to be an input layer, and
  67.        by convention we won't set any biases for those neurons, since
  68.        biases are only ever used in computing the outputs from later
  69.        layers.
  70.        This weight and bias initializer uses the same approach as in
  71.        Chapter 1, and is included for purposes of comparison.  It
  72.        will usually be better to use the default weight initializer
  73.        instead.
  74.        """
  75.         self.biases = [np.random.randn(y, 1) for y in self.sizes[1:]]
  76.         self.weights = [np.random.randn(y, x)
  77.                         for x, y in zip(self.sizes[:-1], self.sizes[1:])]
  78.     def feedforward(self, a):
  79.         """Return the output of the network if ``a`` is input."""
  80.         for b, w in zip(self.biases, self.weights):
  81.             a = sigmoid(np.dot(w, a)+b)
  82.         return a
  83.     def SGD(self, training_data, epochs, mini_batch_size, eta,
  84.             lmbda = 0.0,
  85.             evaluation_data=None,
  86.             monitor_evaluation_cost=False,
  87.             monitor_evaluation_accuracy=False,
  88.             monitor_training_cost=False,
  89.             monitor_training_accuracy=False):
  90.         """Train the neural network using mini-batch stochastic gradient
  91.        descent.  The ``training_data`` is a list of tuples ``(x, y)``
  92.        representing the training inputs and the desired outputs.  The
  93.        other non-optional parameters are self-explanatory, as is the
  94.        regularization parameter ``lmbda``.  The method also accepts
  95.        ``evaluation_data``, usually either the validation or test
  96.        data.  We can monitor the cost and accuracy on either the
  97.        evaluation data or the training data, by setting the
  98.        appropriate flags.  The method returns a tuple containing four
  99.        lists: the (per-epoch) costs on the evaluation data, the
  100.        accuracies on the evaluation data, the costs on the training
  101.        data, and the accuracies on the training data.  All values are
  102.        evaluated at the end of each training epoch.  So, for example,
  103.        if we train for 30 epochs, then the first element of the tuple
  104.        will be a 30-element list containing the cost on the
  105.        evaluation data at the end of each epoch. Note that the lists
  106.        are empty if the corresponding flag is not set.
  107.        """
  108.         if evaluation_data: n_data = len(evaluation_data)
  109.         n = len(training_data)
  110.         evaluation_cost, evaluation_accuracy = [], []
  111.         training_cost, training_accuracy = [], []
  112.         for j in xrange(epochs):
  113.             random.shuffle(training_data)
  114.             mini_batches = [
  115.                 training_data[k:k+mini_batch_size]
  116.                 for k in xrange(0, n, mini_batch_size)]
  117.             for mini_batch in mini_batches:
  118.                 self.update_mini_batch(
  119.                     mini_batch, eta, lmbda, len(training_data))
  120.             print("Epoch"+ j +" training complete")
  121.             if monitor_training_cost:
  122.                 cost = self.total_cost(training_data, lmbda)
  123.                 training_cost.append(cost)
  124.                 print("Cost on training data: {}".format(cost))
  125.             if monitor_training_accuracy:
  126.                 accuracy = self.accuracy(training_data, convert=True)
  127.                 training_accuracy.append(accuracy)
  128.                 print("Accuracy on training data: {} / {}".format(
  129.                     accuracy, n))
  130.             if monitor_evaluation_cost:
  131.                 cost = self.total_cost(evaluation_data, lmbda, convert=True)
  132.                 evaluation_cost.append(cost)
  133.                 print("Cost on evaluation data: {}".format(cost))
  134.             if monitor_evaluation_accuracy:
  135.                 accuracy = self.accuracy(evaluation_data)
  136.                 evaluation_accuracy.append(accuracy)
  137.                 print("Accuracy on evaluation data: {} / {}".format(
  138.                     self.accuracy(evaluation_data), n_data))
  139.             print
  140.         return evaluation_cost, evaluation_accuracy, \
  141.             training_cost, training_accuracy
  142.     def update_mini_batch(self, mini_batch, eta, lmbda, n):
  143.         """Update the network's weights and biases by applying gradient
  144.        descent using backpropagation to a single mini batch.  The
  145.        ``mini_batch`` is a list of tuples ``(x, y)``, ``eta`` is the
  146.        learning rate, ``lmbda`` is the regularization parameter, and
  147.        ``n`` is the total size of the training data set.
  148.        """
  149.         nabla_b = [np.zeros(b.shape) for b in self.biases]
  150.         nabla_w = [np.zeros(w.shape) for w in self.weights]
  151.         for x, y in mini_batch:
  152.             delta_nabla_b, delta_nabla_w = self.backprop(x, y)
  153.             nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)]
  154.             nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)]
  155.         self.weights = [(1-eta*(lmbda/n))*w-(eta/len(mini_batch))*nw
  156.                         for w, nw in zip(self.weights, nabla_w)]
  157.         self.biases = [b-(eta/len(mini_batch))*nb
  158.                        for b, nb in zip(self.biases, nabla_b)]
  159.     def backprop(self, x, y):
  160.         """Return a tuple ``(nabla_b, nabla_w)`` representing the
  161.        gradient for the cost function C_x.  ``nabla_b`` and
  162.        ``nabla_w`` are layer-by-layer lists of numpy arrays, similar
  163.        to ``self.biases`` and ``self.weights``."""
  164.         nabla_b = [np.zeros(b.shape) for b in self.biases]
  165.         nabla_w = [np.zeros(w.shape) for w in self.weights]
  166.         # feedforward
  167.         activation = x
  168.         activations = [x] # list to store all the activations, layer by layer
  169.         zs = [] # list to store all the z vectors, layer by layer
  170.         for b, w in zip(self.biases, self.weights):
  171.             z = np.dot(w, activation)+b
  172.             zs.append(z)
  173.             activation = sigmoid(z)
  174.             activations.append(activation)
  175.         # backward pass
  176.         delta = (self.cost).delta(zs[-1], activations[-1], y)
  177.         nabla_b[-1] = delta
  178.         nabla_w[-1] = np.dot(delta, activations[-2].transpose())
  179.         # Note that the variable l in the loop below is used a little
  180.         # differently to the notation in Chapter 2 of the book.  Here,
  181.         # l = 1 means the last layer of neurons, l = 2 is the
  182.         # second-last layer, and so on.  It's a renumbering of the
  183.         # scheme in the book, used here to take advantage of the fact
  184.         # that Python can use negative indices in lists.
  185.         for l in xrange(2, self.num_layers):
  186.             z = zs[-l]
  187.             sp = sigmoid_prime(z)
  188.             delta = np.dot(self.weights[-l+1].transpose(), delta) * sp
  189.             nabla_b[-l] = delta
  190.             nabla_w[-l] = np.dot(delta, activations[-l-1].transpose())
  191.         return (nabla_b, nabla_w)
  192.     def accuracy(self, data, convert=False):
  193.         """Return the number of inputs in ``data`` for which the neural
  194.        network outputs the correct result. The neural network's
  195.        output is assumed to be the index of whichever neuron in the
  196.        final layer has the highest activation.
  197.        The flag ``convert`` should be set to False if the data set is
  198.        validation or test data (the usual case), and to True if the
  199.        data set is the training data. The need for this flag arises
  200.        due to differences in the way the results ``y`` are
  201.        represented in the different data sets.  In particular, it
  202.        flags whether we need to convert between the different
  203.        representations.  It may seem strange to use different
  204.        representations for the different data sets.  Why not use the
  205.        same representation for all three data sets?  It's done for
  206.        efficiency reasons -- the program usually evaluates the cost
  207.        on the training data and the accuracy on other data sets.
  208.        These are different types of computations, and using different
  209.        representations speeds things up.  More details on the
  210.        representations can be found in
  211.        mnist_loader.load_data_wrapper.
  212.        """
  213.         if convert:
  214.             results = [(np.argmax(self.feedforward(x)), np.argmax(y))
  215.                        for (x, y) in data]
  216.         else:
  217.             results = [(np.argmax(self.feedforward(x)), y)
  218.                         for (x, y) in data]
  219.         return sum(int(x == y) for (x, y) in results)
  220.     def total_cost(self, data, lmbda, convert=False):
  221.         """Return the total cost for the data set ``data``.  The flag
  222.        ``convert`` should be set to False if the data set is the
  223.        training data (the usual case), and to True if the data set is
  224.        the validation or test data.  See comments on the similar (but
  225.        reversed) convention for the ``accuracy`` method, above.
  226.        """
  227.         cost = 0.0
  228.         for x, y in data:
  229.             a = self.feedforward(x)
  230.             if convert: y = vectorized_result(y)
  231.             cost += self.cost.fn(a, y)/len(data)
  232.         cost += 0.5*(lmbda/len(data))*sum(
  233.             np.linalg.norm(w)**2 for w in self.weights)
  234.         return cost
  235.     def save(self, filename):
  236.         """Save the neural network to the file ``filename``."""
  237.         data = {"sizes": self.sizes,
  238.                 "weights": [w.tolist() for w in self.weights],
  239.                 "biases": [b.tolist() for b in self.biases],
  240.                 "cost": str(self.cost.__name__)}
  241.         f = open(filename, "w")
  242.         json.dump(data, f)
  243.         f.close()
  244. #### Loading a Network
  245. def load(filename):
  246.     """Load a neural network from the file ``filename``.  Returns an
  247.    instance of Network.
  248.    """
  249.     f = open(filename, "r")
  250.     data = json.load(f)
  251.     f.close()
  252.     cost = getattr(sys.modules[__name__], data["cost"])
  253.     net = Network(data["sizes"], cost=cost)
  254.     net.weights = [np.array(w) for w in data["weights"]]
  255.     net.biases = [np.array(b) for b in data["biases"]]
  256.     return net
  257. #### Miscellaneous functions
  258. def vectorized_result(j):
  259.     """Return a 10-dimensional unit vector with a 1.0 in the j'th position
  260.    and zeroes elsewhere.  This is used to convert a digit (0...9)
  261.    into a corresponding desired output from the neural network.
  262.    """
  263.     e = np.zeros((10, 1))
  264.     e[j] = 1.0
  265.     return e
  266. def sigmoid(z):
  267.     """The sigmoid function."""
  268.     return 1.0/(1.0+np.exp(-z))
  269. def sigmoid_prime(z):
  270.     """Derivative of the sigmoid function."""
  271.     return sigmoid(z)*(1-sigmoid(z))
Add Comment
Please, Sign In to add comment