Showing posts with label Game Theory. Show all posts
Showing posts with label Game Theory. Show all posts

Thursday, October 24, 2024

What Is UCB1 Algorithm? Reinforcement Learning Explained Simply


UCB1 Explained – Exploration vs Exploitation

UCB1 Algorithm

A practical and intuitive solution to the exploration vs. exploitation problem in reinforcement learning and multi-armed bandits.

๐ŸŽฐ The Exploration vs. Exploitation Problem

Imagine playing a slot machine with multiple levers. Each lever gives a different payout, but you don’t know which one is best.

Pulling a new lever helps you learn (exploration), but repeatedly pulling the best-known lever helps you earn (exploitation).

The core challenge: How do you explore enough to learn — without sacrificing too much reward?

๐Ÿ“Œ What Is UCB1?

UCB1 (Upper Confidence Bound) selects actions by computing an optimistic estimate of each arm’s reward.

  • Exploitation: Prefer arms with high average reward
  • Exploration: Prefer arms with high uncertainty

Arms that are under-explored receive a temporary boost, ensuring they aren’t ignored too early.

๐Ÿงฎ UCB1 Formula

arm_t = argmax (
  mean_reward
  + sqrt( (2 * log(total_pulls)) / pulls_for_this_arm )
)
      
  • mean_reward: Average reward from the arm
  • total_pulls: Total pulls across all arms
  • pulls_for_this_arm: Pull count for the arm

๐Ÿ’ป CLI Simulation Example

$ python ucb1_simulation.py

Initializing arms...
Pulling each arm once...

Round 10:
Arm 1 | mean=0.50 | UCB=0.91
Arm 2 | mean=0.70 | UCB=0.88
Arm 3 | mean=0.30 | UCB=0.85

Selected Arm → 1

Round 100:
Arm 2 dominates with highest UCB
Exploration bonus shrinking...
    

๐Ÿš€ Why UCB1 Is Effective

  • No hyperparameters to tune
  • Strong theoretical regret guarantees
  • Simple and computationally efficient

๐Ÿ“Š Real-World Use Cases

  • Online advertising (CTR optimization)
  • Clinical trials
  • Game AI and strategy optimization

⚠️ Limitations

  • Assumes stationary reward distributions
  • Does not incorporate contextual information

For changing environments, consider Thompson Sampling or Contextual Bandits.

๐Ÿ’ก Key Takeaways

UCB1 offers a clean, mathematically grounded solution to exploration vs. exploitation — ideal when rewards are stable and simplicity matters.
Built for learning • Interactive • No external dependencies

Monday, October 21, 2024

Self-Play in Reinforcement Learning: How Agents Learn by Competing Against Themselves


Self-Play in Reinforcement Learning Explained | Complete Educational Guide

Self-Play in Reinforcement Learning Explained: Complete Educational Guide

Self-play is one of the most revolutionary concepts in artificial intelligence and reinforcement learning. It allows AI systems to improve by competing against themselves instead of relying on human-generated datasets or external opponents.

This idea transformed modern AI and led to groundbreaking achievements such as AlphaGo defeating world-class Go players, advanced Chess engines surpassing grandmasters, and video game AI mastering complex environments.

๐Ÿ’ก Key Takeaways

  • Self-play allows AI agents to train against themselves.
  • It removes the dependency on labeled datasets.
  • Agents improve continuously through repeated interactions.
  • AlphaGo became superhuman using self-play.
  • Mathematics and probability are deeply connected to RL.
  • Self-play dynamically adjusts difficulty automatically.
  • Modern AI breakthroughs heavily depend on reinforcement learning.

Table of Contents


1. Introduction to Reinforcement Learning

Reinforcement Learning (RL) is a branch of machine learning where an intelligent agent learns through interaction with an environment.

Instead of learning from fixed examples, the agent learns from consequences. Good actions receive rewards, while bad actions receive penalties.

Over time, the system improves its decision-making abilities.

Basic RL Concept

The learning loop works like this:

  1. The agent observes the environment.
  2. The agent chooses an action.
  3. The environment responds.
  4. The agent receives a reward.
  5. The agent updates its strategy.

Mathematical Representation

Reinforcement learning tries to maximize cumulative reward:

$$ R = \sum_{t=0}^{\infty} \gamma^t r_t $$

Where:

  • \(R\) = total reward
  • \(r_t\) = reward at time step \(t\)
  • \(\gamma\) = discount factor

The discount factor controls how much future rewards matter.


2. What is Self-Play?

Self-play means the AI learns by playing against itself repeatedly.

Instead of needing humans or external opponents, multiple copies of the same AI compete against each other.

This creates an endlessly evolving learning environment.

Simple Example

Imagine two beginner Chess bots.

  • Initially, both make random moves.
  • Over time, they discover winning strategies.
  • Each improvement creates a stronger opponent.
  • The cycle repeats continuously.

Core Self-Play Formula

$$ Agent_{new} = Agent_{old} + Learning $$

Each training cycle improves the policy slightly.

Why Self-Play Is Powerful

Feature Benefit
Infinite Opponents Never runs out of training data
Automatic Difficulty Scaling Challenge grows naturally
No Human Labels Needed Reduces dependency on datasets
Continuous Improvement Agent evolves over time

3. Core Components of Reinforcement Learning

1. Agent

The AI decision-maker.

2. Environment

The world where the agent operates.

3. State

The current situation.

$$ S_t $$

4. Action

Possible choices:

$$ A_t $$

5. Reward

Feedback signal:

$$ R_t $$

Markov Decision Process

Most RL systems are modeled using:

$$ MDP = (S, A, P, R, \gamma) $$

Where:

  • \(S\) = States
  • \(A\) = Actions
  • \(P\) = Transition probabilities
  • \(R\) = Rewards
  • \(\gamma\) = Discount factor

4. Mathematics Behind Self-Play

Reinforcement learning relies heavily on mathematics and optimization.

Expected Reward

$$ E[R] = \sum P(s,a) \times Reward $$

Policy Function

A policy determines which action the agent should take.

$$ \pi(a|s) $$

This means:

Probability of taking action \(a\) given state \(s\).

Bellman Equation

$$ V(s) = \max_a \left[ R(s,a) + \gamma \sum P(s'|s,a)V(s') \right] $$

This equation is one of the foundations of reinforcement learning.

Q-Learning Formula

$$ Q(s,a) = Q(s,a) + \alpha [r + \gamma \max Q(s',a') - Q(s,a)] $$

Where:

  • \(\alpha\) = learning rate
  • \(\gamma\) = discount factor
  • \(r\) = immediate reward

5. Policy Optimization

The AI continuously updates its policy to maximize rewards.

Policy Update Formula

$$ \pi_{new} = \pi_{old} + \alpha (Reward - Prediction) $$

This helps the model move toward better strategies.

Gradient Ascent

Modern reinforcement learning often uses gradient optimization:

$$ \theta = \theta + \alpha \nabla J(\theta) $$

Where:

  • \(\theta\) = model parameters
  • \(\nabla J(\theta)\) = gradient direction

6. Exploration vs Exploitation

One of the hardest problems in RL is balancing exploration and exploitation.

Exploration

Trying new strategies.

Exploitation

Using already known successful strategies.

Mathematical Balance

$$ Optimal = Exploration + Exploitation $$

Epsilon-Greedy Strategy

$$ P(random) = \epsilon $$

With probability \(\epsilon\), the agent explores random actions.

Otherwise, it exploits the best-known action.

Why Exploration Matters

Without exploration, the AI may get stuck repeating mediocre strategies forever.

Exploration allows discovery of:

  • Hidden tactics
  • Unexpected strategies
  • Better long-term rewards

7. AlphaGo: The Most Famous Self-Play AI

One of the greatest demonstrations of self-play was AlphaGo developed by DeepMind.

Go is an extremely difficult board game because the number of possible positions is enormous.

Go Complexity

$$ PossibleStates > 10^{170} $$

This number is greater than atoms in the observable universe.

How AlphaGo Learned

  1. Started from human expert games
  2. Transitioned into self-play
  3. Played millions of games against itself
  4. Discovered entirely new strategies

AlphaGo Impact

Achievement Importance
Defeated Go Champion Historic AI milestone
Used Self-Play Proved autonomous learning works
Discovered New Moves AI creativity surprised humans

8. Reinforcement Learning Code Examples

Simple Python Reward Example


reward = 10
learning_rate = 0.1
policy = 0.5

new_policy = policy + learning_rate * reward

print(new_policy)

Q-Learning Example


Q[state][action] = Q[state][action] + alpha * (
reward + gamma * max(Q[next_state]) 
- Q[state][action]
)

Self-Play Pseudocode


Initialize Agent

while training:
    play game against self
    collect rewards
    update policy
    improve strategy

9. CLI Output Simulation

Training Simulation


$ python train.py

Episode 1: Loss
Episode 2: Draw
Episode 3: Win
Episode 10: Win
Episode 100: Strong Strategy Learned

Policy Optimization Output


$ python optimize.py

Current Reward: 0.45
Updated Reward: 0.61
Policy Improved

Self-Play Match Output


$ python selfplay.py

Agent A vs Agent B
Winner: Agent A
Updating policies...
Training Complete

10. Advantages of Self-Play

1. Infinite Data Generation

Self-play continuously generates new experiences.

2. Adaptive Difficulty

The opponent improves automatically.

3. No Human Bias

The AI may discover strategies humans never considered.

4. Efficient Learning

Millions of games can be simulated quickly.

Improvement Curve

$$ Performance \propto TrainingTime $$

11. Challenges of Self-Play

Stagnation

The AI may stop improving.

Local Optima

$$ Agent \rightarrow SuboptimalStrategy $$

The system may settle on strategies that are good but not optimal.

Computation Cost

Massive hardware is often required.

Instability

Training may become unstable if learning updates are too aggressive.

Overfitting to Self

An AI may become too specialized against itself but weak against different opponents.


12. Real World Applications Beyond Games

Robotics

Robots can simulate movements and learn optimal control strategies.

Autonomous Vehicles

Self-driving systems simulate traffic scenarios.

Finance

Trading agents compete in simulated markets.

Negotiation Systems

AI agents learn bargaining tactics.

Cybersecurity

Security systems simulate attackers and defenders.


Neural Networks in Self-Play

Modern self-play systems use deep neural networks.

Neural Function

$$ y = f(Wx + b) $$

Where:

  • \(W\) = weights
  • \(x\) = input
  • \(b\) = bias

Loss Minimization

$$ Loss = (Prediction - Target)^2 $$

Training minimizes this loss over time.


13. Future of Self-Play AI

Self-play may become one of the dominant methods for creating general-purpose intelligent systems.

Future possibilities include:

  • Scientific discovery
  • Drug research
  • Climate optimization
  • Autonomous robotics
  • Advanced strategy systems

General Intelligence Equation

$$ Intelligence = Learning + Adaptation + Optimization $$

14. Conclusion

Self-play is one of the most transformative concepts in reinforcement learning. By allowing AI systems to compete against themselves, researchers created a method capable of producing superhuman performance without relying entirely on human-generated data.

The success of systems like AlphaGo proved that AI can:

  • Learn independently
  • Adapt dynamically
  • Discover innovative strategies
  • Master highly complex environments

The combination of mathematics, optimization, neural networks, and continuous self-improvement makes self-play one of the foundations of modern AI research.

As computational power increases and algorithms become more advanced, self-play could play a central role in solving some of humanity’s biggest challenges.

๐ŸŽฏ Final Summary

  • Reinforcement learning learns through rewards.
  • Self-play allows AI to train against itself.
  • AlphaGo demonstrated the power of self-play.
  • Mathematics is central to RL optimization.
  • Exploration and exploitation must be balanced.
  • Self-play extends far beyond games.
  • The future of AI heavily depends on autonomous learning.

Wednesday, October 16, 2024

Q-Learning Implementation for Rock, Paper, Scissors with Custom Rewards and Strategy Analysis


Q-Learning Rock Paper Scissors Tutorial | Reinforcement Learning Explained

Implementing Q-Learning for Rock Paper Scissors

This article explains how to train a Reinforcement Learning agent using Q-learning to play the classic game Rock Paper Scissors.

Instead of manually programming strategies, the agent learns through trial and error by observing rewards from its actions.


๐Ÿ“š Table of Contents


Introduction to Reinforcement Learning

Reinforcement Learning (RL) is a machine learning paradigm where an agent learns by interacting with an environment and receiving rewards or penalties.

Instead of learning from labeled datasets, the agent learns through experience.

  • Agent takes an action
  • Environment returns a reward
  • Agent updates its knowledge
Why Reinforcement Learning Matters

Reinforcement Learning powers many modern technologies such as:

  • Game-playing AI systems
  • Autonomous robotics
  • Recommendation engines
  • Financial trading algorithms

Game Mechanics

The Rock Paper Scissors game contains three actions:

  • Rock
  • Paper
  • Scissors

Each action has a deterministic outcome against another action.

Action Beats
Rock Scissors
Paper Rock
Scissors Paper

Reward Matrix Design

To train a reinforcement learning agent, we convert game outcomes into numerical rewards.

Outcome Reward
Win +1
Loss -1
Tie 0

These rewards guide the learning algorithm toward optimal strategies.


Understanding Q-Learning

Q-learning is a reinforcement learning algorithm that learns the value of taking an action in a specific state.

The algorithm maintains a table called the Q-table.

The Q-table stores expected rewards for each state-action pair.

Q-Learning Formula


Q(s,a) = Q(s,a) + ฮฑ [R + ฮณ max(Q(s',a')) - Q(s,a)]

  • s = current state
  • a = action
  • ฮฑ = learning rate
  • ฮณ = discount factor
  • R = reward
Intuition Behind Q-Learning

The algorithm updates knowledge using:

  • Immediate reward
  • Best possible future reward

Over many iterations the values converge toward optimal behavior.


Python Implementation

Initialize Q-table


import numpy as np

import random

actions = ["Rock","Paper","Scissors"]

Q = np.zeros((3,3))

alpha = 0.1

gamma = 0.9

epsilon = 0.1

reward_matrix = [

[0,-1,1],

[1,0,-1],

[-1,1,0]

]

The Q-table starts with zeros, meaning the agent initially has no knowledge.


Training the Agent


for episode in range(10000):

    state = random.randint(0,2)

    if random.random() < epsilon:

        action = random.randint(0,2)

    else:

        action = np.argmax(Q[state])

    opponent = random.randint(0,2)

    reward = reward_matrix[action][opponent]

    Q[state][action] = Q[state][action] + 0.1 * (

        reward + 0.9 * np.max(Q[action]) - Q[state][action]

    )

During training the agent sometimes explores random actions to discover better strategies.


CLI Output Example


$ python rps_qlearning.py

Training started...

Episode 1000 complete

Episode 5000 complete

Episode 10000 complete

Final Q Table:

[[ 0.12 0.88 -0.44]

 [-0.32 0.21 0.92]

 [0.71 -0.51 0.08]]

Optimal Strategy Learned:

Rock -> Paper

Paper -> Scissors

Scissors -> Rock


Understanding the Q-Table

The Q-table stores expected rewards for each action.

State Rock Paper Scissors
Rock 0.12 0.88 -0.44
Paper -0.32 0.21 0.92
Scissors 0.71 -0.51 0.08

Interactive Demo

Play against a simple agent:


๐Ÿ’ก Key Insights

  • Reinforcement Learning learns through rewards
  • Q-learning uses a table of expected action rewards
  • Exploration allows discovery of better strategies
  • Rock Paper Scissors demonstrates RL concepts clearly
  • Q-tables help interpret the learning process


Author: Subham

Saturday, August 3, 2024

Challenges with Alpha-Beta Pruning in Real-Life Chess Scenarios


Challenges with Alpha-Beta Pruning in Real-Life Chess Scenarios

Challenges with Alpha-Beta Pruning in Real-Life Chess Scenarios


๐Ÿง  Introduction

Alpha-beta pruning is a widely used optimization technique in artificial intelligence, especially in game-playing systems like chess engines.

While it dramatically reduces computation, real-world chess scenarios introduce complexities that challenge its effectiveness.

๐Ÿ’ก Core Idea: Alpha-beta pruning speeds up decision-making, but may miss deeper strategic opportunities if not implemented carefully.

♟️ What is Alpha-Beta Pruning?

Alpha-beta pruning is an enhancement of the minimax algorithm that eliminates branches of the game tree that do not need to be explored.

  • Alpha: Best already explored option for maximizer
  • Beta: Best already explored option for minimizer
๐Ÿ“– Expand for Simple Explanation

Imagine evaluating moves in chess. If you already found a strong move, you can skip exploring weaker alternatives.


⚠️ Key Challenges in Real Chess

1. Initial Promising Moves

A move that looks strong initially might actually be inferior in deeper analysis.

2. Delayed Tactical Benefits

Some sacrifices only pay off after multiple moves — pruning may remove them early.

3. Move Ordering Dependency

Efficiency heavily depends on evaluating the best moves first.

๐Ÿ” Why Move Ordering Matters

If bad moves are evaluated first, pruning becomes ineffective, leading to higher computation and missed opportunities.


♞ Real-Life Chess Scenario

Consider sacrificing a queen for long-term positional advantage.

  • Short-term: Material loss ❌
  • Long-term: Winning position ✅
๐Ÿ’ก Engines without deep evaluation may reject such moves prematurely.

๐Ÿ’ป Code Example (Python)

def alpha_beta(node, depth, alpha, beta, maximizing):
    if depth == 0 or node.is_terminal():
        return node.evaluate()

    if maximizing:
        value = float('-inf')
        for child in node.children():
            value = max(value, alpha_beta(child, depth-1, alpha, beta, False))
            alpha = max(alpha, value)
            if alpha >= beta:
                break  # Beta cut-off
        return value
    else:
        value = float('inf')
        for child in node.children():
            value = min(value, alpha_beta(child, depth-1, alpha, beta, True))
            beta = min(beta, value)
            if beta <= alpha:
                break  # Alpha cut-off
        return value

๐Ÿ–ฅ️ CLI Output Simulation

Evaluating Move: Qxh7+ (Sacrifice)
Depth 1 Score: -9
Depth 3 Score: +2
Depth 5 Score: +8 (Winning)

Alpha-Beta Pruning Skipped Branches: 42%
Nodes Evaluated: 1,230

๐Ÿš€ Heuristics & Improvements

  • Better Evaluation Functions – Capture positional strength
  • Move Ordering – Evaluate captures, checks first
  • Iterative Deepening – Gradually increase depth
  • Transposition Tables – Cache results
๐Ÿ“Š Advanced Optimization Techniques
  • Killer Heuristic
  • History Heuristic
  • Principal Variation Search

๐ŸŽฏ Key Takeaways

  • Alpha-beta pruning is powerful but not foolproof
  • Move ordering directly impacts efficiency
  • Deep tactics can be missed without good heuristics
  • Real-world chess requires hybrid strategies


© 2026 Data Dive with Subham

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts