Neural Networks
local graph
Chapter 3 — Neural Networks
Section titled “Chapter 3 — Neural Networks”We learned about perceptrons in the previous chapter, and there is both good news and bad news. The good news is that perceptrons are likely to represent complicated functions. For example, the perceptron can (theoretically) represent complicated processes performed by a computer, as described in the previous chapter. The bad news is that weights must be defined manually first before the appropriate weights are determined in order to meet the expected inputs and outputs. In the previous chapter, we used the truth tables with AND and OR gates to determine the appropriate weights manually.
Neural networks exist to solve the bad news. More specifically, one important property of a neural network is that it can learn appropriate weight parameters from data automatically. This chapter provides an overview of neural networks and focuses on what distinguishes them. The next chapter will describe how it learns weight parameters from data.
From Perceptrons to Neural Networks
Section titled “From Perceptrons to Neural Networks”A neural network is similar to the perceptron described in the previous chapter in many ways. How a neural network works, as well as how it differs from a perceptron, will be described in this section.
Neural Network Example
Section titled “Neural Network Example”Figure 3.1 shows a neural network example. Here, the left column is called an input layer, the right column is called an output layer, and the center column is called the middle layer. The middle layer is also known as a hidden layer. “Hidden” means that the neurons in the hidden layer are invisible (unlike those in the input and output layers). In this book, we’ll call the layers layer 0, layer 1, and layer 2 from the input layer to the output layer (layer numbers start from layer 0 because doing so is convenient when the layers are implemented in Python later). In Figure 3.1, layer 0 is the input layer, layer 1 is the middle layer, and layer 2 is the output layer:

Figure 3.1: Neural network example
Section titled “Figure 3.1: Neural network example”Although the network in Figure 3.1 consists of three layers, we call it a “two-layer network” because it has two layers with weights. Some books call it a “three-layer network” based on the number of layers that constitute the network, but in this book, the network name is based on the number of layers that have weights (that is, the total number of input, hidden, and output layers, minus 1).
The neural network in Figure 3.1 is similar to the perceptron in the previous chapter in terms of its shape. In fact, in terms of how neurons are connected, it is no different from the perceptron we saw in the previous chapter. So, how are signals transmitted in a neural network?
Reviewing the Perceptron
Section titled “Reviewing the Perceptron”To answer this question, we first need to review the perceptron. Consider a network that has the following structure:

Figure 3.2: Reviewing the perceptron
Section titled “Figure 3.2: Reviewing the perceptron”Figure 3.2 shows a perceptron that receives two input signals (x1 and x2) and outputs y. As described earlier, the perceptron in Figure 3.2 is represented by equation (3.1):
![]() | (3.1) |
|---|
Here, b is a parameter called “bias” and controls how easily the neuron fires. Meanwhile, w1 and w2 are the parameters that indicate the “weights” of individual signals to control their importance.
You may have noticed that the network in Figure 3.2 has no bias, b. We can indicate the bias shown in Figure 3.3, if we want to. A signal of weight b and input 1 has been added in Figure 3.3. This perceptron receives three signals (x1, x2, and 1) as the inputs to the neuron, and multiplies the signals by each weight before transmitting them to the next neuron. The next neuron sums the weighted signals and then outputs 1 if the sum exceeds 0. It outputs 0 if it doesn’t. The neuron in the following diagram is shown in solid gray to distinguish it from other neurons. This is because the input signal of the bias is always 1:

Figure 3.3: Showing the bias explicitly
Section titled “Figure 3.3: Showing the bias explicitly”Now, we want to simplify equation (3.1). To do that, we use a single function to express the condition, where 1 is the output if the sum exceeds 0, and 0 is the output if it does not. Here, we will introduce a new function, h(x), and rewrite equation (3.1) to equations (3.2) and (3.3) shown here:
![]() | (3.2) |
|---|---|
![]() | (3.3) |
Equation (3.2) indicates that the h(x) function converts the sum of input signals into the output, y. The h(x) function represented by equation (3.3) returns 1 if the input exceeds 0 and returns 0 if it does not. Therefore, equations (3.2) and (3.3) operate in the same way as equation (3.1).
Introducing an Activation Function
Section titled “Introducing an Activation Function”The h(x) function that appears here is generally called an activation function. It converts the sum of input signals into an output signal. As the name “activation” indicates, the activation function determines how the sum of the input signals activates (that is, how it fires).
Now, we can rewrite equation (3.2) again. Equation (3.2) performs two processes: the weighted input signals are summed, and the sum is converted by the activation function. Therefore, you can divide equation (3.2) into the following two equations:
![]() | (3.4) |
|---|---|
![]() | (3.5) |
In equation (3.4), the sum of the weighted input signals and biases becomes a. In equation (3.5), a is converted by h(), and y is output.
So far, a neuron has been shown as one circle. Figure 3.4 shows equations (3.4) and (3.5) explicitly:

Figure 3.4: Showing the process performed by the activation function explicitly
Section titled “Figure 3.4: Showing the process performed by the activation function explicitly”Figure 3.4 explicitly shows the process that is performed by the activation function in the circle of the neuron. We can clearly see that the sum of the weighted signals becomes node a and that it is converted into node y by the activation function, h(). In this book, the terms “neuron” and “node” are used interchangeably. Here, circles a and y are called “nodes,” which are used in the same sense as “neurons” that were used earlier.
We will continue to show a neuron as one circle, as shown on the left of Figure 3.5. In this book, we will also show the activation process (to the right of Figure 3.5), if the behavior of the neural network can be clarified:

Figure 3.5: The left-hand image is an ordinary image that shows a neuron, while the right-hand image explicitly shows the process of activation in a neuron (a is the sum of input signals, h() is the activation function, and y is the output)
Section titled “Figure 3.5: The left-hand image is an ordinary image that shows a neuron, while the right-hand image explicitly shows the process of activation in a neuron (a is the sum of input signals, h() is the activation function, and y is the output)”Now, let’s focus on the activation function, which serves as the bridge from a perceptron to a neural network.
In this book, the algorithm indicated by the word “perceptron” is not strictly defined. Generally, a “simple perceptron” is a single-layer network where a step function that changes the output values at a threshold is used as the activation function. A “multilayer perceptron” usually means a neural network that contains multiple layers and uses a smooth activation function, such as a sigmoid function.
Activation Function
Section titled “Activation Function”The activation function represented by equation (3.3) changes output values at a threshold and is called a “step function” or a “staircase function.” Therefore, we can say, “a perceptron uses a step function as the activation function.” In other words, a perceptron chooses a “step function” as the activation function from many candidate functions. When a perceptron uses a step function as the activation function, what happens if a function other than a step function is used as the activation function? Well, by changing the activation function from a step function to another function, we can move to the world of a neural network. The next section will introduce an activation function for a neural network.
Sigmoid Function
Section titled “Sigmoid Function”One of the activation functions often used in neural networks is the sigmoid function, represented by equation (3.6):
![]() | (3.6) |
|---|
exp(-x) in equation (3.6) indicates e-x. The real number, e, is Napier’s number, 2.7182… The sigmoid function represented by equation (3.6) seems complicated, but it is only a “function.” A function is a converter that returns output when input is provided. For example, when a value such as 1.0 and 2.0 is provided to the sigmoid function, values such as h(1.0) = 0.731… and h(2.0) = 0.880… are returned.
In a neural network, a sigmoid function is often used as the activation function to convert signals, and the converted signals are transmitted to the next neuron. In fact, the main difference between the perceptron described in the previous chapter and the neural network described here is the activation function. Other aspects, such as the structure where neurons are connected in multiple layers and how signals are transmitted, are basically the same as they are for perceptrons. Now, let’s look more closely at a sigmoid function (used as the activation function) by comparing it with a step function.
Implementing a Step Function
Section titled “Implementing a Step Function”Here, we will use Python to show the graph of a step function. As represented by equation (3.3), the step function outputs 1 when the input exceeds 0 and outputs 0 if it does not. The following shows a simple implementation of the step function:
def step_function(x): if x > 0: return 1 else: return 0This implementation is simple and easy to understand, but it only takes a real number (a floating-point number) as argument x. Therefore, step_function(3.0) is allowed. However, the function cannot take a NumPy array as the argument. Thus, step_function(np.array([1.0, 2.0])) is not allowed. Here, we want to change to the future implementation so that it can take a NumPy array. For that purpose, we can write an implementation like the following:
def step_function(x): y = x > 0 return y.astype(np.int)Although the preceding function contains only two lines, it may be a little difficult to understand because it uses a useful “trick” from NumPy. Here, the following example from the Python interpreter is used to describe what kind of trick is used. In this example, the NumPy x array is provided. For the NumPy array, a comparison operator is conducted:
>>> import numpy as np
x = np.array([-1.0, 1.0, 2.0]) x array([-1., 1., 2.]) y = x > 0 y array([False, True, True], dtype=bool)
When a greater than comparison is conducted for a NumPy array, each element in the array is compared to generate a Boolean array. Here, each element in the x array is converted into True when it exceeds 0 or into False when it does not. Then, the new array, y, is generated.
The y array is Boolean, and the desired step function must return 0 or 1 of the int type. Therefore, we convert the type of elements of array y from Boolean into int:
>>> y = y.astype(np.int)
y array([0, 1, 1])
As shown here, the astype() method is used to convert the type of the NumPy array. The astype() method takes the desired type (np.int, in this example) as the argument. In Python, True is converted into 1, and False is converted into 0 by converting the Boolean type into the int type. The preceding code explains NumPy’s “trick” that’s used when implementing the step function.
Step Function Graph
Section titled “Step Function Graph”Now, let’s draw the graph of the step function we defined previously. To do that, we need to use the Matplotlib library:
import numpy as npimport matplotlib.pylab as pltdef step_function(x): return np.array(x > 0, dtype=np.int)x = np.arange(-5.0, 5.0, 0.1)y = step_function(x)plt.plot(x, y)plt.ylim(-0.1, 1.1) # Specify the range of the y-axisplt.show()np.arange(-5.0, 5.0, 0.1) generates a NumPy array containing values from -5.0 to 5.0 in 0.1 steps, ([-5.0, -4.9, …, 4.9]). step_function() takes a NumPy array as the argument. It executes the step function for each element in the array and returns an array as the result. When these x and y arrays are plotted, the graph shown in Figure 3.6 is displayed:

Figure 3.6: Step function graph
Section titled “Figure 3.6: Step function graph”As shown in Figure 3.6, the output of the step function changes from 0 to 1 (or 1 to 0) at the threshold of 0. A step function is sometimes called a “staircase function” because the output represents the steps of stairs, as shown in Figure 3.6.
Implementing a Sigmoid Function
Section titled “Implementing a Sigmoid Function”Now, let’s implement a sigmoid function. We can write the sigmoid function of equation (3.6) in Python as follows:
def sigmoid(x): return 1 / (1 + np.exp(-x))Here, np.exp(-x) corresponds to exp(−x) in the equation. This implementation is not very difficult. The correct results are returned even when a NumPy array is provided as the x argument. When this sigmoid function receives a NumPy array, it calculates correctly, as shown here:
>>> x = np.array([-1.0, 1.0, 2.0])
sigmoid(x) array([0.26894142, 0.73105858, 0.88079708])
The implementation of the sigmoid function supports a NumPy array due to NumPy’s broadcasting (refer to the Broadcasting section in Chapter 1, Introduction to Python for details). When an operation is performed on a scalar and a NumPy array, thanks to the broadcast, the operation is performed between the scalar and each element of the NumPy array.
>>> t = np.array([1.0, 2.0, 3.0])
1.0 + t array([2., 3., 4.]) 1.0 / t array([1. , 0.5 , 0.33333333])
In the preceding example, arithmetic operations (such as + and /) are performed between the scalar value (1.0 here) and the NumPy array. As a result, the scalar value and each element of the NumPy array is used in the operations, and the results are output as a NumPy array. In this implementation of the sigmoid function, because np.exp(-x) generates a NumPy array, 1 / (1 + np.exp(-x)) also uses each element of the NumPy array for the operation.
Now, let’s draw the graph of the sigmoid function. The code for drawing is almost the same as the code for the step function. The only difference is that the function that outputs y is changed to the sigmoid function:
x = np.arange(-5.0, 5.0, 0.1)y = sigmoid(x)plt.plot(x, y)plt.ylim(-0.1, 1.1) # Specify the range of the y-axisplt.show()The preceding code creates the graph shown in Figure 3.7 when it is executed:

Figure 3.7: Graph of the sigmoid function
Section titled “Figure 3.7: Graph of the sigmoid function”Comparing the Sigmoid Function and the Step Function
Section titled “Comparing the Sigmoid Function and the Step Function”Let’s compare the sigmoid function and the step function. Figure 3.8 shows the sigmoid function and the step function. In what ways are the two functions different? In what ways are they alike? We can consider Figure 3.8 and think about this for a moment.
When you look at Figure 3.8, you may notice the difference in smoothness. The sigmoid function is a smooth curve, where the output changes continuously based on the input. On the other hand, the output of the step function changes suddenly at 0. This smoothness of the sigmoid function has an important meaning when training neural networks:

Figure 3.8: Step function and sigmoid function (the dashed line shows the step function)
Section titled “Figure 3.8: Step function and sigmoid function (the dashed line shows the step function)”In connection with the smoothness mentioned previously, they are different in that the step function returns only 0 or 1, while the sigmoid function returns real numbers such as 0.731… and 0.880… That is, binary signals of 0 and 1 flow among neurons in a perceptron, while signals of continuous real numbers flow in a neural network.
When we use “water” to describe the behaviors of these two functions, the step function can be compared to a “shishi-odoshi” (a bamboo tube that clacks against a stone after water flows out of a tube), and the sigmoid function can be compared to a “waterwheel.” The step function conducts two actions: it drains or stores water (0 or 1), while the sigmoid function controls the flow of water like a “waterwheel” based on the amount of water that reaches it.
Now, consider the ways in which the step and sigmoid functions are similar. They are different in “smoothness,” but you may notice that they are similar in shape when you view Figure 3.8 from a broader perspective. Actually, both of them output a value near/of 0 when the input is small, and, as the input becomes larger, the output approaches/reaches 1. The step and sigmoid functions output a large value when the input signal contains important information and output a small value when it don’t. They are also similar in that they output a value between 0 and 1, no matter how small or large the value of the input signal is.
Nonlinear Function
Section titled “Nonlinear Function”The step and sigmoid functions are similar in another way. One important similarity is that they are both nonlinear functions. The sigmoid function is represented by a curve, while the step function is represented by straight lines that look like stairs. They are both classified as nonlinear functions.
The terms “nonlinear function” and “linear function” often appear when an activation function is used. A function is a “converter” that returns a value when a value is provided. A function that outputs the input values multiplied by a constant is called a linear function (represented by the equation h(x) = cx, where c is a constant). Therefore, the graph of a linear function is a straight line. Meanwhile, as its name suggests, the graph of a nonlinear function is not a simple straight line.
In a neural network, a nonlinear function must be used as the activation function. In other words, a linear function may not be used as the activation function. Why may a linear function not be used? The reason is that increasing the number of layers in a neural network becomes useless if a linear function is used.
The problem with a linear function is caused by the fact that a “network without a hidden layer” that does the same task always exists, no matter how many layers are added. To understand this specifically (and somewhat intuitively), let’s consider a simple example. Here, a linear function, h(x) = cx, is used as the activation function and the calculation of y(x) = h(h(h(x))) is performed as in a three-layer network. It contains multiplications of y(x) = c×c×c×x, and the same operation can be represented by one multiplication of y(x) = ax (where a = c3). Thus, it can be represented by a network without a hidden layer. As this example shows, using a linear function offsets the advantage of multiple layers. Therefore, to take advantage of multiple layers, a nonlinear function must be used as the activation function.
ReLU Function
Section titled “ReLU Function”Thus far, we have learned about step and sigmoid functions as activation functions. While a sigmoid function has been used for a long time in the history of neural networks, a function called Rectified Linear Unit (ReLU) is mainly used these days.
If the input exceeds 0, the ReLU function outputs the input as it is. If the input is equal to or smaller than 0, it outputs 0 (see Figure 3.9):

Figure 3.9: ReLU function
Section titled “Figure 3.9: ReLU function”Equation (3.7) represents the ReLU function:
![]() | (3.7) |
|---|
As the graph and the equation shows, the ReLU function is very simple. Therefore, we can also implement it easily, as shown here:
def relu(x): return np.maximum(0, x)Here, NumPy’s maximum function is used. It outputs the larger of the input values.
While a sigmoid function will be used as the activation function later in this chapter, the ReLU function is mainly used in the latter half of this book.
Bookmark
Calculating Multidimensional Arrays
Section titled “Calculating Multidimensional Arrays”If you learn how to calculate multidimensional arrays using NumPy, you will be able to implement a neural network efficiently. First, we will look at how to use NumPy to calculate multidimensional arrays. Then, we will implement a neural network.
Multidimensional Arrays
Section titled “Multidimensional Arrays”Simply put, a multidimensional array is “a set of numbers” arranged in a line, in a rectangle, in three dimensions, or (more generally) in N dimensions, called a multidimensional array. Let’s use NumPy to create a multidimensional array. First, we will create a one-dimensional array, as described so far:
>>> import numpy as np
A = np.array([1, 2, 3, 4]) print(A) [1 2 3 4] np.ndim(A) 1 A.shape (4,) A.shape[0] 4
As shown here, you can use the np.ndim() function to obtain the number of dimensions of an array. You can also use the instance variable, shape, to obtain the shape of the array. The preceding example shows that A is a one-dimensional array consisting of four elements. Please note that the result of A.shape is a tuple. This is because the result is returned in the same format both for a one-dimensional array and for a multidimensional array. For example, a (4,3) tuple is returned for a two-dimensional array, and a (4,3,2) tuple is returned for a three-dimensional one. Therefore, a tuple is also returned for a one-dimensional array. Now, let’s create a two-dimensional array:
>>> B = np.array([[1,2], [3,4], [5,6]])
print(B) [[1 2] [3 4] [5 6]] np.ndim(B) 2 B.shape (3, 2)
Here, a 3x2 array, B, is created. A 3x2 array means that it has three elements in the first dimension and two elements in the next dimension. The first dimension is dimension 0, and the next dimension is dimension 1 (an index starts from 0 in Python). A two-dimensional array is called a matrix. As shown in Figure 3.10, a horizontal sequence in an array is called a row, while a vertical sequence is called a column:

Figure 3.10: A horizontal sequence is called a “row,” and a vertical one is called a “column”
Section titled “Figure 3.10: A horizontal sequence is called a “row,” and a vertical one is called a “column””Matrix Multiplication
Section titled “Matrix Multiplication”Now, consider the product of matrices (two-dimensional arrays). For 2x2 matrices, matrix multiplication is calculated as shown in Figure 3.11 (defined as the calculation in this procedure):

Figure 3.11: Calculating matrix multiplication
Section titled “Figure 3.11: Calculating matrix multiplication”As this example indicates, matrix multiplication is calculated by multiplying the elements between the (horizontal) rows of the left matrix and the (vertical) columns of the right matrix and adding the results. The calculation result is stored as the elements of a new multidimensional array. For example, the result between A’s first row and B’s first column becomes the first element in the first row, while the result between A’s second row and B’s first column becomes the first element in the second row. In this book, a matrix in an equation is shown in bold. For example, a matrix is shown as A to differentiate it from a scalar value (for example, a or b) with one element. This calculation is implemented in Python as follows:
>>> A = np.array([[1,2], [3,4]])
A.shape (2, 2) B = np.array([[5,6], [7,8]]) B.shape (2, 2) np.dot(A, B)
array([[19, 22], [43, 50]])A and B are 2x2 matrices. NumPy’s np.dot() function is used to calculate the product of matrices A and B (the “dot” here indicates a dot product). np.dot (dot product) calculates the inner product of vectors for one-dimensional arrays and matrix multiplication for two-dimensional arrays. You should note that np.dot(A, B) and np.dot(B, A) can return different values. Unlike regular operations (+, *, and so on), the product of matrices becomes different when the order of operands (A and B) is different.
The preceding example shows the product of 2x2 matrices. You can also calculate the product of matrices in different shapes. For example, the product of 2x3 and 3x2 matrices can be implemented in Python as follows:
>>> A = np.array([[1,2,3], [4,5,6]])
A.shape (2, 3) B = np.array([[1,2], [3,4], [5,6]]) B.shape (3, 2) np.dot(A, B)
array([[22, 28], [49, 64]])The preceding code shows how the product of the 2x3 matrix A and the 3x2 matrix B can be implemented. Here, you must be careful about the “shapes of matrices.” Specifically, the number of elements (number of columns) in dimension 1 of matrix A must be the same as the number of elements (number of rows) in dimension 0 of matrix B. Actually, in the preceding example, matrix A is 2x3, and matrix B is 3x2. The number of elements in dimension 1 of matrix A (3) is the same as the number of elements in dimension 0 of matrix B (3). If they are different, the product of the matrices cannot be calculated. So then, if you try to calculate the product of the 2x3 matrix A and the 2x2 matrix C in Python, the following error occurs:
>>> C = np.array([[1,2], [3,4]])
C.shape (2, 2) A.shape (2, 3) np.dot(A, C)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>ValueError: shapes (2,3) and (2,2) not aligned: 3 (dim 1) != 2 (dim 0)This error says that dimension 1 of matrix A and dimension 0 of matrix C are different in terms of the numbers of their elements (the index of a dimension starts from zero). In other words, to calculate the product of a multidimensional array, the number of elements in the corresponding dimensions of two matrices must be the same. Because this is an important point, let’s check it again in Figure 3.12:

Figure 3.12: The number of elements in corresponding dimensions must be the same for matrix multiplication
Section titled “Figure 3.12: The number of elements in corresponding dimensions must be the same for matrix multiplication”Figure 3.12 shows an example of the product of the 3x2 matrix A and the 2x4 matrix B, resulting in the 3x4 matrix C. As we can see, the number of elements in the corresponding dimensions of matrices A and B must be the same. The resulting matrix, C, consists of as many rows as matrix A and as many columns as matrix B. This is also important.
Even when A is a two-dimensional matrix and B is a one-dimensional array, the same principle (that the number of elements in the corresponding dimensions must be the same) applies, as shown in Figure 3.13:

Figure 3.13: The number of elements in the corresponding dimensions must be the same, even when A is a two-dimensional matrix and B is a one-dimensional array
Section titled “Figure 3.13: The number of elements in the corresponding dimensions must be the same, even when A is a two-dimensional matrix and B is a one-dimensional array”The sample in Figure 3.13 can be implemented in Python as follows:
>>> A = np.array([[1,2], [3, 4], [5,6]])
A.shape (3, 2) B = np.array([7,8]) B.shape (2,) np.dot(A, B) array([23, 53, 83])
Matrix Multiplication in a Neural Network
Section titled “Matrix Multiplication in a Neural Network”Now, let’s use NumPy matrices to implement a neural network, as shown in Figure 3.14. Let’s assume that the neural network only has weights. Bias and an activation function have been omitted.

Figure 3.14: Using matrix multiplication to calculate a neural network
Section titled “Figure 3.14: Using matrix multiplication to calculate a neural network”In this implementation, we must be careful about the shapes of X, W, and Y. It is very important that the number of elements in the corresponding dimensions of X and W are the same:
>>> X = np.array([1, 2])
X.shape (2,) W = np.array([[1, 3, 5], [2, 4, 6]]) print(W) [[1 3 5] [2 4 6]] W.shape (2, 3) Y = np.dot(X, W) print(Y) [ 5 11 17]
As shown here, you can use np.dot (dot product of multidimensional matrices) to calculate the result, Y, at one time. This means that, even if the number of elements of Y is 100 or 1,000, you can calculate it all at once. Without np.dot, you must take out each element of Y (and use a for statement) for calculation, which is very tiresome. Therefore, we can say that the technique of using matrix multiplication to calculate the product of multidimensional matrices is very important.
Bookmark
Implementing a Three-Layer Neural Network
Section titled “Implementing a Three-Layer Neural Network”Now, let’s implement a “practical” neural network. Here, we will implement the process from its input to its output (a process in the forward direction) in the three-layer neural network shown in Figure 3.15. We will use NumPy’s multidimensional arrays (as described in the previous section) for implementation. By making good use of NumPy arrays, you can write some short code for a forward process in the neural network.
Examining the Symbols
Section titled “Examining the Symbols”Here, we will use symbols such as
and
to explain the processes performed in the neural network. They may seem a little complicated. You can skim through this section because the symbols are only used here:

Figure 3.15: A three-layer neural network consisting of two neurons in the input layer (layer 0), three neurons in the first hidden layer (layer 1), two neurons in the second hidden layer (layer 2), and two neurons in the output layer (layer 3)
Section titled “Figure 3.15: A three-layer neural network consisting of two neurons in the input layer (layer 0), three neurons in the first hidden layer (layer 1), two neurons in the second hidden layer (layer 2), and two neurons in the output layer (layer 3)”What is important in this section is that calculating a neural network can be conducted collectively as a matrix calculation. Calculating each layer in a neural network can be conducted collectively using matrix multiplication (this can be considered from a larger viewpoint). So, there is no problem in understanding subsequent explanations, even if you forget the detailed rules relating to these symbols.
Let’s begin by defining the symbols. Look at Figure 3.16. This diagram illustrates the weight from the input layer x2 to the neuron a
in the next layer.
As shown in Figure 3.16, “(1)” is placed at the upper right of a weight or a hidden layer neuron. This number indicates the weight or neuron of layer 1. A weight has two numbers at the lower right, which are the index numbers of the next and previous layer neurons. For example,
indicates that it is the weight from the second neuron (x2) in the previous layer to the first neuron (
) in the next layer. The index numbers at the lower right of weight must be in the order of “the number for the next layer and the number for the previous layer”:

Figure 3.16: Weight symbols
Section titled “Figure 3.16: Weight symbols”Implementing Signal Transmission in Each Layer
Section titled “Implementing Signal Transmission in Each Layer”Now, let’s look at transmitting signals from the input layer to “the first neuron in layer 1.” Figure 3.17 shows this graphically:

Figure 3.17: Transmitting signals from the input layer to layer 1
Section titled “Figure 3.17: Transmitting signals from the input layer to layer 1”As shown in Figure 3.17, ① is added as a neuron for a bias. Note that there is only one index at the lower right of the bias. This is because only one bias neuron (① neuron) exists in the previous layer. Now, let’s express
as an equation to review what we have learned so far.
is the sum of the weighted signals and the bias and is calculated as follows:
![]() | (3.8) |
|---|
By using matrix multiplication, you can express “the weighted sum” of layer 1 collectively as follows:
![]() | (3.9) |
|---|
Here, A(1), X, B(1), and W(1) are as follows:

Now, let’s use NumPy’s multidimensional arrays to implement equation (3.9). Arbitrary values are set for input signals, weights, and biases here:
X = np.array([1.0, 0.5])W1 = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]])B1 = np.array([0.1, 0.2, 0.3])print(W1.shape) # (2, 3)print(X.shape) # (2,)print(B1.shape) # (3,)A1 = np.dot(X, W1) + B1This calculation is the same as the one in the previous section. W1 is a 2x3 array and X is a one-dimensional array with two elements. Also, in this case, the number of elements in the corresponding dimensions of W1 and X are the same.
Now, consider the processes performed by the activation function in layer 1. Figure 3.18 shows these processes graphically.
As shown in Figure 3.18, the weighted sums in a hidden layer (the total of the weighted signals and the biases) are shown as *a’*s, and the signals converted with the activation function are shown as z’s. Here, the activation function is shown as h() using a sigmoid function:

Figure 3.18: Transmitting signals from the input layer to layer 1
Section titled “Figure 3.18: Transmitting signals from the input layer to layer 1”This process is implemented in Python as follows:
Z1 = sigmoid(A1)print(A1) # [0.3, 0.7, 1.1]print(Z1) # [0.57444252, 0.66818777, 0.75026011]This sigmoid() function is the one we defined previously. It takes a NumPy array and returns a NumPy array with the same number of elements.
Let’s now move on to the implementation from layer 1 to layer 2 (Figure 3.19):

Figure 3.19: Transmitting signals from layer 1 to layer 2
Section titled “Figure 3.19: Transmitting signals from layer 1 to layer 2”This implementation is the same as the previous one, except that the output of layer 1 (Z1) is the input of layer 2. As you can see, you can write the transmission of signals from one layer to another easily by using NumPy arrays:
W2 = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]])B2 = np.array([0.1, 0.2])print(Z1.shape) # (3,)print(W2.shape) # (3, 2)print(B2.shape) # (2,)A2 = np.dot(Z1, W2) + B2Z2 = sigmoid(A2)Finally, let’s implement the transmission of signals from layer 2 to the output layer (Figure 3.20). You can implement the output layer almost in the same way as the other implementations we’ve looked at so far. Only the last activation function is different from that of the hidden layers we’ve seen so far:
A3 = np.dot(Z2, W3) + B3Here, we will define a function named identity_function() and use it as the activation function for the output layer. An identity function outputs the input as it is. Although you do not need to define identity_function() in this example, this implementation is used so that it is consistent with the previous ones. In Figure 3.20, the activation function of the output layer is shown as σ() to indicate that it is different from the activation function, h(), of the hidden layers (σ is called sigma):

Figure 3.20: Transmitting signals from layer 2 to the output layer
Section titled “Figure 3.20: Transmitting signals from layer 2 to the output layer”You can select the activation function used in the output layer, depending on what type of problem you wish to solve. Generally, an identity function is used for a regression problem, a sigmoid function for a two-class classification problem, and a softmax function for a multi-class classification problem. The activation function for an output layer will be explained in detail in the next section.
Implementation Summary
Section titled “Implementation Summary”This completes our investigation of a three-layer neural network. The following summarizes the implementation we’ve performed so far. As is customary in the implementation of a neural network, only weights are written in uppercase (for example, W1), while other items (such as a bias and intermediate result) are written in lowercase:
def init_network(): network = {} network['W1'] = np.array([[0.1, 0.3, 0.5], [0.2, 0.4, 0.6]]) network['b1'] = np.array([0.1, 0.2, 0.3]) network['W2'] = np.array([[0.1, 0.4], [0.2, 0.5], [0.3, 0.6]]) network['b2'] = np.array([0.1, 0.2]) network['W3'] = np.array([[0.1, 0.3], [0.2, 0.4]]) network['b3'] = np.array([0.1, 0.2]) return networkdef forward(network, x): W1, W2, W3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['b1'], network['b2'], network['b3'] a1 = np.dot(x, W1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, W2) + b2 z2 = sigmoid(a2) a3 = np.dot(z2, W3) + b3 y = identity_function(a3) return ynetwork = init_network()x = np.array([1.0, 0.5])y = forward(network, x)print(y) # [ 0.31682708 0.69627909]Here, the init_network() and forward() functions are defined. The init_network() function initializes the weights and biases and stores them in a dictionary type variable, network which stores the parameters required for individual layers, weights, and biases. The forward() function collectively implements the process of converting an input signal into an output signal.
The word “forward” here indicates the transmission process from an input to an output. Later, we will look at the process in the backward direction (from output to input) when we train a neural network.
This completes the implementation of a three-layer neural network in the forward direction. By using NumPy’s multidimensional arrays, we were able to implement a neural network efficiently.
Bookmark
Designing the Output Layer
Section titled “Designing the Output Layer”You can use a neural network both for a classification problem and for a regression problem. However, you must change the activation function of the output layer, depending on which of the problems you use a neural network for. Usually, an identity function is used for a regression problem, and a softmax function is used for a classification problem.
Machine learning problems can be broadly divided into “classification problems” and “regression problems.” A classification problem is a problem of identifying which class the data belongs to—for example, classifying the person in an image as a man or a woman—while a regression problem is a problem of predicting a (continuous) number from certain input data—for example, predicting the weight of the person in an image.
Bookmark
Identity Function and Softmax Function
Section titled “Identity Function and Softmax Function”An identity function outputs the input as it is. The function that outputs what is entered without doing anything is an identity function. Therefore, when an identity function is used for the output layer, an input signal is returned as-is. Using the diagram of the neural network we’ve used so far, you can represent the process by an identity function as shown in Figure 3.21. The process of conversion by the identity function can be represented with one arrow, in the same way in the same way as the activation function we have seen so far:

Figure 3.21: Identity function
Section titled “Figure 3.21: Identity function”The softmax function, which is used for a classification problem, is expressed by the following equation:
![]() | (3.10) |
|---|
exp(x) is an exponential function that indicates ex (e is Napier’s constant, 2.7182…). Assuming the total number of output layers is n, the equation provides the k-th output, yk. As shown in equation (3.10), the numerator of the softmax function is the exponential function of the input signal, ak, and the denominator is the sum of the exponential functions of all the input signals.
Figure 3.22 shows the softmax function graphically. As you can see, the output of the softmax function is connected from all the input signals with arrows. As the denominator of equation (3.10) indicates, each neuron of the output is affected by all the input signals:

Figure 3.22: Softmax function
Section titled “Figure 3.22: Softmax function”Now, let’s implement the softmax function,using the Python interpreter to check the results, one by one:
>>> a = np.array([0.3, 2.9, 4.0])
exp_a = np.exp(a) # Exponential function print(exp_a) [ 1.34985881 18.17414537 54.59815003]
sum_exp_a = np.sum(exp_a) # Sum of exponential functions print(sum_exp_a) 74.1221542102
y = exp_a / sum_exp_a print(y) [ 0.01821127 0.24519181 0.73659691]
This implementation represents the softmax function of equation (3.10) with Python. Therefore, no special description will be required. When considering the use of the softmax function later, we will define it as a Python function, as follows:
def softmax(a): exp_a = np.exp(a) sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return yIssues when Implementing the Softmax Function
Section titled “Issues when Implementing the Softmax Function”The preceding implementation of the softmax function represents equation (3.10) correctly, but it is defective for computer calculations. This defect is an overflow problem. Implementing the softmax function involves calculating the exponential functions, and the value of an exponential function can be very large. For example, e10 is larger than 20,000, and e100 is a large value that has more than 40 digits. The result of e1000 returns inf, which indicates an infinite value. Dividing these large values returns an “unstable” result.
When a computer handles a “number,” it is stored in finite data width, such as four or eight bytes. This means that a number has a number of significant figures. The range of a number that can be represented is limited. Therefore, there is a problem in that a very large value cannot be expressed. This is called an overflow, so we must be careful when we use a computer for calculation.
Improved implementation of the softmax function is obtained from the following equation:
![]() | (3.11) |
|---|
First, equation (3.11) is transformed by multiplying both the numerator and the denominator by an arbitrary constant, C (the same calculations are performed because both the numerator and the denominator are multiplied by the same constant). Then, C is moved into the exponential function (exp) as log C. Finally, log C is replaced with another symbol, C’.
Equation (3.11) says that adding or subtracting a certain constant does not change the result when the exponential functions in the softmax function are calculated. Although you can use any number as C’ here, the largest value from the input signals is usually used to prevent an overflow. Consider the following example:
>>> a = np.array([1010, 1000, 990])
np.exp(a) / np.sum(np.exp(a)) # Calculating the softmax function array([ nan, nan, nan]) # Not calculated correctly
c = np.max(a) # 1010 a - c array([ 0, -10, -20])
np.exp(a - c) / np.sum(np.exp(a - c)) array([ 9.99954600e-01, 4.53978686e-05, 2.06106005e-09])
As this example indicates, when the largest value of the input signals (c, here) is subtracted, you can calculate the function properly. Otherwise, nan (not a number: unstable) values are returned. Based on this description, we can implement the softmax function as follows:
def softmax(a): c = np.max(a) exp_a = np.exp(a - c) # Prevent an overflow sum_exp_a = np.sum(exp_a) y = exp_a / sum_exp_a return yCharacteristics of the Softmax Function
Section titled “Characteristics of the Softmax Function”You can use the softmax() function to calculate the output of the neural network, as follows:
>>> a = np.array([0.3, 2.9, 4.0])
y = softmax(a) print(y) [ 0.01821127 0.24519181 0.73659691] np.sum(y) 1.0
The softmax function outputs a real number between 0 and 1.0. The total of the outputs of the softmax function is 1. The fact that the total is 1 is an important characteristic of the softmax function as it means we can interpret the output of the softmax function as “probability.”
For instance, in the preceding example, we could interpret the probability of y[0] as 0.018 (1.8%), the probability of y[1] as 0.245 (24.5%), and the probability of y[2] as 0.737 (73.7%). From these probabilities, we can say, “because the second element is the most probable, the answer is the second class.” We can even answer probabilistically: “the answer is the second class with a probability of 74%, the first class with a probability of 25%, and the zeroth class with a probability of 1%.” Thus, you can use the softmax function to handle a problem probabilistically (statistically).
We should note that applying the softmax function does not change the order of the elements. This is because an exponential function, (y = exp(x)), increases monotonically. Actually, in the preceding example, the order of the elements in a is the same as those of the elements in y. The largest value in a is the second element, and the largest value in y is also the second element.
Generally, class classification by a neural network recognizes only the class that corresponds to the neuron with the largest output. Using the softmax function does not change the position of the neuron of the largest output. Therefore, you can omit the softmax function for the output layer from neural network classification. In reality, the softmax function for the output layer is usually omitted because the exponential function requires some computation.
The procedure for solving a machine learning problem consists of two phases: “training” and “predicting.” First, you train a model in the training phase and then use the trained model to predict (classify) unknown data in the inference phase. As described earlier, the softmax function for the output layer is usually omitted in the inference phase. The reason we use the softmax function for the output layer will be relevant when the neural network trains (for more details, refer to the next chapter).
Number of Neurons in the Output Layer
Section titled “Number of Neurons in the Output Layer”You must determine the number of neurons in the output layer as appropriate, depending on the problem to solve. For classification problems, the number of classes to classify is usually used as the number of neurons in the output layer. For example, to predict a number from 0 to 9 from an input image (10-class classification), 10 neurons are placed in the output layer, as shown in Figure 3.23:

Figure 3.23: The neuron in the output layer corresponds to each number
Section titled “Figure 3.23: The neuron in the output layer corresponds to each number”As shown in Figure 3.23, the neurons in the output layer correspond to the numbers 0, 1, …, 9 from the top. Here, the various shades of gray represent the values of the neurons in the output layer. In this example, the color of y2 is the darkest because the y2 neuron outputs the largest value. It shows that this neural network predicts that the input belongs to the class that corresponds to y2; that is, “2.”
Bookmark
Handwritten Digit Recognition
Section titled “Handwritten Digit Recognition”Now that we have covered the mechanisms of a neural network, let’s consider a practical problem. We will classify some handwritten digit images. Assuming that training has already been completed, we will use trained parameters to implement “inference” in the neural network. This inference is also called forward propagation in a neural network.
In the same way as the procedure for solving a machine learning problem (which consists of two phases, “training” and “inference”), to solve a problem using a neural network, we will use training data to train the weight parameters and then use the trained parameters while predicting to classify the input data.
MNIST Dataset
Section titled “MNIST Dataset”Here, we will use a set of images of handwritten digits called MNIST. MNIST is one of the most famous datasets in the field of machine learning and is used in various ways, from simple experiments to research. When you read research papers on image recognition or machine learning, you will often notice that the MNIST dataset is used as experimental data.
The MNIST dataset consists of images of numbers from 0 to 9 (Figure 3. 24). It contains 60,000 training images and 10,000 test images, and they are used for training and inference. When we use the MNIST dataset, we usually use training images for training and measure how correctly the trained model can classify the test images:

Figure 3.24: Examples from the MNIST image dataset
Section titled “Figure 3.24: Examples from the MNIST image dataset”MNIST’s image data is a 28x28 gray image (one channel), and each pixel has a value from 0 to 255. Each image data is labeled, such as “7”, “2”, and “1.”
This book provides a convenient Python script, mnist.py, which is located in the dataset directory. It supports downloading the MNIST dataset and converting image data into NumPy arrays. To use the mnist.py script, the current directory must be the ch01, ch02, ch03, …, or ch08 directory. By using the load_mnist() function in mnist.py, you can load the MNIST data easily, as follows:
import sys, ossys.path.append(os.pardir) # Configure to import the files in the parent directory
from dataset.mnist import load_mnist# Waits for a few minutes for the first call ...(x_train, t_train), (x_test, t_test) = ∖
load_mnist(flatten=True, normalize=False)# Output the shape of each dataprint(x_train.shape) # (60000, 784)print(t_train.shape) # (60000,)print(x_test.shape) # (10000, 784)print(t_test.shape) # (10000,)First, configure the details for importing the files in the parent directory. Then, import the load_mnist function from dataset/mnist.py. Finally, use the imported load_mnist function to load the MNIST dataset. When you call load_mnist for the first time, an internet connection is required to download the MNIST data. A subsequent call completes immediately because it only loads the locally saved files (pickle files).
The files for loading the MNIST images exist in the dataset directory of the source code provided in this book. It is assumed that this MNIST dataset is used only from the ch01, ch02, ch03, …, or ch08 directory. Therefore, to use the dataset, the sys.path.append(os.pardir) statement is required. This is because the files in the parent directory (dataset directory) must be imported.
The load_mnist function returns the loaded MNIST data in the format of (training image, training label), (test image, test label). It can take three arguments: load_mnist(normalize=True, flatten=True, one_hot_label=False). The first argument, normalize, specifies whether to normalize the input image between 0.0 and 1.0. If False is set, the pixel of the input image remains between 0 and 255. The second argument, flatten, specifies whether to flatten the input image (convert it into a one-dimensional array). If False is set, the input image is stored as an array with three dimensions (1 × 28 × 28). If True is set, it is stored as a one-dimensional array with 784 elements. The third argument, one_hot_label, specifies whether to store the label using one-hot encoding. In a one-hot encoded array, only the element for the correct label is 1 and the other elements are 0, such as in [0,0,1,0,0,0,0,0,0,0]. When one_hot_label is False, only the correct label, such as 7 or 2, is stored. If one_hot_label is True, the labels are stored as a one-hot encoded array.
Python has a convenient feature called pickle, which saves objects as files while a program is being executed. By loading the saved pickle file, you can immediately restore the object that was used during the execution of the program. The load_mnist() function, which loads the MNIST dataset, also uses pickle (for the second or subsequent loading phases). By using pickle’s feature, you can prepare the MNIST data quickly.
Now, let’s display MNIST images to check the data. We will use the Python Image Library (PIL) module to display the images. When you execute the following code, the first training image will be displayed, as shown in Figure 3.25 (the source code is located at ch03/mnist_show.py):
import sys, ossys.path.append(os.pardir)import numpy as npfrom dataset.mnist import load_mnistfrom PIL import Imagedef img_show(img): pil_img = Image.fromarray(np.uint8(img)) pil_img.show()(x_train, t_train), (x_test, t_test) = /
load_mnist(flatten=True, normalize=False) img = x_train[0] label = t_train[0] print(label) # 5 print(img.shape) # (784,) img = img.reshape(28, 28) # Reshape the image based on the original size print(img.shape) # (28, 28) img_show(img)This results in the following output:

Figure 3.25: Displaying an MNIST image
Section titled “Figure 3.25: Displaying an MNIST image”Please note that when flatten=True, the loaded image is stored as a NumPy array in a line (one-dimensionally). Therefore, to display the image, you must reshape it into its original 28x28 size. You can use the reshape() method to reshape a NumPy array by specifying the desired shape with an argument. You must also convert the image data stored as a NumPy array into the data object for PIL. You can use Image.fromarray() for this conversion.
Inference for Neural Network
Section titled “Inference for Neural Network”Now, let’s implement a neural network that predicts over this MNIST dataset. The network consists of an input layer containing 784 neurons and an output layer containing 10 neurons. The number 784 for the input layer comes from the image size (28 x 28 = 784), while the number 10 for the output layer comes from 10-class classification (10 classes of numbers 0 to 9). There are two hidden layers: the first one has 50 neurons, and the second one has 100 neurons. You can change the numbers 50 and 100 as you like. First, let’s define the three functions, get_data(), init_network(), and predict() (the following source code is located at ch03/neuralnet_mnist.py):
def get_data(): (x_train, t_train), (x_test, t_test) = / load_mnist(normalize=True, flatten=True, one_hot_label=False) return x_test, t_testdef init_network(): with open("sample_weight.pkl", 'rb') as f: network = pickle.load(f) return networkdef predict(network, x): W1, W2, W3 = network['W1'], network['W2'], network['W3'] b1, b2, b3 = network['b1'], network['b2'], network['b3'] a1 = np.dot(x, W1) + b1 z1 = sigmoid(a1) a2 = np.dot(z1, W2) + b2 z2 = sigmoid(a2) a3 = np.dot(z2, W3) + b3 y = softmax(a3) return yThe init_network() function loads the trained weight parameters that are stored in the pickle file sample_weight.pkl. This file contains weight and bias parameters as a dictionary type variable. The remaining two functions are almost the same as in the implementations described so far, so these don’t need to be described. Now, we will use these three functions to predict using a neural network. We want to evaluate the recognition precision—that is, how correctly it can classify:
x, t = get_data()network = init_network()accuracy_cnt = 0for i in range(len(x)): y = predict(network, x[i]) p = np.argmax(y) # Obtain the index of the most probable element if p == t[i]: accuracy_cnt += 1print("Accuracy:" + str(float(accuracy_cnt) / len(x)))Here, we will obtain the MNIST dataset and build a network, then use a for statement to get each image data stored in x and use the predict() function to classify it. The predict() function returns a NumPy array containing the probability of each label. For example, an array such as [0.1, 0.3, 0.2, …, 0.04] is returned, which indicates that the probability of “0” is 0.1, that of “1” is 0.3, and so on. The index with the largest value in this probability list, which indicates the most probable element, is obtained as the prediction result. You can use np.argmax(x) to obtain the index of the largest element in an array. It returns the index of the largest element in the array specified by the x argument. Finally, the answers predicted by the neural network and the correct labels are compared, and the rate of correct predictions is displayed as the recognition precision (accuracy).
When the preceding code is executed, Accuracy:0.9352 is displayed. This shows that 93.52% of the classifications were correct. We will not discuss the recognition accuracy here as our goal is to run a trained neural network, but later in this book, we will improve the structure and training method of the neural network to gain higher recognition accuracy. In fact, the accuracy will exceed 99%.
In this example, the argument of the load_mnist function, normalize, is set to True. When normalize is True, the function divides the value of each pixel in the image by 255 so that the data values are between 0.0 and 1.0. Converting data so that it fits in a certain range is called normalization, while converting the input data for a neural network in a defined way is called pre-processing. Here, the input image data was normalized as pre-processing.
In practical usage, pre-processing is often used in a neural network (deep learning). The validity of pre-processing, as in improved discrimination and faster learning, has been proven through experiments. In the preceding example, simple normalization was conducted by dividing the value of each pixel by 255 using pre-processing. Actually, pre-processing is often conducted while considering the distribution of the whole data. Normalization is conducted by using the average and standard deviation of the whole data so that all of the data is distributed around 0 or fits in a certain range. In addition, whitening is also conducted so that all the data is distributed more evenly.
Batch Processing
Section titled “Batch Processing”This process is all about implementing a neural network using the MNIST dataset. Here, we will re-examine the preceding implementation while paying attention to the “shapes” of the input data and weight parameters.
Let’s use the Python interpreter to output the shape of the weights for each layer in the preceding neural network:
>>> x, _ = get_data( )
network = init_network( ) W1, W2, W3 = network[‘W1’], network[‘W2’], network[‘W3’]
x.shape (10000, 784) x[0].shape (784,) W1.shape (784, 50) W2.shape (50, 100) W3.shape (100, 10)
Let’s check that the number of elements in the corresponding dimensions of the multidimensional arrays are the same as they are in the preceding result (biases are omitted). Figure 3.26 shows this graphically. Here, the number of elements in the corresponding dimensions of the multidimensional arrays are the same. Verify that a one-dimensional array with 10 elements, y, is returned as the final result:

Figure 3.26: Transition of the shapes of arrays
Section titled “Figure 3.26: Transition of the shapes of arrays”Figure 3.26 shows the flow where a one-dimensional array with 784 elements (originally a two-dimensional 28x28 array) is provided, and a one-dimensional array with 10 elements is returned. This is the process when a single image is input.
Now, let’s think about the process when multiple images are entered at once. For example, let’s assume that you want to use the predict() function to process 100 images at one time. To do that, you can change the shape of x to 100×784 so that you can enter 100 images collectively as input data. Figure 3.27 shows this graphically:

Figure 3.27: Transition of the shapes of arrays in batch processing
Section titled “Figure 3.27: Transition of the shapes of arrays in batch processing”As shown in Figure 3.27, the shape of the input data is 100x784, and that of the output data is 100x10. This indicates that the results for the input data of 100 images are returned in one go. For example, x[0] and y[0] store the image and predict the result of the 0th image, x[1], and y[1] store the image and predicting the result of the first image, and so on.
An organized set of input data, as described here, is called a batch. A batch is a stack of images, such as a wad of bills.
Batch processing has a big advantage in computer calculation. It can greatly reduce the processing time of each image since many of the libraries that handle numerical calculations are highly optimized so that large arrays can be calculated efficiently. When data transfer causes a bottleneck in neural network calculation, batch processing can reduce the load on the bus band (i.e.: the ratio of operations to data loading can be increased). Although batch processing requires a large array to be calculated, calculating a large array in one go is faster than calculating by dividing small arrays little by little.
Now, let’s use batch processing for our implementation. Here, the differences from the previous code are shown in bold:
batch_size = 100 # Number of batchesNow, we will describe each section shown in bold. First, let’s look at the range() function. You can use the range() function, such as range(start, end), to generate a list of integers from start to end-1. By specifying three integers, as in range(start, end, step), you can generate a list of integers where values are incremented by the value specified with the step, as in the following example:
>>> list( range(0, 10) ) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list( range(0, 10, 3) ) [0, 3, 6, 9]
Based on the list returned by the range() function, x[i:i+batch_size] is used to extract a batch from the input data. x[i:i+batch_n] obtains from the i-th to i+batch_n-th data in the input data. In this example, 100 items of data are obtained from the beginning, such as x[0:100], x[100:200], …
Then, argmax() obtains the index of the largest value. Please note that an argument, axis=1, is specified here. It indicates that, in a 100x10 array, the index of the largest value is found among the elements in dimension 1 (the axis is almost the same as the dimension), as shown below:
>>> x = np.array([[0.1, 0.8, 0.1], [0.3, 0.1, 0.6], … [0.2, 0.5, 0.3], [0.8, 0.1, 0.1]])
y = np.argmax(x, axis=1) print(y) [1 2 1 0]
Lastly, the classification results for each batch are compared with the actual answers. To do that, a comparison operator (==) is used to compare the NumPy arrays. A Boolean array of True/False is returned, and the number of Trues is calculated, as follows:
>>> y = np.array([1, 2, 1, 0])
t = np.array([1, 2, 0, 0]) print(y==t) [True True False True] np.sum(y==t) 3
That’s it for implementation using batch processing. Batch processing enables fast and efficient processing. When we learn about neural networks in the next chapter, batches of image data will be used for training. There, we will also build an implementation of batch processing, just like we did in this chapter.
Bookmark
Summary
Section titled “Summary”This chapter described forward propagation in a neural network. The neural network we explained in this chapter is the same as a perceptron in the previous chapter in that the signals of the neurons are transmitted hierarchically. However, a large difference exists in the activation functions that change signals when they are transmitted to the next neurons. As an activation function, a neural network uses a sigmoid function, which changes signals smoothly, and a perceptron uses a step function, which changes signals sharply. This difference is important in neural network training and will be described in the next chapter. This chapter covered the following points:
- A neural network uses a function that changes smoothly, such as a sigmoid function or a ReLU function, as an activation function.
- By using NumPy’s multidimensional arrays, you can implement a neural network efficiently.
- Machine learning problems can be broadly divided into classification problems and regression problems.
- When using the activation function for the output layer, an identity function is often used for a regression problem, and a softmax function is used for a classification problem.
- For a classification problem, the number of classes to classify is used as the number of neurons in the output layer.
- A set of input data is called a batch. Predicting per batch accelerates the calculation process.










