Neural Network Training
local graph
Chapter 4 — Neural Network Training
Section titled “Chapter 4 — Neural Network Training”This chapter describes neural network training. When we talk about “training” in this context, we mean obtaining the optimal weight parameters automatically from training data. In this chapter, we will introduce a criterion called a loss function; this enables a neural network to learn. The purpose of training is to discover the weight parameters that lead to the smallest value of the loss function. In this chapter, we will be introduced to the method of using the gradient of a function, called a gradient method, to discover the smallest loss function value.
Learning from Data
Section titled “Learning from Data”The essential characteristic of a neural network is its ability to learn from data. Training from data means that weight parameter values can be automatically determined. If you have to determine all the parameters manually, it is quite hard work. For example, for a sample perceptron, as shown in Chapter 2, Perceptrons, we determined the parameter values manually while looking at the truth table. There are as few as three parameters. However, in an actual neural network, the number of parameters can range between thousands and tens of thousands. For deep learning with more layers, the number of parameters may reach hundreds of millions. It is almost impossible to determine them manually. This chapter describes neural network training, or how to determine parameter values from data, and implements a model that learns handwritten digits from the MNIST dataset with Python.
For a linearly separable problem, a perceptron can learn automatically from data. That training, when completed a finite number of times, can solve a linearly separable problem, which is known as “the perceptron convergence theorem.” On the other hand, a nonlinear separation problem cannot be solved (automatically).
Data-Driven
Section titled “Data-Driven”Data is critical in machine learning. Machine learning looks for an answer in the data, finds a pattern in the data, and tells a story based on it. It can do nothing without data. Therefore, “data” exists at the center of machine learning. We can say that this data-driven approach is a departure from a “man”-centered approach.
Usually, when we solve a problem—especially when we need to find a pattern—we must consider various things to find an answer. “This problem seems to have this pattern.” “No, there may be a cause somewhere else.” Based on our experience and intuition, we advance this task through trial and error. Machine learning avoids human intervention as much as possible. It tries to find an answer (pattern) from the collected data. Moreover, a neural network and deep learning have an important characteristic in common in that they can avoid human intervention more than traditional machine learning.
Let’s look at a specific problem here. Suppose that we want to implement a program that recognizes the number “5”, for example. Let’s suppose that our goal is implementing the program that determines whether handwritten images, as shown in Figure 4.1, are “5” or not “5”. This problem seems relatively simple. What algorithm can we use?

Figure 4.1: Sample handwritten digits – how “5” is written varies from person to person
Section titled “Figure 4.1: Sample handwritten digits – how “5” is written varies from person to person”When you try to design a program that can classify “5” correctly, you will find that it is a more difficult problem than expected. We can easily recognize “5”, but it is difficult to clarify the rule for recognizing an image as “5”. As shown in Figure 4.1, how it is written differs from person to person. This tells us that finding the rule for recognizing “5” will be hard work and that it may take a lot of time.
Now, instead of “working out” the algorithm that recognizes “5” from scratch, we want to use data effectively to solve the problem. One of the methods we can use is to extract features from an image and use machine learning technology to learn the pattern of the features. A feature indicates a converter that is designed to extract essential data (important data) from input data (input image) accurately. The feature of an image is usually described as a vector. Famous features in the field of computer vision include SIFT, SURF, and HOG. You can use these features to convert image data into vectors and use a classifier in machine learning, such as SVM and KNN, to learn the converted vectors.
In this machine learning approach, a “machine” discovers a pattern from the collected data. This can solve a problem more efficiently and reduce the burden on a “person” compared to when we invent an algorithm from scratch. However, we must note that the features that are used when images are converted into vectors are designed by a “man.” This is because good results cannot be obtained without using features that are suitable for the problem (or without designing the features). For example, to recognize the face of a dog, a person may need to select the features that are different from those for recognizing “5”. After all, even the approach of using features and machine learning may need suitable features to be selected by a “man,” depending on the problem.
So far, we have discussed two approaches to machine learning problems. These two approaches are shown in the upper rows in Figure 4.2. Meanwhile, the approach to using a neural network (deep learning) is shown in the lower row of Figure 4.2. It is represented by a block without human intervention.
As shown in Figure 4.2, a neural network learns images “as they are.” In the second approach, an example that uses features and machine learning, called human-designed features, are used, while in a neural network, a “machine” learns important features from images:

Figure 4.2: A paradigm shift from man-made rules to a “machine” learning from data – a block without human intervention is shown in gray
Section titled “Figure 4.2: A paradigm shift from man-made rules to a “machine” learning from data – a block without human intervention is shown in gray”Deep learning is sometimes called “end-to-end machine learning.” “End-to-end” means “from one end to the other end,” that is, the acquisition of the desired result (output) from raw data (input).
The advantage of a neural network is that it can solve all the problems in the same flow; for example, whether trying to recognize “5”, a dog, or a human face, a neural network learns the provided data patiently, trying to discover a pattern in the given problem. A neural network can learn data as it is “end-to-end,” regardless of the problem to solve.
Training Data and Test Data
Section titled “Training Data and Test Data”In this chapter, we will cover neural network training, beginning with some best practices when handling data in machine learning.
In machine learning problems, we usually use training data and test data according to the purpose. First, we use only training data to find optimal parameters. Then, we use test data to evaluate the ability of the trained model. Why should we divide training data and test data? Because we want the generalization capability of the model. We must separate the training data and test data because we want to evaluate this generalization correctly.
Generalization means the ability of unknown data (data that is not contained in the training data), and the ultimate goal of machine learning is to obtain this generalization. For example, handwritten digit recognition may be used in a system for reading postal codes on postcards automatically. In that case, handwritten digit recognition must be able to recognize the characters written by “someone.” That “someone” is not “a specific character written by a specific person,” but “an arbitrary character is written by an arbitrary person.” Even if the model can distinguish only your training data well, it may have learned only specific characters of the person’s handwriting contained in the data.
Therefore, if you use only one dataset to learn parameters and evaluate them, the correct evaluation will not be provided. This results in a model that can handle a certain dataset well but cannot handle another one. When a model has become too adapted to only one dataset, overfitting occurs. Avoiding overfitting is an important challenge in machine learning.
Loss Function
Section titled “Loss Function”How do you answer when you are asked, “How happy are you now?”. We may usually answer vaguely: “I am moderately happy” or “I am not very happy.” You may be surprised if someone answers, “My current happiness score is 10.23” because the person can only quantify their happiness with one score. If such a person exists, the person may lead their life only based on their “happiness score.”
This “happiness score” is an allegory used to illustrate some similar things which occur in neural network training. In neural network training, one “score” is used to indicate the current status. Based on the score, optimal weight parameters are searched for. As this person looks for an “optimal life” based on the “happiness score,” a neural network searches for optimal parameters using “one score” as a guide. The score that’s used in neural network training is called a loss function. Although any function can be used as the loss function, the sum of squared errors or a cross-entropy error is usually used.
A loss function is an index that indicates the “poorness” of a neural network’s ability. It indicates how unfit the current neural network is for labeled data and how it deviates from labeled data. You may feel that it’s unnatural for the “poorness of ability” to be the score, but you can interpret the loss function multiplied by a negative value as the score of the opposite of “how poor the ability is” (that is, the score of “how good the ability is”). “To minimize poorness of ability” is the same as “to maximize the goodness of ability.” Therefore, the index of the “poorness” of ability is essentially the same as that of the “goodness” of ability.
Sum of Squared Errors
Section titled “Sum of Squared Errors”There are a few functions that are used as loss functions. Probably the most famous one is the sum of squared errors. It is expressed by the following equation:
![]() | (4.1) |
|---|
Here, yk is the output of the neural network, tk is labeled data, and k is the number of dimensions of the data. For example, in the section, Handwritten Digit Recognition, of Chapter 3, Neural networks, yk, and tk are data items that consist of 10 elements:
>>> y = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0]
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
The elements of these arrays correspond to numbers “0,” “1,” “2,” … in order from the first index. Here, the output of the neural network, y, is the output of a softmax function. The output of the softmax function can be interpreted as a probability. In this example, the probability of “0” is 0.1, that of “1” is 0.05, that of “2” is 0.6, and so on. Meanwhile, t is labeled data. In the labeled data, the correct label is 1 and the other labels are 0. Here, label “2” is 1, which indicates that the correct answer is “2.” Setting 1 for the correct label and 0 for other labels is called one-hot representation.
As shown in equation (4.1), the sum of squared errors is the sum of the squares of the differences between the outputs of the neural network and the corresponding elements of the correct teacher data. Now, let’s implement the sum of squared errors in Python. You can implement it as follows:
def sum_squared_error(y, t): return 0.5 * np.sum((y-t)**2)Here, the y and t arguments are NumPy arrays. Because this simply implements equation (4.1), we won’t explain this here. Now, we will use this function to perform a calculation:
>>> # Assume that “2” is correct
t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
Example 1: “2” is the most probable (0.6)
Section titled “Example 1: “2” is the most probable (0.6)”y = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] sum_squared_error(np.array(y), np.array(t)) 0.097500000000000031
Example 2: “7” is the most probable (0.6)
Section titled “Example 2: “7” is the most probable (0.6)”y = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0] sum_squared_error(np.array(y), np.array(t)) 0.59750000000000003
There are two examples here. In the first one, the correct answer is “2”, and the output of the neural network is the largest at “2.” Meanwhile, in the second one, the correct answer is “2,” but the output of the neural network is the largest at “7.” As the result of this experiment shows, the loss function of the first example is smaller, which indicates that the difference in the labeled data is smaller. In other words, the sum of squared errors indicates that the output in the first example fits the labeled data better.
Cross-Entropy Error
Section titled “Cross-Entropy Error”Other than the sum of squared errors, a cross-entropy error is also often used as a loss function. It is expressed by the following equation:
![]() | (4.2) |
|---|
Here, log indicates the natural logarithm, that is, the logarithm to the base of e (loge*)*. yk is the output of the neural network and tk is the correct label. In tk, only the index for the correct label is 1; the other indices are 0 (one-hot representation). Therefore, equation (4.2) only calculates the logarithm of the output that corresponds to the correct label, 1. For example, if “2” is the index of the correct label, and the corresponding output from the neural network is 0.6, a cross-entropy error is -log 0.6 = 0.51. If the output for “2” is 0.1, the error is -log 0.1 = 2.30. A cross-entropy error depends on the output result from the correct label. Figure 4.3 shows the graph of this natural logarithm:

Figure 4.3: Graph of the natural logarithm y = log x
Section titled “Figure 4.3: Graph of the natural logarithm y = log x”As shown in Figure 4.3, y is 0 when x is 1, and the value of y is getting smaller as x approaches 0. Therefore, since the output corresponding to the correct label is larger, equation (4.2) approaches 0. When the output is 1, the cross-entropy error becomes 0. When the output corresponding to the correct label is smaller, the value of equation (4.2) is larger.
Now, let’s implement a cross-entropy error:
def cross_entropy_error(y, t): delta = 1e-7 return -np.sum(t * np.log(y + delta))Here, the y and t arguments are NumPy arrays. When np.log is calculated, a very small value, delta, is added. If np.log(0) is calculated, -inf, which indicates minus infinity, is returned. At this point, the calculation cannot be advanced further. To avoid this, a very small value is added so that minus infinity does not occur. Now, let’s use cross_entropy_error(y, t) for ease of calculation:
>>> t = [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
y = [0.1, 0.05, 0.6, 0.0, 0.05, 0.1, 0.0, 0.1, 0.0, 0.0] cross_entropy_error(np.array(y), np.array(t)) 0.51082545709933802
y = [0.1, 0.05, 0.1, 0.0, 0.05, 0.1, 0.0, 0.6, 0.0, 0.0] cross_entropy_error(np.array(y), np.array(t)) 2.3025840929945458
In the first example, the output of the correct label is 0.6 and the cross-entropy error is 0.51. In the next example, the output of the correct label is as small as 0.1 and the cross-entropy error is 2.3. These results are consistent with what we’ve discussed so far.
Mini-Batch Learning
Section titled “Mini-Batch Learning”For a machine learning problem, training data is used for training. To be precise, it means finding the loss function for the training data and finding the parameters that make that value as small as possible. Therefore, all the training data must be used to obtain the loss function. If there are 100 pieces of training data, the sum of their 100 loss functions must be used as the index.
In the example of the loss function we described earlier, the loss function for one piece of data was used. For a cross-entropy error, equation (4.3) can calculate the sum of the loss functions for all training data:
![]() | (4.3) |
|---|
Suppose that the number of data elements is N. tnk means the k-th value of the n-th data (ynk is the output of the neural network, and tnk is labeled data). Although this equation seems a little complicated, it is only an extension of equation (4.2), which expresses the loss function for one piece of data for N items of data. In the end, it is divided by N for normalization. Division by N calculates the “average loss function” per data. The average can be used as a consistent index, regardless of the amount of training data. For example, even when the number of training data elements is 1,000 or 10,000, you can calculate the average loss function per data element.
The MNIST dataset contains 60,000 items of training data. Calculating the sum of the loss functions for all this data takes a while. Big data sometimes contains millions or tens of millions of pieces of data. In that case, calculating the loss functions for all the data is not practical. Therefore, some data is extracted to approximate all the data. Also, in neural network training, some training data is selected, and training is conducted for each group of data, which is called a mini-batch (small collection). For example, 100 pieces of data are selected at random from 60,000 items of training data to be used for training. This training method is called mini-batch training.
Now, let’s write some code that selects the specified amount of data from the training data at random for mini-batch training. Before that, the following is the code for loading the MNIST dataset:
import sys, ossys.path.append(os.pardir)import numpy as npfrom dataset.mnist import load_mnist(x_train, t_train), (x_test, t_test) = /
load_mnist(normalize=True, one_hot_label=True)print(x_train.shape) # (60000, 784)print(t_train.shape) # (60000, 10)As described in Chapter 3, Neural Networks, the load_mnist function loads the MNIST dataset. It is located in the dataset/mnist.py file provided with this book. This function loads the training and test data. By specifying the one_hot_label=True argument, you can use one-hot representation, where the correct label is 1 and the other labels are 0.
When you load the preceding MNIST data, you will find that the number of training data is 60,000 and that the input data contains 784 rows of image data (originally 28x28). Labeled data is data with 10 rows. Therefore, the shapes of x_train and t_train are (60000, 784) and (60000, 10), respectively.
Now, how can we extract 10 pieces of data at random from the training data? We can write the following code by using NumPy’s np.random.choice() function:
train_size = x_train.shape[0]batch_size = 10batch_mask = np.random.choice(train_size, batch_size)x_batch = x_train[batch_mask]t_batch = t_train[batch_mask]By using np.random.choice(), you can select the desired number of numerals at random from the specified numerals. For example, np.random.choice(60000, 10) selects 10 numerals at random from the numerals between 0 and less than 60,000. In the actual code, as shown here, you can obtain the indices as an array for selecting mini-batches:
>>> np.random.choice(60000, 10)
array([ 8013, 14666, 58210, 23832, 52091, 10153, 8107, 19410, 27260,21411])Now, you can specify the randomly selected indices to extract mini-batches. We will use these mini-batches to calculate loss functions.
To measure television viewership, not all households, but selected ones, are targeted. For example, by measuring viewership among 1,000 households randomly selected from Tokyo, you can approximate the viewership throughout Tokyo. The viewership among these 1,000 households is not exactly the same as the whole viewership, but it can be used as an approximate value. Like the viewership described here, the loss function of a mini-batch is measured by using sample data to approximate the whole data. In short, a small group of randomly selected data (mini-batch) is used as the approximation of the whole training data.
Implementing Cross-Entropy Error (Using Batches)
Section titled “Implementing Cross-Entropy Error (Using Batches)”How can we use batch data such as mini-batches to implement a cross-entropy error? By improving the cross-entropy error we implemented earlier, which targets only one piece of data, we can implement it easily. Here, we will support both the input of a single piece of data and the input of data as batches:
def cross_entropy_error(y, t): if y.ndim == 1: t = t.reshape(1, t.size) y = y.reshape(1, y.size) batch_size = y.shape[0] return -np.sum(t * np.log(y + 1e-7)) / batch_sizeHere, y is the output of the neural network, and t is labeled data. If y is one-dimensional (that is, to calculate the cross-entropy error for one piece of data), the shape of the data is changed. The average cross-entropy error per data is calculated by normalization based on the amount of data in a batch.
If labeled data is provided as labels (not in one-hot representation format but as labels such as “2” and “7”), we can implement a cross-entropy error as follows:
def cross_entropy_error(y, t): if y.ndim == 1: t = t.reshape(1, t.size) y = y.reshape(1, y.size) batch_size = y.shape[0] return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_sizePlease note that if t of an element is 0 in one-hot representation, its cross-entropy error is also 0, and you can ignore this calculation. In other words, if you can obtain the output of the neural network for a correct label, you can calculate the cross-entropy error. Therefore, for t as the one-hot representation, t * np.log(y) is used, while for t as labels, np.log( y[np.arange(batch_size), t] ) is used for the same processing (here, the description of “a very small value, 1e-7” has been omitted for visibility).
For reference, we can cover np.log( y[np.arange(batch_size), t] ) briefly. np.arange(batch_size) generates an array from 0 to batch_size-1. When batch_size is 5, np.arange(batch_size) generates a NumPy array, [0, 1, 2, 3, 4]. t contains labels, as in [2, 7, 0, 9, 4] and y[np.arange(batch_size), t] extracts the output of the neural network corresponding to the correct label for each piece of data (in this example, y[np.arange(batch_size), t] generates a NumPy array, [y[0,2], y[1,7], y[2,0], y[3,9], y[4,4]]).
Why Do We Configure a Loss Function?
Section titled “Why Do We Configure a Loss Function?”Some people may wonder why we introduce a loss function. For example, in the case of number recognition, we want parameters to improve recognition accuracy. Isn’t it extra work to introduce a loss function? Our goal is to achieve a neural network that maximizes recognition accuracy. So, surely, we should use “recognition accuracy” as a score?
You can find the answer to this question by paying attention to the role of the “derivative” in neural network training. This will be explained in detail in the next section. Neural network training looks for optimal parameters (weights and biases) so that the value of the loss function is the smallest. To look for the position of the smallest loss function, the derivative (gradient, to be precise) of a parameter is calculated, and the parameter value is updated gradually, based on the value of the derivative.
For example, suppose that a virtual neural network exists here. We will pay attention to one weight parameter in the neural network. Here, the derivative of the loss function of the weight parameter indicates how the loss function changes when the value of the weight parameter is changed a little. If the derivative becomes a negative value, you can reduce the loss function by changing the weight parameter in a positive direction. On the other hand, if the derivative is a positive value, you can reduce the loss function by changing the weight parameter in the negative direction. However, when the value of the derivative becomes 0, the value of the loss function does not change, no matter how the weight parameter is moved. Updating the weight parameter is stopped there.
We cannot use recognition accuracy as the score because the derivative becomes 0 at almost all positions, preventing parameters from being updated. Now, let’s neatly summarize this.
When training a neural network, we should not use recognition accuracy as the score. The reason is that if you use recognition accuracy as the score, the derivative of the parameters will be zero in most places.
So why does recognition accuracy as the score lead the derivative of the parameter to 0 at almost all positions? Well, to explain this, let’s consider another example. Say that a neural network can recognize 32 out of 100 items of training data. This means that the recognition accuracy is 32%. If we use the recognition accuracy as the score, slightly changing the weight parameter will leave it at 32% and cause no change. Slightly adjusting the parameters does not improve recognition accuracy. Even if the recognition accuracy is improved, the change will not be continuous, such as 32.0123…%, but discontinuous, such as 33% and 34%. On the other hand, if the loss function is used as the score, the current value of the loss function is represented as a value, such as 0.92543… Slightly changing the parameter value also changes the loss function continuously, such as 0.93432…
Slightly adjusting the parameter only changes the recognition accuracy a bit, and any change is discontinuous and sudden. This is also true of the “step function” of an activation function. If you use a step function for an activation function, a neural network cannot learn appropriately for the same reason. The reason for this is that the derivative of a step function is 0 almost anywhere (positions other than 0), as shown in Figure 4.4. When you use a step function, a slight change to the parameter is erased by the step function, and the value of the loss function shows no changes, even if you use it as the score.
A step function changes only at some moments, like a shishi-odoshi or scarecrow. On the other hand, for the derivative (tangent) of a sigmoid function, the output (value of the vertical axis) changes continuously and the gradient of the curve also changes continuously, as shown in Figure 4.4. In short, the derivative of a sigmoid function is not 0 at any position. This is important for “training” in a neural network. Because the gradient is never 0, a neural network can learn correctly:

Figure 4.4: Step function and sigmoid function – the gradient of a step function is 0 at almost all positions, while the gradient of a sigmoid function (tangent) is never 0
Section titled “Figure 4.4: Step function and sigmoid function – the gradient of a step function is 0 at almost all positions, while the gradient of a sigmoid function (tangent) is never 0”Numerical Differentiation
Section titled “Numerical Differentiation”The gradient method uses information from the gradient to determine which direction to follow. This section describes what a gradient is and its characteristics, beginning with a “derivative.”
Derivative
Section titled “Derivative”For example, let’s assume that you ran 2 km in 10 minutes from the start of a full marathon. You can calculate the speed as 2 / 10 = 0.2 [km/minute]. You ran at a speed of 0.2 km per minute.
In this example, we calculated how much the “running distance” changed over “time.” Strictly speaking, this calculation indicates the “average speed” for 10 minutes because you ran 2 km in 10 minutes. A derivative indicates the amount of change at “a certain moment.” Therefore, by minimizing the time of 10 minutes (the distance in the last 1 minute, the distance in the last 1 second, the distance in the last 0.1 seconds, and so on), you can obtain the amount of change at a certain moment (instantaneous speed).
Thus, a derivative indicates the amount of change at a certain moment. This is defined by the following equation:
![]() | (4.4) |
|---|
Equation (4.4) indicates the derivative of a function. The left-hand side
indicates the derivative of f(x) with respect to x – the degree of changes of f(x) with respect to x. The derivative expressed by equation (4.4) indicates how the value of the function, f(x), changes because of a “slight change” in x. Here, the slight change, h, is brought close to 0 infinitely, which is indicated as
.
Let’s write a program to obtain the derivative of a function based on equation (4.4). To implement equation (4.4) directly, you can assign a small value to h for calculation purposes:
# Bad implementation sample
def numerical_diff(f, x): h = 10e-50 return (f(x+h) - f(x)) / hThe function is named numerical_diff(f, x), after numerical differentiation. It takes two arguments: the function, f, and the argument, x, of the function, f. This implementation seems correct, but two improvements can be made.
The preceding implementation uses a small value of 10e-50 (“0.00…1” containing 50 0s) as h because we want to use the smallest possible value as h (we want to bring h infinitely close to 0 if possible). But the problem of a rounding error occurs here. A rounding error occurs in the final calculation result by omitting a numeric value in the small range of a decimal (for example, by omitting eight or more places of decimals). The following example shows a rounding error in Python:
>>> np.float32(1e-50) 0.0
When you represent 1e-50 in the float32 type (a 32-bit floating-point number), the value becomes 0.0. You cannot express it correctly. Using too small value causes a problem in computer calculation. Now, here is the first improvement. You can use 10−4 as the small value, h. It is known that a value of around 10−4 brings about good results.
The second improvement is in terms of the difference in the function, f. The preceding implementation calculates the difference in the function f between x + h and x. You should observe that this calculation causes an error in the first place. As shown in Figure 4.5, the “true derivative ” corresponds to the gradient of the function at the position of x (called a tangent), while the derivative in this implementation corresponds to the gradient between (x + h) and x. Therefore, the true derivative (true tangent) is not strictly identical to the value of this implementation. This difference occurs because you cannot bring h close to 0 infinitely:

Figure 4.5: True derivative (true tangent) and numerical differentiation (tangent by approximation) are different in value
Section titled “Figure 4.5: True derivative (true tangent) and numerical differentiation (tangent by approximation) are different in value”As shown in Figure 4.5, a numerical differential contains an error. To reduce this error, you can calculate the difference of the function, (f), between (x + h) and (x - h). This difference is called a central difference because it is calculated around x (on the other hand, the difference between (x + h) and x is called a forward difference). Now, let’s implement a numerical differentiation (numerical gradient) based on these two improvements:
def numerical_diff(f, x): h = 1e-4 # 0.0001 return (f(x+h) - f(x-h)) / (2*h)As the preceding code shows, calculating a derivative by using a very small value difference is called numerical differentiation. On the other hand, obtaining a derivative with the expansion is called an “analytical solution” or “analytically obtaining a derivative,” for example, by using the word “analytic.” You can obtain the derivative of y = x2 analytically as
. Therefore, you can calculate the derivative of y as x = 2, and this is 4. An analytic derivative is the “true derivative” without errors.
Examples of Numerical Differentiation
Section titled “Examples of Numerical Differentiation”Let’s differentiate an easy function by using numerical differentiation. The first example is the quadratic function expressed by the following equation:
![]() | (4.5) |
|---|
Implement equation (4.5) in Python as follows:
def function_1(x): return 0.01*x**2 + 0.1*xDraw the graph of this function. The following shows the code for drawing a graph and the resulting graph (Figure 4.6):
import numpy as npimport matplotlib.pylab as plt
x = np.arange(0.0, 20.0, 0.1) # The array x containing 0 to 20 in increments of 0.1y = function_1(x)plt.xlabel("x")plt.ylabel("f(x)")plt.plot(x, y)plt.show()Now calculate the differentials of the function when x=5 and x=10:
>>> numerical_diff(function_1, 5) 0.1999999999990898
numerical_diff(function_1, 10) 0.2999999999986347
The differential calculated here is the amount of change of f(x) for x, which corresponds to the gradient of the function. By the way, the analytical solution of f (x) = 0.01x2 + 0.1x is
= 0.02x + 0.1. The true derivative when x=5 and 10 are 0.2 and 0.3, respectively. They are not strictly identical to the results from numerical differentiation, but the error is very small. Actually, the error is so small that they can be regarded as almost identical values:

Figure 4.6: Graph of f (x) = 0.01x2 + 0.1x
Section titled “Figure 4.6: Graph of f (x) = 0.01x2 + 0.1x”We will use the preceding results of our numerical differentiation to plot graphs of lines whose gradients are the values of the numerical differentiation. The results are shown in Figure 4.7. Here, you can see that the derivatives correspond to the tangents of the function (the source code is located at ch04/gradient_1d.py):

Figure 4.7: Tangents when x = 5 and x = 10 – using the values from numerical differentiation as the gradients of lines
Section titled “Figure 4.7: Tangents when x = 5 and x = 10 – using the values from numerical differentiation as the gradients of lines”Partial Derivative
Section titled “Partial Derivative”Next, let’s look at the function expressed by equation (4.6). This simple equation calculates the square sum of the arguments. Note that it has two variables, unlike the previous example:
![]() | (4.6) |
|---|
You can implement it in Python as follows:
def function_2(x): return x[0]**2 + x[1]**2 # or return np.sum(x**2)Here, it is assumed that NumPy arrays are passed as arguments. The function simply squares each element of the NumPy arrays and sums it up (np.sum(x**2) can implement the same processing). Now, let’s draw the graph of this function. This three-dimensional graph appears as follows:

Figure 4.8: Graph of 
Section titled “Figure 4.8: Graph of ”Now, we want to calculate the derivative of equation (4.6). Here, please note that equation (4.6) has two variables. Therefore, you must specify for which of the two variables, x0 and x1, the differentials are calculated. The derivative of a function that consists of multiple variables is called a partial derivative. They are expressed as
.
To illustrate this, consider the following two partial derivative problems and their solutions:
Question 1: Calculate the partial derivative,
, for x0 when x0 = 3 and x1 = 4:
>>> def function_tmp1(x0): … return x0*x0 + 4.0**2.0 …
numerical_diff(function_tmp1, 3.0) 6.00000000000378
Question 2: Calculate the partial derivative,
, for x1 when x0 = 3 and x1 = 4:
>>> def function_tmp2(x1): … return 3.0**2.0 + x1*x1 …
numerical_diff(function_tmp2, 4.0) 7.999999999999119
To solve these problems, a function with one variable is defined, and the derivative for the function is calculated. For example, in Question 1, a new function for x1=4 is defined, and the function, which has only one variable, x0, is passed to the function to calculate a numerical differentiation. Based on the results, the answer to Question 1 is 6.00000000000378, and the answer to Question 2 is 7.999999999999119. They are mostly the same as the solutions from analytical differentiation.
In this way, the partial derivative calculates the gradient at a certain position, such as the differentiation for one variable. However, for the partial derivative, one of the variables is targeted, and the other variables are fixed at a certain value. In the preceding implementation, a new function was defined to hold the other variables at a specific value. The newly defined function was passed to the previous numerical differential function to calculate the partial derivative.
Bookmark
Gradient
Section titled “Gradient”In the previous example, the partial derivatives of x0 and x1 were calculated for each variable. Now, we want to calculate the partial derivatives of x0 and x1 collectively. For example, let’s calculate the partial derivatives of (x0, x1) when x0 = 3 and x1 = 4 as (
)The vector that collectively indicates the partial differentials of all the variables, such as (
) is called a gradient. You can implement a gradient as follows:
def numerical_gradient(f, x): h = 1e-4 # 0.0001 grad = np.zeros_like(x) # Generate an array with the same shape as x for idx in range(x.size): tmp_val = x[idx] # Calculate f(x+h) x[idx] = tmp_val + h fxh1 = f(x) # Calculate f(x-h) x[idx] = tmp_val - h fxh2 = f(x) grad[idx] = (fxh1 - fxh2) / (2*h) x[idx] = tmp_val # Restore the original value return gradImplementing the numerical_gradient(f, x) function seems a little complicated, but the processes are almost the same as those in numerical differentiation for one variable. Note that np.zeros_like(x) generates an array that has the same shape as x and whose elements are all zero.
The numerical_gradient(f, x) function takes the f (function) and x (NumPy array) arguments and obtains numerical differentiations for each element of the NumPy array, x. Now, let’s use this function to calculate a gradient. Here, we will obtain the gradients at points (3, 4), (0, 2), and (3, 0):
>>> numerical_gradient(function_2, np.array([3.0, 4.0])) array([ 6., 8.])
numerical_gradient(function_2, np.array([0.0, 2.0])) array([ 0., 4.]) numerical_gradient(function_2, np.array([3.0, 0.0])) array([ 6., 0.])
The actual result is [6.0000000000037801, 7.9999999999991189], but [6., 8.] is returned. This is because a returned NumPy array is formatted to enhance the visibility of the values.
Thus, we can calculate the gradient at each point of (x0, x1). The preceding example shows that the gradient for point (3, 4) is (6, 8), that for point (0, 2) is (0, 4), and that for point (3, 0) is (6, 0). What do these gradients mean? To understand this, let’s look at the gradients of
. Here, we will make the gradients negative and draw the vectors (the source code is located at ch04/gradient_2d.py).
The gradients of
are shown as the vectors (arrows) that have the direction toward the lowest point, as shown in Figure 4. 9. In Figure 4.9, the gradients seem to point at “the lowest position (smallest value)” of the function, f(x0, x1). Just like a compass, the arrows point to one point. The more distant they are from “the lowest position,” the larger the size of the arrow:

Figure 4.9: Gradients of 
Section titled “Figure 4.9: Gradients of ”In the example shown in Figure 4.9, the gradients point at the lowest position, but this is not always the case. In fact, gradient points in the lower direction at each position. To be more precise, the direction of a gradient is the direction that reduces the value of the function most at each position. This is an important point, so please keep this in mind.
Gradient Method
Section titled “Gradient Method”Many machine learning problems look for optimal parameters during training. A neural network also needs to find optimal parameters (weights and biases) during training. The optimal parameter here is the parameter value when the loss function takes the minimum value. However, a loss function can be complicated. The parameter space is vast, and we cannot guess where it takes the minimum value. A gradient method makes good use of gradients to find the minimum value (or the smallest possible value) of the function.
A gradient shows the direction that reduces the value of the function most at each position. Therefore, whether the position that a gradient points in is really the minimum value of the function, in other words, whether the direction is really the one to take, cannot be guaranteed. Actually, in a complicated function, the direction that a gradient points to is not the minimum value in most cases.
The gradient is 0 at the local minimum, the minimum, and at a point called the saddle point of a function. A local minimum is locally the smallest value, which is the minimum value in a limited range. A saddle point is a position of the local maximum in one direction and of the local minimum in another direction. A gradient method looks for the position where a gradient is 0, but where the position is not always the global minimum (it can be the local minimum or a saddle point). When a function has a complicated and distorted shape, learning enters an (almost) flat land and a stagnant period called a “plateau” might occur, leading to stagnation in training.
Even if the direction of a gradient does not always point at the global minimum value, moving in that direction can reduce the value of the function the most. Therefore, to look for the position of the minimum value or to look for the position where the function has the smallest possible value, you should determine the direction of movement based on the information about gradients.
Now, let’s look at the gradient method. In the gradient method, you move a fixed distance from the current position in the gradient direction. By doing this, you obtain a gradient at the new position and move in the gradient direction again. Thus, you move in the gradient direction repeatedly. Reducing the value of a function gradually by going in the gradient direction repeatedly is known as the gradient method. This method is often used in optimization problems for machine learning. It is typically used when training neural networks.
A gradient method is called by another name if it looks for the minimum or the maximum value. To be precise, the method for the minimum value is called the gradient descent method, while the method for the maximum value is called the gradient ascent method. However, reversing the sign of a loss function can change this from a problem for the minimum value into a problem for the maximum value. So, the difference between “descent” and “ascent” is not especially important. Generally, a “gradient descent” method is often used in neural networks (deep learning).
Now, let’s express a gradient method with an equation. Equation (4.7) shows a gradient method:
![]() | (4.7) |
|---|
In equation (4.7), η adjusts the amount to be updated. This is called a learning rate in neural network. A learning rate determines how much needs to be learned and how much to update the parameters.
Equation (4.7) shows an update equation for one training instance, and the step is repeated. Each step updates the variable values, as shown in equation (4.7), and the step is repeated several times to reduce the value of the function gradually. This example has two variables, but even when the number of variables is increased, a similar equation—a partial differential value for each variable—is used for updating.
You must specify the value of the learning rate, such as 0.01 and 0.001, in advance. Generally, if this value is too large or too small, you cannot reach a “good place.” In neural network training, we usually check whether training is successful by changing the value of the learning rate.
Now, let’s implement a gradient descent method in Python. This can be done as follows:
def gradient_descent(f, init_x, lr=0.01, step_num=100): x = init_x for i in range(step_num): grad = numerical_gradient(f, x) x -= lr * grad return xThe f argument is a function to optimize, the init_x argument is an initial value, the lr argument is a learning rate, and the step_num argument is the number of repetitions in a gradient method. The gradient of the function is obtained by numerical_gradient(f, x) and the gradient updated by multiplying it by the learning rate, which is repeated the number of times specified by step_num.
You can use this function to obtain the local minimum of the function and even the minimum value if you are lucky. Now, let’s try solving a problem.
Question: Obtain the minimum value of
with a gradient method:
>>> def function_2(x): … return x[0]**2 + x[1]**2 …
init_x = np.array([-3.0, 4.0]) gradient_descent(function_2, init_x=init_x, lr=0.1, step_num=100) array([ -6.11110793e-10, 8.14814391e-10])
Here, specify (-3.0, 4.0) as the initial value and start looking for the minimum value by using a gradient method. The final result is (-6.1e-10, 8.1e-10), which is almost near (0, 0). Actually, the true minimum value is (0, 0). You successfully obtained almost correct results by using a gradient method. Figure 4.10 shows the process of updating with a gradient method. The origin is the lowest position, and you can see that the result is approaching it gradually. The source code to draw this graph is located at ch04/gradient_method.py (ch04/gradient_method.py does not display dashed lines, which show the contour lines in the graph):

Figure 4.10: Updating
with a gradient method – the dashed lines show the contour lines of the function
Section titled “Figure 4.10: Updating with a gradient method – the dashed lines show the contour lines of the function”As mentioned earlier, an overly large or small learning rate does not achieve good results. Let’s do some experiments regarding both cases here:
# When the learning rate is too large: lr=10.0
init_x = np.array([-3.0, 4.0]) gradient_descent(function_2, init_x=init_x, lr=10.0, step_num=100)
array([ -2.58983747e+13, -1.29524862e+12])# When the learning rate is too small: lr=1e-10init_x = np.array([-3.0, 4.0]) gradient_descent(function_2, init_x=init_x, lr=1e-10, step_num=100) array([-2.99999994, 3.99999992])
As this experiment shows, the result diverges to a large value if the learning rate is too large. On the other hand, almost no updates occur if the learning rate is too small. Setting an appropriate learning rate is important.
A parameter such as a learning rate is called a hyperparameter. It is different from the parameters (weights and biases) of a neural network in terms of its characteristics. Weight parameters in a neural network can be obtained automatically with training data and a training algorithm, while a hyperparameter must be specified manually. Generally, you must change this hyperparameter to various values to find a value that enables good training.
Gradients for a Neural Network
Section titled “Gradients for a Neural Network”You must also calculate gradients in neural network training. The gradients here are those of a loss function for weight parameters. For example, let’s assume that a neural network has the weight W (2x3 array) only, and the loss function is L. In this case, we can express the gradient as
. The following equation shows this:
![]() | (4.8) |
|---|
Each element of
is the partial derivative for each element. For example, the element at the first row and column,
, indicates how a slight change in w11 changes the loss function, L. What is important here is that the shape of
is the same as that of W. Actually, in equation (4.8), both W and
are the same (2x3) in shape.
Now, let’s implement a program that calculates a gradient by taking an easy neural network as an example. To do that, we will implement a class named simpleNet (the source code is located at ch04/gradient_simplenet.py):
import sys, ossys.path.append(os.pardir)import numpy as npfrom common.functions import softmax, cross_entropy_errorfrom common.gradient import numerical_gradientclass simpleNet: def __ init __ (self): self.W = np.random.randn(2,3) # Initialize with a Gaussian distribution def predict(self, x): return np.dot(x, self.W) def loss(self, x, t): z = self.predict(x) y = softmax(z) loss = cross_entropy_error(y, t) return lossHere, the softmax and cross_entropy_error methods in common/functions.py are being used. The numerical_gradient method in common/gradient.py is also being used. The simpleNet class has only one instance variable, which is the weight parameters with a shape of 2x3. It has two methods: one is predict(x) for prediction, and the other is loss(x, t) for obtaining the value of the loss function. Here, the x argument is the input data and the t argument is a correct label. Now, let’s try using simpleNet:
>>> net = simpleNet()
print(net.W) # Weight parameters [[ 0.47355232 0.9977393 0.84668094] [ 0.85557411 0.03563661 0.69422093]]
x = np.array([0.6, 0.9]) p = net.predict(x) print(p) [ 1.05414809 0.63071653 1.1328074] np.argmax(p) # Index for the maximum value 2
t = np.array([0, 0, 1]) # Correct label net.loss(x, t) 0.92806853663411326
Next, let’s obtain the gradients,using numerical_gradient(f, x). The f(W) function defined here takes a dummy argument, W. Because the f(x) function is executed inside numerical_gradient(f, x), f(W) is defined for consistency:
>>> def f(W): … return net.loss(x, t) …
dW = numerical_gradient(f, net.W) print(dW) [[ 0.21924763 0.14356247 -0.36281009] [ 0.32887144 0.2153437 -0.54421514]]
The f argument of numerical_gradient(f, x) is a function and the x argument is the argument to the function, f. Therefore, a new function, f, is defined here. It takes net.W as an argument and calculates the loss function. The newly defined function is passed to numerical_gradient(f, x).
numerical_gradient(f, net.W) returns dW, which is a two-dimensional 2x3 array. dW shows that
for
is around 0.2, for example. This indicates that when w11 is increased by h, the value of the loss function increases by 0.2h.
is about -0.5, which indicates that when w23 is increased by h, the value of the loss function decreases by 0.5h. Therefore, to reduce the loss function, you should update w23 in a positive direction and w11 in a negative direction. You can also see that updating w23 contributes to the reduction more than updating w11.
In the preceding implementation, the new function is written as def f(x):… In Python, you can use a lambda notation to write and implement a simple function, as follows:
>>> f = lambda w: net.loss(x, t)
dW = numerical_gradient(f, net.W)
After obtaining the gradients for a neural network, all you have to do is use a gradient method to update the weight parameters. In the next section, we will implement all these training processes for a two-layer neural network.
The numerical_gradient() function we used here is slightly different from the previous implementation for handling multi-dimensional arrays such as the weight parameter, W. However, these changes are simple and are only for handling multidimensional arrays. For further details, please refer to the source code (common/gradient.py).
Bookmark
Implementing a Training Algorithm
Section titled “Implementing a Training Algorithm”So far, we have learned about the basics of neural network training. Important keywords such as “loss function”, “mini-batch”, “gradient”, and “gradient descent method” have appeared in succession. Here, we will look at the procedure of neural network training for review purposes. Let’s go over the neural network training procedure.
Presupposition
A neural network has adaptable weights and biases. Adjusting them so that they fit the training data is called “training.” Neural network training consists of four steps.
Step 1 (mini-batch)
Select some data at random from the training data. The selected data is called a mini-batch. The purpose here is to reduce the value of the loss function for the mini-batch.
Step 2 (calculating gradients)
To reduce the loss function for the mini-batch, calculate the gradient for each weight parameter. The gradient shows the direction that reduces the value of the loss function the most.
Step 3 (updating parameters)
Update the weight parameters slightly in the gradient direction.
Step 4 (repeating)
Repeat steps 1, 2, and 3.
The preceding four steps are used for neural network training. This method uses a gradient descent method to update parameters. Because the data used here is selected at random as a mini-batch, it is referred to as stochastic gradient descent. “Stochastic” means “selecting data at random stochastically.” Therefore, stochastic gradient descent means “the gradient descent method for randomly selected data.” In many deep learning frameworks, stochastic gradient descent is usually implemented as the SGD function, which is named after its initials.
Now, let’s implement the neural network that actually learns handwritten digits. Here, a two-layer neural network (with one hidden layer) will use the MNIST dataset for training.
A Two-Layer Neural Network as a Class
Section titled “A Two-Layer Neural Network as a Class”First, let’s implement a two-layer neural network as a class. This class is named TwoLayerNet and is implemented as follows (implementing TwoLayerNet is based on the Python source code provided by the CS231n (Convolutional Neural Networks for Visual Recognition (http://cs231n.github.io/) course at Stanford University). The source code is located at ch04/two_layer_net.py:
import sys, ossys.path.append(os.pardir)from common.functions import *from common.gradient import numerical_gradientclass TwoLayerNet: def __ init __ (self, input_size, hidden_size, output_size, weight_init_std=0.01): # Initialize weights self.params = {} self.params['W1'] = weight_init_std * / np.random.randn(input_size, hidden_size) self.params['b1'] = np.zeros(hidden_size) self.params['W2'] = weight_init_std * / np.random.randn(hidden_size, output_size) self.params['b2'] = np.zeros(output_size) def predict(self, x): W1, W2 = self.params['W1'], self.params['W2'] b1, b2 = self.params['b1'], self.params['b2'] a1 = np.dot(x, W1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, W2) + b2 y = softmax(a2) return y # x: input data, t: label data def loss(self, x, t): y = self.predict(x) return cross_entropy_error(y, t) def accuracy(self, x, t): y = self.predict(x) y = np.argmax(y, axis=1) t = np.argmax(t, axis=1) accuracy = np.sum(y == t) / float(x.shape[0]) return accuracy # x: input data, t: teacher data def numerical_gradient(self, x, t): loss_W = lambda W: self.loss(x, t) grads = {} grads['W1'] = numerical_gradient(loss_W, self.params['W1']) grads['b1'] = numerical_gradient(loss_W, self.params['b1']) grads['W2'] = numerical_gradient(loss_W, self.params['W2']) grads['b2'] = numerical_gradient(loss_W, self.params['b2']) return gradsThe implementation of this class is a little long, but nothing that new appears. It has many things in common with the implementation of forward processing a neural network covered in the previous chapter. First, let’s look at the variables and methods that were used in this class. Table 4.1 shows the important variables, while Table 4.2 shows all the methods:

Table 4. 1: Variables used in the TwoLayerNet class
Section titled “Table 4. 1: Variables used in the TwoLayerNet class”
Table 4.2: Methods used in the TwoLayerNet class
Section titled “Table 4.2: Methods used in the TwoLayerNet class”The TwoLayerNet class has two dictionary variables, params and grads, as instance variables. The params variable contains the weight parameters. For example, the weight parameters for layer 1 are stored in params['W1'] as a NumPy array. You can access the bias for layer 1 using params['b1']. Here is an example:
net = TwoLayerNet(input_size=784, hidden_size=100, output_size=10)net.params['W1'].shape # (784, 100)net.params['b1'].shape # (100,)net.params['W2'].shape # (100, 10)net.params['b2'].shape # (10,)As shown here, the params variable contains all the parameters required for this network. The weight parameters contained in the params variable are used for predicting (forward processing). You can make a prediction as follows:
x = np.random.rand(100, 784) # Dummy input data (for 100 images)y = net.predict(x)The grads variable contains the gradient for each parameter so that it corresponds to the params variable. When you calculate gradients by using the numerical_gradient() method, gradient information is stored in the grads variable, as follows:
x = p.random.rand(100, 784) # Dummy input data (for 100 images)t = np.random.rand(100, 10) # Dummy correct label (for 100 images)grads = net.numerical_gradient(x, t) # Calculate gradientsgrads[‘W1’].shape # (784, 100) grads[‘b1’].shape # (100,) grads[‘W2’].shape # (100, 10) grads[‘b2’].shape # (10,)
Now, let’s look at the implementation of the methods in TwoLayerNet. The __init__ (self, input_size, hidden_size, output_size) method is the initialization method of the class ( called when TwoLayerNet is generated). The arguments are the numbers of neurons in the input layer, in the hidden layer, and the output layer in order from left to right. For handwritten digit recognition, a total of 784 input images that are 28x28 in size are provided and 10 classes are returned. Therefore, we specify the input_size=784 and output_size=10 arguments and set an appropriate value for hidden_size as the number of hidden layers.
This initialization method also initializes the weight parameters. Determining what values to set as the initial weight parameters is important for successful neural network training. We will discuss the initialization of weight parameters in detail later. Here, the weights are initialized by using the random numbers based on Gaussian distribution, and the biases are initialized by 0. predict(self, x), and accuracy(self, x, t) are almost the same as in the implementation of predicting in relation to the neural network, which we looked at in the previous chapter. If you have any questions, please refer to the previous chapter. The loss(self, x, t) method calculates the value of the loss function. It obtains a cross-entropy error based on the result of predict() and the correct label.
The remaining numerical_gradient(self, x, t) method calculates the gradient of each parameter. It uses numerical differentiation to calculate the gradient for the loss function of each parameter. The gradient(self, x, t) method will be implemented in the next chapter.
numerical_gradient(self, x, t) uses numerical differentiation to calculate the gradients of the parameters. In the next chapter, we will look at how to calculate gradients quickly using backpropagation, which returns almost the same result as using numerical differentiation, but with faster processing. The method for obtaining a gradient through backpropagation will be implemented as gradient(self, x, t) in the next chapter. If you want to save time, you can use gradient(self, x, t) instead of numerical_gradient(self, x, t) because neural network training takes time.
Implementing Mini-Batch Training
Section titled “Implementing Mini-Batch Training”Here, we will use mini-batch training to implement neural network training. In mini-batch training, we extract some data randomly from training data (called a mini-batch) and use it to update the parameters using a gradient method. Let’s conduct training for the TwoLayerNet class by using the MNIST dataset (the source code is located at ch04/train_neuralnet.py):
import numpy as npfrom dataset.mnist import load_mnistfrom two_layer_net import TwoLayerNet(x_train, t_train), (x_test, t_test) = \
load_mnist(normalize=True, one_hot_label=True)train_loss_list = []# Hyper-parametersiters_num = 10000train_size = x_train.shape[0]batch_size = 100learning_rate = 0.1network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)for i in range(iters_num): # Obtain a mini-batch batch_mask = np.random.choice(train_size, batch_size) x_batch = x_train[batch_mask] t_batch = t_train[batch_mask] # Calculate a gradient grad = network.numerical_gradient(x_batch, t_batch) # grad = network.gradient(x_batch, t_batch) # fast version! # Update the parameters for key in ('W1', 'b1', 'W2', 'b2'): network.params[key] -= learning_rate * grad[key] # Record learning progress loss = network.loss(x_batch, t_batch) train_loss_list.append(loss)Here, the size of a mini-batch is 100. Each time, 100 pieces of data (image data and correct label data) are extracted randomly from 60,000 pieces of training data. Then, gradients are obtained for the mini-batch, and the parameters are updated using stochastic gradient descent (SGD). Here, the number of updates made by a gradient method;that is, the number of iterations is 10,000. At each update, the loss function for the training data is calculated, and the value is added to the array. Figure 4.11 shows the graph of how the value of this loss function changes.
Figure 4.11 shows that, as the number of training increases, the value of the loss function decreases. It indicates that training is successful. The weight parameters of the neural network are adapting to the data gradually. The neural network is indeed learning. By being exposed to data repeatedly, it is approaching the optimal weight parameters:

Figure 4.11: Transition of the loss function – the image on the left shows the transition up to 10,000 iterations, while the image on the right shows the transition up to 1,000 iterations
Section titled “Figure 4.11: Transition of the loss function – the image on the left shows the transition up to 10,000 iterations, while the image on the right shows the transition up to 1,000 iterations”Using Test Data for Evaluation
Section titled “Using Test Data for Evaluation”The result of Figure 4.11 shows that repeatedly training the data reduces the value of the loss function gradually. However, the value of the loss function is the value of “the loss function for the mini-batch of training data.” The reduction in the value of the loss function for the training data indicates that the neural network is learning well. However, this result does not prove that it can handle a different dataset as well as this one.
In neural network training, we must check whether data other than training data can be recognized correctly. We must check whether “overfitting” does not occur. Overfitting means that only the number of images contained in the training data can be recognized correctly, and those that are not contained there cannot be recognized, for example.
The goal of neural network training is to obtain generalization capability. To do that, we must use data that is not contained in the training data to evaluate the generalization capability of the neural network. In the next implementation, we will record the recognition accuracy for the test data and the training data periodically during training. We will record the recognition accuracy for the test data and the training data for each epoch.
An epoch is a unit. One epoch indicates the number of iterations when all the training data has been used for training. For example, let’s assume that 100 mini-batches are used to learn 10,000 pieces of training data. After a stochastic gradient descent method is repeated 100 times, all the training data has been seen. In this case, 100 iterations = 1 epoch.
Now, we will change the previous implementation slightly to gain a correct evaluation. Here, the differences from the previous implementation are shown in bold:
train_acc_list = []In the preceding example, the recognition accuracy is calculated for all the training and test data and the results are recorded for each epoch. The recognition accuracy is calculated for each epoch because it takes time if it is calculated repeatedly in a for statement. Also, we do not need to record recognition accuracy frequently (all we need is the approximate transition of recognition accuracy). Therefore, the transition of recognition accuracy is recorded for each epoch of training data.
Now, let’s show the results of the preceding code in a graph:

Figure 4.12: Transition of recognition accuracy for training data and test data. The horizontal axis shows the epochs
Section titled “Figure 4.12: Transition of recognition accuracy for training data and test data. The horizontal axis shows the epochs”In Figure 4.12, the solid line shows the recognition accuracy of the training data, while the dashed line shows that of the test data. As you can see, as the number of epochs increases (training advances), the recognition accuracies for both the training data and the test data improve. Here, we can see that the two recognition accuracies are almost the same as the two lines mostly overlap. This indicates that overfitting did not occur here.
Summary
Section titled “Summary”This chapter described neural network training. First, we introduced a score called a loss function so that a neural network can learn. The goal of neural network training is to discover the weight parameters that lead to the smallest value of the loss function. Then, we learned how to use the gradient of a function, called the gradient method, to discover the smallest loss function value. This chapter covered the following points:
- In machine learning, we use training data and test data.
- Training data is used for training, while test data is used to evaluate the generalization capability of the trained model.
- A loss function is used as a score in neural network training. Weight parameters are updated so that the value of the loss function will decrease.
- To update the weight parameters, their gradients are used to update their values in the gradient direction repeatedly.
- Calculating a derivative based on the difference when very small values are provided is called numerical differentiation.
- You can use numerical differentiation to obtain the gradients for the weight parameters.
- Numerical differentiation takes time to calculate, but its implementation is easy. On the other hand, backpropagation, which will be described in the next chapter, is slightly complicated, but it can calculate gradients quickly.







