Understanding the agent-environment interaction model, state representations, and environment design in reinforcement learning.
The fundamental loop in RL is the continuous interaction between an agent and its environment.
Agent-Environment Loop
┌─────────────────────────────┐
│ Agent │
│ (Decision Maker) │
└────────────┬────────────────┘
│ action a_t
▼
┌─────────────────────────────┐
│ Environment │
│ (Dynamics, Rewards) │
└────────────┬────────────────┘
│ state s_{t+1}, reward r_t
▼
┌─────────────────────────────┐
│ Agent │
│ (Update Policy) │
└─────────────────────────────┘
State Representation
State: Complete description of environment configuration
Types of States
Fully Observable: Agent sees complete state
state = [position, velocity, angle, angular_velocity]
Partially Observable: Agent sees partial state
# Poker: only own hand visible
state = [own_cards, community_cards_public, betting_history]
Latent: Hidden features must be learned
# Image: raw pixels, must learn features
state = image_array # shape (84, 84, 3)
Action Space
Discrete: Finite set of actions
actions = ['forward', 'backward', 'left', 'right']
n_actions = 4
Continuous: Infinite actions in range
# Robotic control
action = [joint_1_angle, joint_2_angle, joint_3_angle]
# Each in [-1.0, 1.0]
Hybrid: Mix of discrete and continuous
action = {
'direction': discrete, # [0, 1, 2] for left/forward/right
'speed': continuous # [0.0, 1.0]
}
Reward Structure
Single Reward
reward = {
+1: goal reached,
-1: collision,
0: otherwise
}
Shaped Reward
reward = {
+100: goal,
-50: collision,
-0.1: per step (encourage efficiency),
+5: moved towards goal
}
Multi-Objective
rewards = {
'main_goal': 100,
'efficiency': -0.1, # per time step
'safety': -50 # for collision
}
# Combine with weights
total_reward = 1.0*main + 0.5*efficiency + 1.0*safety
Agent Architecture
┌──────────────────────────────┐
│ Observation/State │
│ (from environment) │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Feature Extraction │
│ (if needed) │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Policy Network │
│ (or Value Network) │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Action Selection │
│ (e.g., ε-greedy) │
└────────────┬─────────────────┘
│
▼
┌──────────────────────────────┐
│ Action to Environment │
└──────────────────────────────┘
Environment Types
Deterministic
Same action always produces same outcome:
next_state, reward = env.step(action)
# Deterministic
Stochastic
Same action can have different outcomes:
# Wind affects ball trajectory
next_state = stochastic_step(state, action)
Episodic
Task has natural ending:
# Game: start to win/lose
episode = []
done = False
while not done:
action = agent.get_action(state)
state, reward, done, _ = env.step(action)
episode.append((state, action, reward))
Continuing
No natural ending:
# Robot maintaining balance
for t in range(infinite):
action = agent.get_action(state)
state, reward, done, _ = env.step(action)
Implementation Example
import gym
import numpy as np
class RLAgent:
def __init__(self, env):
self.env = env
self.state_space = env.observation_space
self.action_space = env.action_space
self.learning_rate = 0.1
self.gamma = 0.99
self.epsilon = 0.1
def get_action(self, state):
"""Choose action (ε-greedy)"""
if np.random.random() < self.epsilon:
return self.action_space.sample()
else:
return self.get_best_action(state)
def run_episode(self):
"""Run one episode"""
state = self.env.reset()
episode_data = []
done = False
while not done:
# Choose action
action = self.get_action(state)
# Step environment
next_state, reward, done, info = self.env.step(action)
# Store transition
episode_data.append({
'state': state,
'action': action,
'reward': reward,
'next_state': next_state,
'done': done
})
# Update
self.update(state, action, reward, next_state, done)
state = next_state
return episode_data
def update(self, state, action, reward, next_state, done):
"""Update policy (Q-Learning)"""
pass # Implement algorithm-specific update
# Usage
env = gym.make('CartPole-v1')
agent = RLAgent(env)
for episode in range(100):
episode_data = agent.run_episode()
total_reward = sum(d['reward'] for d in episode_data)
print(f"Episode {episode}: {total_reward}")
State Space Representations
Tabular
Discrete states indexed in table:
Q_table = {}
for state in all_states:
for action in all_actions:
Q_table[(state, action)] = 0.0
Linear Features
Hand-crafted features:
features = np.array([
position,
velocity,
angle,
angular_velocity
])
Q_value = theta @ features
Neural Network
Learning features:
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Dense(128, activation='relu', input_shape=(state_dim,)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(n_actions)
])
Summary
Key concepts:
- Agent observes state
- Takes action
- Receives reward and next state
- Updates policy
- Repeat until convergence