Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Basic Structure of Neural Networks

Basic Structure of Neural Networks

In the wave of artificial intelligence, deep learning is undoubtedly the most dazzling star, and what forms the core of deep learning is preciselyNeural networks. It mimics the way neurons in the human brain work, and through layer-by-layer connections and computations, endows machines with the ability to learn and cognize.

For beginners, understanding the basic structure of neural networks is the first key to opening the door to deep learning.

This article will take you from scratch, step by step dissecting the composition of neural networks, and use vivid analogies and clear code to help you fully master how they work.


What is a neural network? A vivid analogy

Imagine you are teaching a child who has never seen cats or dogs to distinguish them—what would you do?

  1. You might first show him many pictures of cats and dogs.
  2. You would point out features: look, a cat's ears are usually pointed and its face is rounder; a dog's ears may droop and its face is longer.
  3. The child's brain (neural network) receives these pictures (input data) and your guidance (labels).
  4. The neurons in his brain start working, trying to find the key patterns that distinguish cats from dogs (such as ear shape and face shape).
  5. After many corrections and learning, a judgment model forms in his brain. The next time he sees a new animal picture, he can confidently say "this is a cat" or "this is a dog".

A neural network is a simplified mathematical model of this child's brain, it is a network system composed of a large number ofartificial neuronsinterconnected with each other, able to automatically learn features and patterns from input data and use them for prediction or decision-making.


The basic building block of neural networks: the neuron

The neuron is the most basic computational unit of a neural network; it simulates the process by which a biological neuron receives signals—processes signals—transmits signals.

The workflow of a neuron

A typical artificial neuron mainly does three things:

Example

This is the pseudocode logic of a neuron's computation to help you understand the process

def

artificial_neuron

(

inputs

,

weights

,

bias

)

:

   

"""
    Simulate the computation process of an artificial neuron.
    Parameters:
        inputs: list of input signals, e.g. [x1, x2, x3]
        weights: list of weights corresponding to each input, e.g. [w1, w2, w3]
        bias: the bias term, a constant
    Returns:
        output: the neuron's output
    """

   

1. Weighted sum: multiply each input by its corresponding weight, then add the bias

    weighted_sum

=

0

   

for

i

in

range

(

len

(

inputs

)

)

:

        weighted_sum +

=

inputs

[

i

]

[

i

]

    weighted_sum +

=

bias

   

2. Activation function processing: through a nonlinear function, decide whether to "activate" and output a signal

    output

=

activation_function

(

weighted_sum

)

   

return

output

Let's use a diagram and a table to understand more intuitively:

Detailed explanation of the functions of each part of a neuron:

parts Analogy Mathematical Expression Purpose
Input (x) Signals from other neurons ( x_1, x_2, ..., x_n ) Receives external information or the output of neurons in the previous layer.
Weight (w) The importance of a signal (w_1, w_2, ..., w_n) Determines how much each input affects the neuron's output.The learning process is the process of continuously adjusting these weights.
Bias (b) The activation threshold of the neuron (b) A constant used to adjust how easily a neuron activates. It can be understood as shifting the weighted sum up or down as a whole.
Weighted sum (z) Total signal strength (z = (x_1w_1 + x_2w_2 + ... + x_nw_n) + b) Combines all input signals.
Activation function (f) Switch and processor (a = f(z)) Introduced innon-linear. Without it, a multi-layer network would degenerate into a single-layer network, unable to learn complex patterns.

Common activation functions

Activation functions bring nonlinear capability to neural networks. The following are the three most commonly used:

  1. Sigmoid

  2. Formula:\(f(z) = \frac{1}{1 + e^{-z}}\)
  3. Feature: Compresses inputs into the range (0, 1). Often used in the output layer for binary classification problems. Prone to the vanishing gradient problem.
  4. Image: A smooth S-shaped curve.
  5. - **Formula**: \(f(z) = \frac{1}{1 + e^{-z}}\) - **Features**: Compresses inputs into the range (0, 1). Often used in the output layer for binary classification problems. Prone to the vanishing gradient problem. - **Graph**: A smooth S-shaped curve.
    1. ReLU (Rectified Linear Unit)

    2. Formula:\(f(z) = max(0, z)\)
    3. Feature: Simple to compute, effectively alleviates the vanishing gradient problem, and is currently the most commonly used hidden-layer activation function.
    4. Image: A polyline that bends at the origin, outputting 0 for negatives and passing positives through unchanged.
    5. - **Formula**: \(f(z) = max(0, z)\) - **Features**: Simple to compute, effectively alleviates the vanishing gradient problem, and is currently the most commonly used hidden-layer activation function. - **Graph**: A polyline that bends at the origin, outputting 0 for negatives and passing positives through unchanged.
      1. Softmax

      2. Formula:\(f(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}}\)
      3. Feature: Converts the outputs of multiple neurons into a probability distribution (all outputs sum to 1).Specially used in the output layer for multi-class classification problems。
      4. - **Formula**: \(f(z_i) = \frac{e^{z_i}}{\sum_{j=1}^{K} e^{z_j}}\) - **Features**: Converts the outputs of multiple neurons into a probability distribution (all outputs sum to 1). **Specially used in the output layer for multi-class classification problems**.

        The layered structure of neural networks

        A single neuron has limited capability, just as a single brain cell cannot think. When we organize a large number of neurons into layers, we form a powerful neural network. A typical neural network contains the following three layers:

        1. Input layer

        2. Hidden layer

        Role: The brain of the network, responsible for complex feature extraction and transformation.

        Feature:

        3. Output layer

        Role: The decision-maker of the network, outputting the final prediction result.

        Feature: The number of neurons is determined by the task.

        Diagram:

        ** Input layer

        ** Hidden layer

        ** Output layer

        ** Weighted connections

        ** Activation signals


        Hands-on: Building a neural network with Python

        No amount of theory beats hands-on practice. Below we use the NumPy library to build the simplest three-layer neural network (with 1 hidden layer) from scratch and perform a forward propagation computation.

        Example

        import

        numpy

        as

        np

        Define activation functions

        def

        sigmoid

        (

        x

        )

        :

           

        """Sigmoid activation function"""

           

        return

        1

        /

        (

        1

        exp

        (

        -x

        )

        )

        def

        relu

        (

        x

        )

        :

           

        """ReLU activation function"""

           

        return

        np.

        maximum

        (

        0

        ,

        x

        )

        Initialize a simple neural network

        def

        initialize_network

        (

        input_size

        ,

        hidden_size

        ,

        output_size

        )

        :

           

        """
            Initialize the network's weights and biases.
            Parameters:
                input_size: number of neurons in the input layer
                hidden_size: number of neurons in the hidden layer
                output_size: number of neurons in the output layer
            Returns:
                network: a dictionary containing the parameters of each layer
            """

            np.

        random

        .

        seed

        (

        42

        )

         

        Set the random seed to ensure consistent results across runs

            network

        =

        {

        }

           

        Initialize the parameters from the input layer -> hidden layer

           

        Weight matrix shape: (number of neurons in the next layer, number of neurons in the previous layer)

            network

        [

        'W1'

        ]

        =

        np.

        random

        .

        randn

        (

        hidden_size

        ,

        input_size

        )

        0.01

            network

        [

        'b1'

        ]

        =

        np.

        zeros

        (

        (

        hidden_size

        ,

        1

        )

        )

         

        The bias is a column vector

           

        Initialize the parameters from the hidden layer -> output layer

            network

        [

        'W2'

        ]

        =

        np.

        random

        .

        randn

        (

        output_size

        ,

        hidden_size

        )

        0.01

            network

        [

        'b2'

        ]

        =

        np.

        zeros

        (

        (

        output_size

        ,

        1

        )

        )

           

        return

        network

        Forward propagation function

        def

        forward_propagation

        (

        network

        ,

        X

        )

        :

           

        """
            Perform forward propagation and compute the network output.
            Parameters:
                network: a dictionary containing weights and biases
                X: input data, shaped as (number of features, number of samples)
            Returns:
                y_pred: the network's predicted output
                cache: caches intermediate results (for later backpropagation)
            """

           

        Retrieve parameters

            W1

        ,

        b1

        ,

        W2

        ,

        b2

        =

        network

        [

        'W1'

        ]

        ,

        network

        [

        'b1'

        ]

        ,

        network

        [

        'W2'

        ]

        ,

        network

        [

        'b2'

        ]

           

        Layer 1 computation: input layer -> hidden layer

            Z1

        =

        np.

        dot

        (

        W1

        ,

        X

        )

        Weighted sum

            A1

        =

        relu

        (

        Z1

        )

                   

        Pass through the ReLU activation function

           

        Layer 2 computation: hidden layer -> output layer

            Z2

        =

        np.

        dot

        (

        W2

        ,

        A1

        )

        Weighted sum

            A2

        =

        sigmoid

        (

        Z2

        )

               

        Pass through the Sigmoid activation function (assuming binary classification)

           

        Cache intermediate results, which will be used during backpropagation

            cache

        =

        {

        'Z1'

        : Z1

        ,

        'A1'

        : A1

        ,

        'Z2'

        : Z2

        ,

        'A2'

        : A2

        }

           

        return

        A2

        ,

        cache

        --- Let's run it! ---

        1. Define the network structure: 2 input features, 3 hidden neurons, 1 output (binary classification)

        input_size

        =

        2

        hidden_size

        =

        3

        output_size

        =

        1

        2. Initialize the network

        my_network

        =

        initialize_network

        (

        input_size

        ,

        hidden_size

        ,

        output_size

        )

        print

        (

        "Shape of weight W1 (hidden layer x input layer):"

        ,

        my_network

        [

        'W1'

        ]

        .

        shape

        )

        print

        (

        "Shape of bias b1:"

        ,

        my_network

        [

        'b1'

        ]

        .

        shape

        )

        print

        (

        "Shape of weight W2 (output layer x hidden layer):"

        ,

        my_network

        [

        'W2'

        ]

        .

        shape

        )

        3. Create a sample input data (2 features, 1 sample)

        Columns of X represent samples, rows represent features

        X_sample

        =

        np.

        array

        (

        [

        [

        1.5

        ]

        ,

        [

        0.5

        ]

        ]

        )

         

        Shape (2, 1)

        print

        (

        "\nInput data X:"

        ,

        X_sample.

        T

        )

        .T is for transposing the printout for easier viewing

        4. Perform forward propagation

        y_pred

        ,

        cache

        =

        forward_propagation

        (

        my_network

        ,

        X_sample

        )

        print

        (

        "\nNeural network predicted output (A2):"

        ,

        y_pred

        )

        If the output > 0.5, we can consider it class 1, otherwise class 0

        predicted_class

        =

        1

        if

        y_pred

        0.5

        else

        0

        print

        (

        f

        "Predicted class: {predicted_class}"

        )

        Code explanation and output analysis:

        Initialization: We created a network with a 2-3-1 structure.W1 is a 3x2 matrix representing the connection weights from 2 inputs to 3 hidden neurons.

        Forward propagation:

        Output: Since the weights are randomly initialized, this untrained network's predicted output A2 is also a random value (close to 0.5).The purpose of training a neural network is to repeatedly adjust W1, b1, W2, b2through large amounts of data, so that A2 produces meaningful predictions for different inputs.


        Summary of core concepts and learning path

        Through this article, you have mastered the cornerstones of neural networks:

        Concept Key points
        Neuron The computational unit, completing加权求和 -> 加偏置 -> 激活函数。
        Weights and biases The core parameters the model needs to learn, determining the network's behavior.
        Activation function Introduces nonlinearity (such as ReLU, Sigmoid), enabling the network to learn complex relationships.
        Network layers Input layer(receives data),Hidden layer(feature extraction),Output layer(produces predictions).
        Forward propagation The process in which data flows from the input layer to the output layer, computing the predicted value.

        Your next steps in learning:

        1. Loss function: How to quantify the goodness of a network's predictions (such as mean squared error, cross-entropy loss)?
        2. Backpropagation and gradient descent: How does a neural network automatically adjust weights and biases according to the degree of "badness" (this is the essence of learning)?
        3. Hands-on with frameworks: replace the current signal mask with TensorFlow or PyTorch and other modern frameworks make it easy to build and train more complex networks without writing from scratch NumPy codes.

        After understanding the basic structure, you will find that all complex deep learning models (such as CNN for images, RNN for speech) evolved from this basic structure by changing the connection patterns of neurons and the functions of layers. Now, you possess the map to continue exploring the vast world of deep learning.

        Linux Command Reference Linux Command Reference