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

Deep Reinforcement Learning

Deep Reinforcement Learning

Deep reinforcement learning is an exciting interdisciplinary direction in the field of artificial intelligence; we can break it down into two parts to understand it:

Reinforcement Learning is the core idea; it simulates the process by which humans or animals learn through "trial and error." Imagine teaching a puppy a new command: when it does something right, you give it a treat as a reward; when it does something wrong, there is no reward and perhaps even a slight punishment. After many attempts, the puppy learns to make the correct action in a specific situation in order to obtain the reward. The agent in reinforcement learning is like this puppy: through interaction with the environment, it adjusts its own behavior policy according to the rewards it receives.

Deep learning is a powerful tool. When the environment faced by reinforcement learning is very complex (such as video game screens or robot sensor data), traditional mathematical methods struggle to directly extract useful features from it for decision-making. Deep learning, especially deep neural networks, excels at handling this kind of high-dimensional, complex raw data (such as images and sound), and can automatically learn hierarchical feature representations of the data.

Therefore,Deep reinforcement learning = the decision-making framework of reinforcement learning + the perception and representation capabilities of deep learning. It enables the agent to learn directly from complex raw inputs (such as pixels) how to take optimal actions in order to achieve long-term goals.


Core Concepts and Basic Framework

To understand deep reinforcement learning, one must first grasp several core roles in its basic framework and the relationships between them.

Basic Elements of Reinforcement Learning

  1. Agent

  2. Role: The learner and decision-maker.
  3. Responsibility: Observes the state of the environment, selects an action according to the learned policy, executes the action, and receives feedback from the environment (a new state and a reward).
  4. - **Role**: The learner and decision-maker. - **Responsibility**: Observes the state of the environment, selects an action according to the learned policy, executes the action, and receives feedback from the environment (a new state and a reward).
    1. Environment

    2. Role: Everything external with which the agent interacts.
    3. Responsibility: Receives the agent's actions, updates its own state, and gives the corresponding reward.
    4. - **Role**: Everything external with which the agent interacts. - **Responsibility**: Receives the agent's actions, updates its own state, and gives the corresponding reward.
      1. State (s)

      2. define: A description of the specific situation of the environment at a certain moment. In deep reinforcement learning, states are usually high-dimensional, such as a single frame of a game image.
      3. - **Definition**: A description of the specific situation of the environment at a certain moment. In deep reinforcement learning, states are usually high-dimensional, such as a single frame of a game image.
        1. Action (a)

        2. define: The choices the agent can make in a given state. For example, in a game, these might be "up," "left," "fire," and so on.
        3. - **Definition**: The choices the agent can make in a given state. For example, in a game, these might be "up," "left," "fire," and so on.
          1. Reward (r)

          2. define: The immediate feedback signal from the environment to the agent's action, a scalar value. Reward is the "compass" for the agent's learning, whose goal is to maximize the long-term cumulative reward.
          3. - **Definition**: The immediate feedback signal from the environment to the agent's action, a scalar value. Reward is the "compass" for the agent's learning, whose goal is to maximize the long-term cumulative reward.
            1. Policy (π)

            2. define: The agent's code of behavior, a mapping function from states to actions. It tells the agent what action to take in a given state. A policy can be deterministic (a = π(s)), or stochastic (a ~ π(a|s))。
            3. - **Definition**: The agent's code of behavior, a mapping function from states to actions. It tells the agent what action to take in a given state. A policy can be deterministic (`a = π(s)`), or stochastic (`a ~ π(a|s)`).
              1. Value Function

              2. define: Used to evaluate the goodness of a state or a state-action pair. It represents the future cumulative reward that can be obtained starting from the current state (or after executing the current action)expected cumulative reward。
              3. State Value Function V(s): In state s , the expected return that can be obtained by following the current policy.
              4. Action Value Function Q(s, a): In state s , executing action a, and then following the current policy to obtain the expected return.
              5. - **Definition**: Used to evaluate the goodness of a state or a state-action pair. It represents the **expected cumulative reward** that can be obtained starting from the current state (or after executing the current action). - **State value function V(s)**: In state `s`, the expected return that can be obtained by following the current policy. - **Action value function Q(s, a)**: In state `s`, executing action `a`, and then following the current policy to obtain the expected return.

                Interaction Process

                The interaction between the agent and the environment is a continuous cyclic process, which can be clearly represented by the following flowchart:

                This cycle repeats continuously; the agent collects a large amount of interaction data (s, a, r, s') and uses this data to improve its own policy.


                Main Algorithms of Deep Reinforcement Learning

                The family of deep reinforcement learning algorithms is mainly divided into two major categories:Value-Based and Policy-Based, and one that combines the advantages of both: Actor-Critic method.

                1. Value-Based Deep Q-Networks

                The core of this type of algorithm is to learn the optimal Action Value Function Q(s, a). Once an accurate Q function has been learned, the optimal policy is simple: in each state s , choose the action that yields the Q(s, a) largest Q value a。

                Deep Q-Network (DQN) is a landmark piece of work. It uses a deep neural network to approximate the complex Q function.

                Key Technical Innovations of DQN:

                A Simplified DQN Training Procedure:

                1. Initialize the online network Q and the target network Q_target(with identical parameters), and clear the experience replay buffer.
                2. The agent, according to the current state s, randomly with a certain probability or according to the Q network, selects an action a。
                3. Executes the action; the environment returns the reward r and the new state s', and stores the experience (s, a, r, s') in the replay buffer.
                4. Randomly sample a batch of experiences from the replay buffer.
                5. For each sample, compute the target Q value:y = r + γ * max_a' Q_target(s', a'). Among them, γ γ is the discount factor, used to balance immediate and future rewards.
                6. Starts with (y - Q(s, a))^2 As the loss, update the online network via gradient descent Q 's parameter.
                7. Every certain number of steps, copy the parameters of the online network to the target network.
                8. Repeat steps 2-7.

                Advantages and Limitations:

                2. Policy-Based Policy Gradient Methods

                These methods directly parametrize the policy π(a|s; θ)(for example, represented by a neural network), and by optimizing the policy parameters θ to directly maximize the expected return.

                Core idea: By computing the gradient of the expected return J(θ) with respect to the policy parameters θ (i.e., the policy gradient), and then updating the parameters along the gradient direction, making the policy better and better.

                The REINFORCE Algorithm is a classic policy gradient algorithm. Its update formula is: θ ← θ + α * ∇_θ log π(a|s; θ) * G_t where G_t is the cumulative reward from the current moment to the end of the episode,α is the learning rate.

                Advantages and Limitations:

                3. Actor-Critic Methods

                The actor-critic framework cleverly combines value-based and policy-based methods, drawing on each other's strengths.

                Workflow:

                1. The actor, according to the current state s and its own policy, selects and executes an action a。
                2. The environment feeds back the reward r and the new state s'。
                3. The critic, based on (s, a, r, s') , computes the TD error (Temporal-Difference Error, a signal that measures the difference between predicted and actual value).
                4. The critic uses this error to update its own value-evaluation network, making its scoring more accurate.
                5. The actor uses the "score" provided by the critic (such as the TD error or an advantage function) to update its own policy network, making itself more inclined to choose actions that receive high scores.

                Advantage: Actor-critic methods generally have lower variance and are more stable than pure policy gradient methods (such as REINFORCE), while also being better at handling continuous actions and stochastic policies than pure value-based methods (such as DQN).A3C, A2C, PPO, SAC are all highly successful actor-critic algorithms.


                Practice: Playing the CartPole Game with DQN

                Let's use a classic control problem CartPole(pole balancing) to gain an intuitive feel for DQN. In this environment, the cart can move left and right, and the goal is to keep the pole on the cart upright without falling.

                Environment setup

                We use OpenAI Gym, a reinforcement learning toolkit.

                Example

                Install the necessary libraries (run in Jupyter Notebook or on the command line)

                !pip install gym numpy torch

                import

                gym

                import

                numpy

                as

                np

                import

                random

                import

                torch

                import

                torch.

                nn

                as

                nn

                import

                torch.

                optim

                as

                optim

                import

                collections

                Create environment

                env

                =

                gym.

                make

                (

                'CartPole-v1'

                )

                state_dim

                =

                env.

                observation_space

                .

                shape

                [

                0

                ]

                 

                State dimensions: 4 (cart position, velocity, pole angle, angular velocity)

                action_dim

                =

                env.

                action_space

                .

                n

                           

                Action dimensions: 2 (left, right)

                print

                (

                f

                "State space dimension: {state_dim}, action space size: {action_dim}"

                )

                Define the Q-Network

                This is a simple fully connected neural network whose input is the state and whose output is the Q value corresponding to each action.

                Example

                class

                DQN

                (

                nn.

                Module

                )

                :

                   

                def

                init

                (

                self

                ,

                state_dim

                ,

                action_dim

                )

                :

                       

                super

                (

                DQN

                ,

                self

                )

                .

                init

                (

                )

                       

                self

                .

                fc1

                =

                nn.

                Linear

                (

                state_dim

                ,

                128

                )

                 

                First fully connected layer

                       

                self

                .

                fc2

                =

                nn.

                Linear

                (

                128

                ,

                128

                )

                       

                Second fully connected layer

                       

                self

                .

                fc3

                =

                nn.

                Linear

                (

                128

                ,

                action_dim

                )

                Output layer, one Q value per action

                   

                def

                forward

                (

                self

                ,

                x

                )

                :

                        x

                =

                torch.

                relu

                (

                self

                .

                fc1

                (

                x

                )

                )

                 

                Use the ReLU activation function to introduce nonlinearity

                        x

                =

                torch.

                relu

                (

                self

                .

                fc2

                (

                x

                )

                )

                       

                return

                self

                .

                fc3

                (

                x

                )

                         

                Output Q values without passing through an activation function

                Define the Experience Replay Buffer

                Used to store and sample past experiences.

                Example

                class

                ReplayBuffer:

                   

                def

                init

                (

                self

                ,

                capacity

                )

                :

                       

                self

                .

                buffer

                =

                collections

                .

                deque

                (

                maxlen

                =

                capacity

                )

                 

                A deque that automatically discards old experiences

                   

                def

                add

                (

                self

                ,

                state

                ,

                action

                ,

                reward

                ,

                next_state

                ,

                done

                )

                :

                       

                self

                .

                buffer

                .

                append

                (

                (

                state

                ,

                action

                ,

                reward

                ,

                next_state

                ,

                done

                )

                )

                   

                def

                sample

                (

                self

                ,

                batch_size

                )

                :

                        transitions

                =

                random

                .

                sample

                (

                self

                .

                buffer

                ,

                batch_size

                )

                       

                Organize the data into a tensor stacked by columns for easy batch processing by the neural network

                        state

                ,

                action

                ,

                reward

                ,

                next_state

                ,

                done

                =

                zip

                (

                *transitions

                )

                       

                return

                (

                np.

                array

                (

                state

                )

                ,

                action

                ,

                reward

                ,

                np.

                array

                (

                next_state

                )

                ,

                done

                )

                   

                def

                size

                (

                self

                )

                :

                       

                return

                len

                (

                self

                .

                buffer

                )

                Define the DQN Agent

                Integrates the network, experience replay, and training logic.

                Example

                class

                DQNAgent:

                   

                def

                init

                (

                self

                ,

                state_dim

                ,

                action_dim

                ,

                lr

                =

                1e-3

                ,

                gamma

                =

                0.98

                ,

                epsilon

                =

                0.01

                ,

                                 target_update_freq

                =

                10

                ,

                buffer_size

                =

                10000

                ,

                batch_size

                =

                64

                )

                :

                       

                self

                .

                action_dim

                =

                action_dim

                       

                self

                .

                q_net

                =

                DQN

                (

                state_dim

                ,

                action_dim

                )

                         

                Online network

                       

                self

                .

                target_q_net

                =

                DQN

                (

                state_dim

                ,

                action_dim

                )

                 

                Target network

                       

                self

                .

                target_q_net

                .

                load_state_dict

                (

                self

                .

                q_net

                .

                state_dict

                (

                )

                )

                Identical initial parameters

                       

                self

                .

                optimizer

                =

                optim.

                Adam

                (

                self

                .

                q_net

                .

                parameters

                (

                )

                ,

                lr

                =

                lr

                )

                Optimizer

                       

                self

                .

                gamma

                =

                gamma              

                Discount factor

                       

                self

                .

                epsilon

                =

                epsilon          

                Exploration rate (final)

                       

                self

                .

                target_update_freq

                =

                target_update_freq

                Target network update frequency

                       

                self

                .

                batch_size

                =

                batch_size

                       

                self

                .

                buffer

                =

                ReplayBuffer

                (

                buffer_size

                )

                       

                self

                .

                count

                =

                0

                                 

                Record the update step count

                   

                def

                take_action

                (

                self

                ,

                state

                ,

                epsilon

                =

                None

                )

                :

                       

                """Select an action according to the epsilon-greedy policy"""

                       

                if

                epsilon

                is

                None

                :

                            epsilon

                =

                self

                .

                epsilon

                       

                if

                np.

                random

                .

                random

                (

                )

                <

                epsilon:

                           

                return

                np.

                random

                .

                randint

                (

                self

                .

                action_dim

                )

                 

                Exploration: random selection

                       

                else

                :

                            state

                =

                torch.

                tensor

                (

                state

                ,

                dtype

                =

                torch.

                float

                )

                .

                unsqueeze

                (

                0

                )

                Add a batch dimension

                           

                with

                torch.

                no_grad

                (

                )

                :

                                q_values

                =

                self

                .

                q_net

                (

                state

                )

                           

                return

                q_values.

                argmax

                (

                )

                .

                item

                (

                )

                           

                Exploitation: choose the action with the largest Q value

                   

                def

                update

                (

                self

                )

                :

                       

                """Sample from the experience replay buffer and update the network"""

                       

                if

                self

                .

                buffer

                .

                size

                (

                )

                <

                self

                .

                batch_size

                :

                           

                return

                       

                1. Sampling

                        states

                ,

                actions

                ,

                rewards

                ,

                next_states

                ,

                dones

                =

                self

                .

                buffer

                .

                sample

                (

                self

                .

                batch_size

                )

                       

                Convert to a PyTorch tensor

                        states

                =

                torch.

                tensor

                (

                states

                ,

                dtype

                =

                torch.

                float

                )

                        actions

                =

                torch.

                tensor

                (

                actions

                )

                .

                unsqueeze

                (

                1

                )

                     

                The shape becomes [batch_size, 1] for easy gather operations

                        rewards

                =

                torch.

                tensor

                (

                rewards

                ,

                dtype

                =

                torch.

                float

                )

                .

                unsqueeze

                (

                1

                )

                        next_states

                =

                torch.

                tensor

                (

                next_states

                ,

                dtype

                =

                torch.

                float

                )

                        dones

                =

                torch.

                tensor

                (

                dones

                ,

                dtype

                =

                torch.

                float

                )

                .

                unsqueeze

                (

                1

                )

                       

                2. Compute the current Q value (Q(s, a))

                        current_q_values

                =

                self

                .

                q_net

                (

                states

                )

                .

                gather

                (

                1

                ,

                actions

                )

                 

                Extract only the Q value corresponding to the executed action a

                       

                3. Compute the target Q value (r + γ * max_a' Q_target(s', a'))

                       

                with

                torch.

                no_grad

                (

                )

                :

                            next_q_values

                =

                self

                .

                target_q_net

                (

                next_states

                )

                .

                max

                (

                1

                )

                [

                0

                ]

                .

                unsqueeze

                (

                1

                )

                Take the maximum Q value of the next state

                            target_q_values

                =

                rewards +

                self

                .

                gamma

                (

                1

                )

                If the episode ends (done=1), there is no future reward

                       

                4. Compute the loss (mean squared error)

                        loss

                =

                nn.

                MSELoss

                (

                )

                (

                current_q_values

                ,

                target_q_values

                )

                       

                5. Update the online network via gradient descent

                       

                self

                .

                optimizer

                .

                zero_grad

                (

                )

                        loss.

                backward

                (

                )

                       

                Optional: gradient clipping to prevent exploding gradients

                       

                torch.nn.utils.clip_grad_norm_(self.q_net.parameters(), max_norm=10)

                       

                self

                .

                optimizer

                .

                step

                (

                )

                       

                self

                .

                count

                =

                1

                       

                6. Periodically update the target network

                       

                if

                self

                .

                count

                %

                self

                .

                target_update_freq

                ==

                0

                :

                           

                self

                .

                target_q_net

                .

                load_state_dict

                (

                self

                .

                q_net

                .

                state_dict

                (

                )

                )

                Training loop

                Example

                def

                train_agent

                (

                env

                ,

                agent

                ,

                num_episodes

                =

                500

                ,

                max_steps

                =

                500

                ,

                initial_epsilon

                =

                0.9

                ,

                epsilon_decay

                =

                0.995

                )

                :

                   

                """Train the agent"""

                    return_list

                =

                [

                ]

                 

                Record the total reward for each episode

                    epsilon

                =

                initial_epsilon

                   

                for

                i_episode

                in

                range

                (

                num_episodes

                )

                :

                        state

                ,

                _

                =

                env.

                reset

                (

                )

                        episode_return

                =

                0

                        done

                =

                False

                       

                for

                step

                in

                range

                (

                max_steps

                )

                :

                           

                1. Select and execute an action

                            action

                =

                agent.

                take_action

                (

                state

                ,

                epsilon

                )

                 

                Use the decayed exploration rate

                            next_state

                ,

                reward

                ,

                done

                ,

                truncated

                ,

                _

                =

                env.

                step

                (

                action

                )

                           

                2. Store the experience

                            agent.

                buffer

                .

                add

                (

                state

                ,

                action

                ,

                reward

                ,

                next_state

                ,

                done

                )

                            state

                =

                next_state

                            episode_return +

                =

                reward

                           

                3. Update the network

                            agent.

                update

                (

                )

                           

                if

                done

                or

                truncated:

                               

                break

                       

                Exploration rate decay

                        epsilon

                =

                max

                (

                agent.

                epsilon

                ,

                epsilon * epsilon_decay

                )

                        return_list.

                append

                (

                episode_return

                )

                       

                if

                (

                i_episode +

                1

                )

                %

                50

                ==

                0

                :

                           

                print

                (

                f

                "Episode: {i_episode+1}, average reward (last 50 episodes): {np.mean(return_list[-50:]):.1f}, exploration rate: {epsilon:.3f}"

                )

                   

                print

                (

                "Training complete!"

                )

                   

                return

                return_list

                Create the agent and start training

                agent

                =

                DQNAgent

                (

                state_dim

                ,

                action_dim

                ,

                lr

                =

                1e-3

                ,

                gamma

                =

                0.99

                ,

                epsilon

                =

                0.01

                )

                returns

                =

                train_agent

                (

                env

                ,

                agent

                ,

                num_episodes

                =

                300

                )

                Test the trained agent

                Example

                def

                test_agent

                (

                env

                ,

                agent

                ,

                num_episodes

                =

                5

                ,

                render

                =

                True

                )

                :

                   

                """Test the agent's performance"""

                    total_rewards

                =

                [

                ]

                   

                for

                i

                in

                range

                (

                num_episodes

                )

                :

                        state

                ,

                _

                =

                env.

                reset

                (

                )

                        episode_return

                =

                0

                        done

                =

                False

                       

                while

                not

                done:

                           

                if

                render:

                                env.

                render

                (

                )

                 

                Visualize the environment; when running locally, you can see the cart balancing the pole

                            action

                =

                agent.

                take_action

                (

                state

                )

                 

                Use the minimum exploration rate during testing (i.e., pure exploitation)

                            next_state

                ,

                reward

                ,

                done

                ,

                truncated

                ,

                _

                =

                env.

                step

                (

                action

                )

                            state

                =

                next_state

                            episode_return +

                =

                reward

                           

                if

                done

                or

                truncated:

                               

                break

                        total_rewards.

                append

                (

                episode_return

                )

                       

                print

                (

                f

                "Test episode {i+1}: total reward = {episode_return}"

                )

                    env.

                close

                (

                )

                   

                print

                (

                f

                "Average test reward: {np.mean(total_rewards):.1f}"

                )

                Test the agent

                test_agent

                (

                env

                ,

                agent

                ,

                num_episodes

                =

                3

                ,

                render

                =

                False

                )

                Set render=False in a GUI-less environment


                Challenges and Future Directions of Deep Reinforcement Learning

                Despite its great success, deep reinforcement learning still faces many challenges:

                Future research is advancing in directions such as more efficient algorithms (e.g., model-based reinforcement learning), more powerful representation learning, multi-task and meta-learning, and safe alignment with the real world.


                Summary and Exercises

                Deep reinforcement learning combines the perceptual capabilities of deep learning with the decision-making framework of reinforcement learning, enabling machines to learn to accomplish advanced tasks in complex environments. You have learned its core concepts and main algorithm families, and gained hands-on experience through the DQN practice code.

                Exercises and Reflection:

                1. Modify the code: Try adjusting the DQNAgent hyperparameters in the code (such as lr, gamma, batch_size), and observe their impact on training speed and final performance.
                2. Change the Environment: Try applying the code to other environments in Gym, such as MountainCar-v0 or LunarLander-v2. Pay attention to adjusting the dimensions of the state and action.
                3. Algorithm Comparison: Read about and try to implement a simple policy gradient algorithm (such as REINFORCE) to solve the CartPole problem, and compare its differences from DQN in terms of training stability and sample efficiency.
                4. Further Exploration: Choose a modern advanced algorithm (such as PPO or SAC), read its paper or open-source implementation, and understand which problems in DQN or policy gradients it solves.