Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials AI Reinforcement Learning Basics
AI Intermediate FREE

Reinforcement Learning Basics

Lesson 1 of 17 Intermediate Interactive

Reinforcement learning trains agents to make decisions by rewarding desired behaviors.

Key Concepts

  • Agent — the learner/decision maker
  • Environment — where the agent operates
  • Action — what the agent can do
  • Reward — feedback signal
  • Policy — strategy for choosing actions

Syntax

AI
import gymnasium as gym

env = gym.make("CartPole-v1")
obs, info = env.reset()

for _ in range(1000):
    action = env.action_space.sample()  # random
    obs, reward, terminated, truncated, info = env.step(action)
    if terminated:
        break
Q-Learning Concept
PYTHON
import random

# Simple Q-learning
q_table = {}
states = ["start", "middle", "end"]
actions = ["left", "right"]

# Initialize Q-table
for s in states:
    for a in actions:
        q_table[(s, a)] = 0.0

# Update Q-values
alpha = 0.1  # learning rate
gamma = 0.9  # discount factor

def update_q(state, action, reward, next_state):
    old_q = q_table[(state, action)]
    max_next = max(q_table[(next_state, a)] for a in actions)
    new_q = old_q + alpha * (reward + gamma * max_next - old_q)
    q_table[(state, action)] = new_q
    return new_q

new_val = update_q("start", "right", 1, "middle")
print(f"Updated Q(start, right): {new_val:.3f}")