🤖 AI/ML

Reinforcement Learning

Reinforcement Learning

An ML approach in which an agent interacts with an environment and learns actions that maximize reward. Used in AlphaGo and robotics.

📖 Detailed Explanation

Reinforcement Learning (RL) is a machine learning paradigm in which an agent interacts with an environment and learns a behavioral policy that maximizes reward. Unlike supervised learning, it discovers the optimal behavioral strategy on its own through trial and error, without labeled correct answers.

Originating in the 1950s from inspiration drawn from animal behavioral psychology, reinforcement learning attracted attention in 2013 when DeepMind's DQN played Atari games at a human level. It became widely known when AlphaGo defeated the world Go champion in 2016, and its range of application has since expanded to robotics, autonomous driving, and even LLM alignment (RLHF).

The core concept of reinforcement learning is the MDP (Markov Decision Process). It consists of State, Action, Reward, and Transition Probability, and the agent selects an action in a state, receives a reward, and moves to the next state. Q-Learning, Policy Gradient, and Actor-Critic are representative algorithms.

Recently, RLHF (Reinforcement Learning from Human Feedback) has been used as a core technique for aligning LLMs with human preferences. Major LLMs such as ChatGPT and Claude are trained in this way, and the PPO (Proximal Policy Optimization) algorithm has become the standard.

💻 Code Example

This is a simple Q-Learning example using OpenAI Gym.

# pip install gymnasium numpy

import gymnasium as gym
import numpy as np

# CartPole 환경 생성
env = gym.make("CartPole-v1")

# Q-Table 초기화 (상태를 이산화하여 사용)
def discretize_state(state):
    bins = [
        np.linspace(-4.8, 4.8, 10),   # cart position
        np.linspace(-4, 4, 10),        # cart velocity
        np.linspace(-0.42, 0.42, 10),  # pole angle
        np.linspace(-4, 4, 10)         # pole velocity
    ]
    indices = []
    for i, val in enumerate(state):
        indices.append(np.digitize(val, bins[i]) - 1)
    return tuple(indices)

# Q-Table 초기화
q_table = np.zeros((10, 10, 10, 10, env.action_space.n))

# 하이퍼파라미터
learning_rate = 0.1
discount_factor = 0.99
epsilon = 1.0
epsilon_decay = 0.995

# 학습 루프
for episode in range(1000):
    state, _ = env.reset()
    state = discretize_state(state)
    total_reward = 0

    while True:
        # Epsilon-greedy 행동 선택
        if np.random.random() < epsilon:
            action = env.action_space.sample()
        else:
            action = np.argmax(q_table[state])

        # 환경에서 행동 수행
        next_state, reward, terminated, truncated, _ = env.step(action)
        next_state = discretize_state(next_state)

        # Q-Value 업데이트 (벨만 방정식)
        best_next_q = np.max(q_table[next_state])
        q_table[state + (action,)] += learning_rate * (
            reward + discount_factor * best_next_q - q_table[state + (action,)]
        )

        state = next_state
        total_reward += reward

        if terminated or truncated:
            break

    epsilon *= epsilon_decay

    if episode % 100 == 0:
        print(f"Episode {episode}, Total Reward: {total_reward:.0f}")

env.close()

🗣️ Say It Like This in Practice

💬 In a Meeting

"If we switch the recommendation system to reinforcement learning, we can reflect user feedback in real time. We just need to design the click-through rate as the reward function."

💬 In an Interview

"We used PPO when training the chatbot with RLHF. We added a KL divergence penalty so that it wouldn't drift too far from the original model."

💬 In a Technical Discussion

"Separating experience replay and the target network in DQN is key to training stability. Without them, the catastrophic forgetting problem is severe."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Reward Function Design Mistakes (Reward Hacking)

Agents often maximize the reward in unintended ways. If you give only "not dying" as the reward, it may just stay still and do nothing.

❌

Ignoring Sample Efficiency

Reinforcement learning requires a large amount of simulation. If you apply it directly to a real robot, the training cost becomes enormously high.

✅

The right way

Train sufficiently in a simulator, then attempt sim-to-real transfer. Improve learning efficiency by using appropriate shaping rather than a sparse reward for the reward function.

🔗 Related Terms

📚 Learn More