Showing posts with label learning rate. Show all posts
Showing posts with label learning rate. Show all posts

Thursday, October 17, 2024

Turn-Based Game Simulation Using Q-Learning for AI Decision Making


Q-Learning Explained Through a Turn-Based Game | Interactive Guide

๐ŸŽฎ Learning Q-Learning Through a Game

Let’s move away from formulas for a moment and think in terms of a game.

Two numbers exist: A = 12 and B = 51. Two players take turns — a human and an AI.

On each turn, a player chooses a number k and applies a move:

new_value = old_value - k × other_value

The objective is simple: force either A or B to become zero.

But beneath this simple rule lies a powerful idea — this game is a playground for reinforcement learning.


๐Ÿ“Œ Table of Contents


๐Ÿง  Game Intuition: More Than Just Numbers

At first glance, this looks like a mathematical game. But in reality, it is a decision-making problem under uncertainty.

Every move changes the state of the system. Every decision affects future possibilities.

The AI does not know the best move at the beginning. It learns through experience — by playing, failing, and improving.

๐Ÿ“– Think Deeper

This is exactly how humans learn strategy games. We don’t start with perfect knowledge — we experiment, observe outcomes, and adjust.


๐Ÿ”„ How the Game Actually Works

The game unfolds in rounds. Each round begins with the same initial values of A and B.

Players take turns. On each turn:

The player chooses:

1. A value of k 2. Whether to reduce A or B

Then the formula is applied, changing the state.

The moment either value becomes zero, the game ends.

What makes this interesting is that every move is not just a step — it is a strategic decision that shapes the entire future of the game.


๐Ÿค– How the AI Learns Over Time

The AI does not start intelligent. Initially, it behaves almost randomly.

Sometimes it explores — trying random values of k. Sometimes it exploits — using what it has learned so far.

This balance between exploration and exploitation is the core of Q-learning.

Over time, the AI begins to notice patterns:

“Certain moves lead to winning more often.” “Certain states are dangerous.”

And slowly, it becomes strategic.

๐Ÿ“– Why Exploration Matters

If the AI only used known strategies, it would never discover better ones. Exploration allows it to improve beyond its current knowledge.


๐Ÿ“Š Understanding the Q-Table (The AI's Memory)

The Q-table is where the AI stores its experience.

Each entry answers a question:

"If I am in this state, and I take this action, how good is it?"

The state is defined by the current values of A and B. The action is the chosen k and the variable being reduced.

After every move, the AI updates this table.

If a move leads to winning, it becomes more valuable. If it leads to losing, its value decreases.

Over many games, this table transforms from random guesses into a decision guide.


๐Ÿ’ป Code Example

import random

A, B = 12, 51
exploration_prob = 0.3

def choose_action(state, q_table):
    if random.random() < exploration_prob:
        return random.randint(1, 5)
    return max(q_table.get(state, {1:0}), key=q_table.get(state, {1:0}).get)

This snippet shows how the AI decides between exploring and exploiting.


๐Ÿ–ฅ️ Sample Game Output

Game Start: A=12, B=51

AI chooses k=2 → Reduces B → New B=27
Human chooses k=1 → Reduces A → New A= -15

Game Ends

Winner: AI

Each move updates the state — and the AI learns from the result.


๐Ÿ’ก Key Takeaways

This simple game reveals a powerful truth:

Learning is not about knowing the answer — it is about improving decisions over time.

Q-learning allows machines to:

Understand consequences Adapt strategies Improve through experience

And most importantly, learn without being explicitly told what is correct.


๐Ÿ”— Related Articles


๐Ÿ“Œ Final Thought

What looks like a small game is actually a model of intelligence.

The AI is not just playing — it is learning how to think.

Tuesday, September 17, 2024

How Gradient Boosted Trees Work: Concepts and Practical Examples

Gradient Boosted Trees Explained: Step-by-Step Guide with Math & Examples

Gradient Boosted Trees (GBT): A Complete Deep Dive

Gradient Boosted Trees are one of the most powerful and widely used machine learning techniques today. If you've ever worked with models like XGBoost or LightGBM, you've already used this concept.

๐Ÿ“š Table of Contents


Introduction

Instead of building one strong model, Gradient Boosting builds many small weak models (decision trees) and combines them.

๐Ÿ’ก Key Idea: Each new tree fixes the mistakes of the previous ones.

What is Gradient Boosting?

Gradient Boosting is an iterative method where each new model learns the residual errors of the previous model.

๐Ÿ“˜ Expand: What is a Residual?

Residual = Actual − Predicted It tells us how wrong the model is.


Step-by-Step Example

Step 1: Initial Prediction

We start with a simple prediction — the mean:

\[ \hat{y} = \frac{1}{n} \sum y_i \]

If average house price = 300,000 → prediction = 300,000

Step 2: Residuals

\[ r_i = y_i - \hat{y} \]

  • House A: 50,000
  • House B: -20,000
  • House C: 10,000

Step 3: Train Tree

Train tree on residuals (not actual values).

Step 4: Update Prediction

\[ \hat{y}^{(t+1)} = \hat{y}^{(t)} + \eta f_t(x) \]

Where:

  • \(\eta\) = learning rate
  • \(f_t(x)\) = tree prediction

Step 5: Repeat

Continue until error is minimized.


Mathematics Behind GBT

1. Mean Squared Error

\[ MSE = \frac{1}{n} \sum (y_i - \hat{y}_i)^2 \]

This penalizes large errors more heavily.

2. Gradient Descent Idea

\[ \text{Gradient} = \frac{\partial L}{\partial \hat{y}} \]

We move in direction of negative gradient.

3. Residual = Negative Gradient

\[ r_i = - \frac{\partial L}{\partial \hat{y}_i} \]

This is why it's called Gradient Boosting.

4. Final Model

\[ F(x) = \sum_{t=1}^{T} \eta f_t(x) \]


๐Ÿ“˜ Expand: Why Learning Rate Matters

Small learning rate → slow but accurate learning Large learning rate → fast but risk of overfitting


Code Example

from sklearn.ensemble import GradientBoostingRegressor

model = GradientBoostingRegressor(
    n_estimators=100,
    learning_rate=0.1,
    max_depth=3
)

model.fit(X_train, y_train)
predictions = model.predict(X_test)

print(predictions)

CLI Output

$ python train_gbt.py

Training started...
Iteration 1: Loss = 12000
Iteration 10: Loss = 4500
Iteration 50: Loss = 1200
Iteration 100: Loss = 300

Training complete!

๐ŸŽฏ Key Takeaways

  • GBT builds trees sequentially
  • Each tree learns residuals
  • Learning rate controls updates
  • Highly accurate and flexible

Conclusion

Gradient Boosted Trees are powerful because they learn from mistakes. Instead of trying to build a perfect model in one go, they gradually improve step by step.

Once you understand residuals, loss functions, and learning rates, the algorithm becomes intuitive and incredibly useful.

Tuesday, August 27, 2024

What Happens If a Linear Regression Model Doesn't Converge to Zero?

If the derivatives (or gradients) of the cost function do not converge to zero during the optimization process, several issues might arise, leading to suboptimal or incorrect solutions in a linear regression model. Here's what could happen if we don't achieve convergence to zero:

### **1. Suboptimal Solution**
- **Incomplete Minimization**: If the gradient (the vector of partial derivatives) does not converge to zero, it means that the algorithm has not found the true minimum of the cost function (e.g., Residual Sum of Squares, RSS). The coefficients \( \beta_0 \) and \( \beta_1 \) may not be at their optimal values, resulting in a model that does not fit the data as well as it could.
  
- **Higher RSS**: Since the model parameters have not been optimized, the Residual Sum of Squares (RSS) will likely be higher than necessary. This means the predictions will be less accurate, leading to larger errors.

### **2. Gradient Descent Issues**
- **Learning Rate Too High**: If you're using an iterative optimization method like gradient descent, and the learning rate is too high, the algorithm might "overshoot" the minimum. This can cause the gradient to oscillate or even diverge rather than converge to zero.

- **Learning Rate Too Low**: Conversely, if the learning rate is too low, the algorithm might converge very slowly or get stuck in a region where the gradient is small but not zero, leading to premature stopping before reaching the true minimum.

- **Stuck in a Plateau or Local Minimum**: In some cases, the algorithm might get stuck in a plateau where the gradient is close to zero, but it's not the global minimum. This can happen in more complex models or when the cost function has a complicated shape.

### **3. Non-Linearity in Data**
- **Model Misspecification**: If the underlying relationship between the independent and dependent variables is not linear, the linear regression model may never truly minimize the cost function, because the model is inherently incapable of capturing the true relationship. In such cases, the residuals might not decrease sufficiently, and the gradients might not converge to zero.

### **4. Numerical Issues**
- **Precision Errors**: In some cases, especially when dealing with very large or very small numbers, numerical precision errors might prevent the gradient from reaching exactly zero. Instead, it might fluctuate around a small value close to zero but not exactly zero.

### **5. Regularization Terms**
- **Regularization**: If you're using regularization (e.g., Ridge or Lasso regression), the cost function includes additional penalty terms (like \( \lambda \beta_1^2 \) for Ridge). The presence of these terms means the minimum might not correspond to a gradient of exactly zero because the cost function is more complex.

### **Consequences**
- **Poor Model Performance**: Ultimately, if the optimization does not converge properly, the model may have poor predictive performance on both training and unseen data.
  
- **Unstable Solutions**: In cases where the gradient doesn't converge due to issues like a high learning rate, the solution might be unstable, with the algorithm potentially oscillating around the minimum rather than settling down.

### **Conclusion**
Achieving convergence (where the gradient is zero or close enough to zero) is crucial in ensuring that the model parameters are optimized. This ensures that the model provides the best possible fit to the data, minimizing prediction errors. If convergence is not achieved, steps should be taken to diagnose the issue—whether it's adjusting the learning rate, re-evaluating the model's assumptions, or checking for numerical stability. 

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