본문으로 건너뛰기

RL 010

· 약 5분

Policy Search Methods​

Instead of VV and QQ functions, we directly estimate the optimal policy.

πθ(a∣s)≈P(a∣s,θ)\pi^{\theta}(a|s) \approx P(a|s, \theta)

  • Policy was generated directly from the value function (e.g. ϵ\epsilon-greedy)
  • Parameterize the policy directly.
    • Instead of v(s,w)v(s,w) or q^(s,a,w)\hat{q}(s,a,w), we have πθ(a∣s)\pi^{\theta}(a|s)
    • Given a particular state ss, what actions should we take? (What is probability of that particular action?)
    • θ\theta is a learnable parameter which could be a neural network.

Value-based and Policy-based Methods​

  • Value-based: Learnt value function, Implicit policy (e.g. ϵ\epsilon-greedy)
  • Policy-based: No value function, Learnt policy.
    • Good convergence properties
    • Effective in high-dimensional or continuous action spaces
      • if it is really continuous and large, it is not efficient as well.
    • Can learn stochastic policies.
    • Sometimes policies are relatively simple, values and models are complex.
    • Typically reaches local optima.
    • Obtained knowledge is specific and does not generalize well.
  • Actor-Critic: Learnt value function, Learnt policy.

Policy Gradient Techniques​

  • Trust-Region Based: Optimize the policy in a trust zone (closer circle).

Stochastic policies​

Rock-Paper-Scissors​

  • A deterministic policy is easily exploited
    • Deterministic policy: If we follow a set of action or sequence of actions, we will definitely reach the goal and will always reach teh same location.
  • A uniform random policy is optimal policy.

Grid World​

Grid World

ϕ(s,a)=(1010⏟walls,0100⏟actions)\phi(s,a) = \big(\underbrace{1 0 1 0}_{walls}, \underbrace{0 1 0 0}_{actions}\big)
  • Agent cannot differentiate between the grey states.
  • ϕ(s,a)\phi(s,a) features describing state ss and action aa.
  • ϕ(s,E)=(1,0,1,0⏟NESW,0,1,0,0⏟NESW)\phi(s,E) = (\underbrace{1, 0, 1, 0}_{\text{NESW}}, \underbrace{0, 1, 0, 0}_{\text{NESW}}) is the North and the South are walls and the agent will move to the East.
  • If π(grey)=W\pi(\text{grey}) = W, then when the agent is in the left grey state, it will move west, get stuck in a loop, and never reach the goal.

Grid World Stochastic

  • Therefore, an optimal stochastic policy moves randomly EE or WW in grey states.
    • πθ(wall to N and S, move E)=0.5\pi_{\theta}(\text{wall to N and S, move E}) = 0.5
    • πθ(wall to N and S, move W)=0.5\pi_{\theta}(\text{wall to N and S, move W}) = 0.5
  • The agent will reach the goal with high probability.
  • Policy-based methods can learn Stochastic policies. 4563

Objective Function in Policy-based Methods​

Given a policy πθ(a∣s)\pi_{\theta}(a|s) with parameters θ\theta, the goal is to find the best θ\theta.

J1(θ)=vπθ(S1)J_1(\theta) = v_{\pi_{\theta}}(S_1)
  • In an episodic task (with an end state), J1(θ)J_1(\theta) is for that particular start state and measures how much expected return we can get.
  • S1S_1 is the start state.
  • J(θ)J(\theta) is the measure of the quality of the policy or the objective function to optimize.
JavV(θ)=∑sμπθ(s)vπθ(s)J_{avV}(\theta) = \sum_{s}\mu_{\pi\theta}(s)v_{\pi\theta}(s)
  • In continuing environments (doesn't have an end state), consider the states and take the average value weighted by how often the agent visits each state.
  • μπθ(s)\mu_{\pi\theta}(s) is how often the agent is visiting that particular state ss.
JavR(θ)=∑sμπθ(s)∑aπθ(a∣s)∑rp(r∣s,a)rJ_{avR}(\theta) = \sum_{s}\mu_{\pi\theta}(s)\sum_{a}\pi_{\theta}(a|s)\sum_{r}p(r|s,a)r
  • Use the average reward per time step.
  • Small batches can be used to estimate this average reward during training.

Policy-based Methods​

  • Policy-based RL is an optimization problem, find θ\theta that maximize J(θ)J(\theta).
    • J(θ)J(\theta) is the policy objective function.
  • Gradient-free methods: Hill Climbing, Genetic Algorithms, ...
  • Gradient-based

Δθ=α∇θJ(θ)\Delta{\theta} = \alpha \nabla_{\theta} J(\theta)

  • Policy gradient method will search for a local minimum in J(θ)J(\theta) by ascending the gradient of the Policy.
    • why ascending? because we want to maximize the objective function's value/rewards.
    • ∇θJ(θ)=(∂J(θ)θ1⋮∂J(θ)θn)\nabla_{\theta} J(\theta) = \begin{pmatrix} \frac{\partial J(\theta)}{\theta_1} \\ \vdots \\ \frac{\partial J(\theta)}{\theta_n} \end{pmatrix}
    • α\alpha is the step size.
ΔθJ(θ)=∇θEd[vπθ(s)]\Delta{\theta} J(\theta) = \nabla_{\theta} \mathbb{E}_d[v_{\pi\theta}(s)]
  • Assume the policy πθ\pi_{\theta} is differentiable.
  • Compute an estimate of the policy gradient.
  • Compute ΔθJ(θ)\Delta{\theta} J(\theta) using Monte Carlo samples since we need to explore the environment, gather information, and then learn the policy.

Score Function​

  • Assume the policy πθ\pi_{\theta} is differentiable.
  • ∇θπθ(s,a)\nabla_{\theta} \pi_{\theta}(s, a) is the gradient.
∇θπθ(s,a)=πθ(s,a)∇θπθ(s,a)πθ(s,a)=πθ(s,a)∇θlog⁡πθ(s,a)(∵ ∇θlog⁡f(θ)=1f(θ)∇θf(θ))\begin{aligned} \nabla_\theta \pi_\theta(s,a) &= \pi_\theta(s,a) \frac{\nabla_\theta \pi_\theta(s,a)} {\pi_\theta(s,a)} \\ &= \pi_\theta(s,a) \nabla_\theta \log \pi_\theta(s,a) \quad \big( \because \ \nabla_\theta \log f(\theta) = \frac{1}{f(\theta)} \nabla_\theta f(\theta) \big) \end{aligned}
  • Multiplying and dividing by πθ(s,a)\pi_\theta(s,a) is called the Likelihood Ratio Trick.
    • Since πθ(s,a)πθ(s,a)=1\frac{\pi_\theta(s,a)}{\pi_\theta(s,a)} = 1, this does not change the original value.
      • ∇θπθ(s,a)\nabla_\theta \pi_\theta(s,a) is Gradient of the policy
      • πθ(s,a)\pi_\theta(s,a) is the policy.
      • ∇θπθ(s,a)πθ(s,a)\frac{\nabla_\theta \pi_\theta(s,a)}{\pi_\theta(s,a)} measures how sensitive the policy is to changes in θ\theta, relative to the policy value itself.
    • From the derivative rule of the logarithm, ∇θπθ(s,a)πθ(s,a)=∇θlog⁡πθ(s,a)\frac{\nabla_\theta \pi_\theta(s,a)}{\pi_\theta(s,a)} = \nabla_\theta \log \pi_\theta(s,a).
  • ∇θlog⁡πθ(s,a)\nabla_\theta \log \pi_\theta(s,a) is called the Score Function.

RL 009

· 약 11분

Function Approximation​

v^(s,w)≈vπ(s)\hat{v}(s, \mathbf{w}) \approx v_\pi(s)

q^(s,a,w)≈qπ(s,a)\hat{q}(s, a, \mathbf{w}) \approx q_\pi(s, a)

  • Incremental methods for prediction
  • Model-free VFA: MC and TD targets

GPI, Generalized Policy Iteration​

  • Iterate between policy evaluation and policy improvement
  • Policy Evaluation: Approximate policy evaluation. q^(⋅,⋅,w)≈qπ\hat{q}(\cdot, \cdot, \mathbf{w}) \approx q_\pi
  • Policy Improvement: ϵ\epsilon-greedy policy improvement.

Types of Action-Value FA​

s→FA(w)→q^(s,w)s \to \text{FA}(\mathbf{w}) \to \hat{q}(s, \mathbf{w})
  • State Value Function Approximation
(s,a)→FA(w)→q^(s,a,w)(s, a) \to \text{FA}(\mathbf{w}) \to \hat{q}(s, a, \mathbf{w})
  • Action Value Function Approximation
    • q^(s,Left,w)=3.2\hat{q}(s, \text{Left}, \mathbf{w}) = 3.2
    • q^(s,Right,w)=8.7\hat{q}(s, \text{Right}, \mathbf{w}) = 8.7
s→FA(w)→q^(s,a1,w)⋯q^(s,an,w)s \to \text{FA}(\mathbf{w}) \to \hat{q}(s,a_1, \mathbf{w}) \cdots \hat{q}(s,a_n, \mathbf{w})
  • The network output is a vector of Q-values for each action.
  • More convenient to use discrete action spaces.
ActionQ-value
Left3.2
Right8.7
Jump5.3

Action VFA​

q^(s,a,w)≈qπ(s,a)\hat{q}(s, a, \mathbf{w}) \approx q_\pi(s, a)

  • Approximate the Action-value function.
  • Doing action aa at state ss, Approximate the Q-value of that action.

J=Eπ[(qπ(s,a)−q^(s,a,w))2]\mathcal{J} = \mathbb{E}_{\pi} \left[ (q_\pi(s, a) - \hat{q}(s, a, \mathbf{w}))^2 \right]

  • Minimize mean-squared error (MSE) between the approximate Q-value q^(s,a,w)\hat{q}(s, a, \mathbf{w}) and the true Q-value qπ(s,a)q_\pi(s, a).

Δw=α(qπ(s,a)−q^(s,a,w))∇wq^(s,a,w) \Delta \mathbf{w} = \alpha (q_{\pi}(s,a) - \hat{q}(s,a,\mathbf{w})) \nabla_{\mathbf{w}} \hat{q}(s,a,\mathbf{w})

  • Use SGD to find the local minimum.
  • qπ−q^q_{\pi} - \hat{q} tells us how much the prediction is off from the target.
  • ∇wq^(s,a,w)\nabla_{\mathbf{w}} \hat{q}(s,a,\mathbf{w}) tells us how each weight affects the predicted QQ-value.

Linear Action VFA​

x(s,a)=[x1(s,a)x2(s,a)⋮xn(s,a)]x(s, a) = \begin{bmatrix} x_1(s, a) \\ x_2(s, a) \\ \vdots \\ x_n(s, a) \end{bmatrix}
  • Feature vector is used to represent the state and action pair.

q^(s,a,w)≈x(s,a)Tw=∑jxj(s,a)wj\hat{q}(s, a, w) \approx x(s, a)^T w = \sum_j x_j (s, a) w_j

  • Predicted Q-value is a linear combination of the feature values. (sum of each feature value xjx_j multiplied by the weight wjw_j)
q^(s,a,w)=x(s,a)Twq^=x1w1+x2w2+⋯+xnwn\begin{aligned} \hat{q}(s, a, w) = x(s, a)^T w \\ \hat{q} = x_1w_1 + x_2w_2 + \cdots + x_n w_n \end{aligned}
  • x1,x2,⋯x_1, x_2, \cdots: features of the state and action pair.
  • w1,w2,⋯w_1, w_2, \cdots: weights that need to be learned.
  • derivative q^\hat{q} with respect to ww.
    • ∂q^∂w1=x1\frac{\partial \hat{q}}{\partial w_1} = x_1
    • ∂q^∂w2=x2\frac{\partial \hat{q}}{\partial w_2} = x_2
∇wq^=[x1x2⋮xn]=x(s,a)\nabla_w\hat{q} = \begin{bmatrix} x_1 \\ x_2 \\ \vdots \\ x_n \end{bmatrix} = x(s, a)
  • e.g. q^=2w1+5w2\hat{q} = 2w_1 + 5w_2, then ∇wq^=[25]\nabla_w\hat{q} = \begin{bmatrix} 2 \\ 5 \end{bmatrix}
Δw=α(qπ−q^)∇wq^=α(qπ−q^)x(s,a)=α(qπ(s,a)−q^(s,a,w))x(s,a)\begin{aligned} \Delta w \\ &= \alpha (q_{\pi} - \hat{q}) \nabla_w\hat{q} \\ &= \alpha (q_{\pi} - \hat{q}) x(s, a) \\ &= \alpha (q_{\pi}(s, a) - \hat{q}(s, a, w)) x(s, a) \end{aligned}

Incremental Prediction Algorithm​

  • Assumption so far: qπ(s,a)q_{\pi}(s,a) is given.
  • But an actual RL agent does not know the true qπ(s,a)q_{\pi}(s,a).
  • Therefore, we need to estimate a target.
  • Monte Carlo (MC): the target is the return GtG_t.
    • Gt=Rt+1+γRt+2+⋯G_t = R_{t+1} + \gamma R_{t+2} + \cdots
    • Update: Δw=α(Gt−q^(st,at,w))∇wq^(st,at,w)\Delta w = \alpha \bigl(G_t - \hat q(s_t,a_t,w)\bigr)\nabla_w\hat q(s_t,a_t,w)
    • It compares the predicted Q-value with the actual return observed after the episode.
    • MC does not use another prediction inside the target.
  • Temporal Difference (TD): the target is Rt+1+γq^(st+1,at+1,w)R_{t+1} + \gamma \hat q(s_{t+1},a_{t+1},w).
    • Update: Δw=α(Rt+1+γq^(st+1,at+1,w)−q^(st,at,w))∇wq^(st,at,w)\Delta w = \alpha \bigl(R_{t+1} + \gamma\hat q(s_{t+1},a_{t+1},w) - \hat q(s_t,a_t,w)\bigr)\nabla_w\hat q(s_t,a_t,w)
    • It compares the current Q prediction with the current reward plus the discounted next Q prediction.
    • Bootstrapping: update the current prediction using another prediction.
    • Because the next prediction can also be wrong, we ask: can repeated updates converge to a stable value?
  • On-policy: behavior policy = target policy.
  • Off-policy: behavior policy ≠\ne target policy.
    • The policy that generates the experience is different from the policy that we want to evaluate or improve.
PolicyAlgorithmLookup TableLinearNon-linear
On-policyMC✓✓✓
On-policyTD(0)✓✓✗
Off-policyMC✓✓✓
Off-policyTD(0)✓✗✗
  • Deadly Triad: Function Approximation + Bootstrapping + Off-policy.
AlgorithmLookup TableLinearNon-linear
MC Control✓(✓)✕
SARSA✓(✓)✕
Q-Learning✓✕✕
  • SARSA learns the policy that it actually follows.
    • Target: Rt+1+γQ(st+1,at+1)R_{t+1} + \gamma Q(s_{t+1},a_{t+1}), On-policy TD
  • Q-Learning learns the optimal policy.
    • Target: max⁡a′Q(st+1,a′)\max_{a'} Q(s_{t+1},a'), Off-policy TD
  • (✓): Moved around the near-optimal value function.
    • Linear FA may not represent the exact Q∗Q^* because all state-action values share the same weight vector and must fit the same linear function.
  • x: Divergence

Batch Methods​

  • Incremental learning: an experience -> update the weights.
  • Batch methods: collect experiences -> store in D\mathcal{D} -> reuse D\mathcal{D} for training.
  • It seeks to find the best fitting value functions.

D={(s1,v1π),(s2,v2π),⋯ ,(sN,vNπ)} \mathcal{D} = \{(s_1, v^{\pi}_1), (s_2, v^{\pi}_2), \cdots, (s_N, v^{\pi}_N)\}

  • Which ww makes v^(s,w)\hat{v}(s, w) fit all stored data best?
    • Using the agents' experience or training data.
    • Training data: a fixed batch of previously collected data.

Least Squares Prediction​

  • Given a value function approximation: v^(s,w)≈vπ(s)\hat{v}(s,w) \approx v^\pi(s)
  • Given experience data: D={(s1,v1π),(s2,v2π),…,(sN,vNπ)}\mathcal{D} = \{(s_1,v_1^\pi),(s_2,v_2^\pi),\ldots,(s_N,v_N^\pi)\} consisting of state-value pairs.
LS(w)=∑t=1N(vtπ−v^(st,w))2LS(w)=\sum_{t=1}^{N}\left(v_t^\pi-\hat{v}(s_t,w)\right)^2
  • LS(w)LS(w) is the sum of all squared prediction errors.
  • The Least Squares method finds the parameter vector ww that minimizes the squared error between v^(s,w)\hat v(s,w) and vπ(s)v^\pi(s).
wπ=arg⁡min⁡wLS(w)w^\pi=\arg\min_w LS(w)
  • If we use the mean squared error instead:
ED[(vtπ−v^(st,w))2]=1N∑t=1N(vtπ−v^(st,w))2\mathbb{E}_{\mathcal D} \left[ \left(v_t^\pi-\hat v(s_t,w)\right)^2 \right] = \frac{1}{N} \sum_{t=1}^{N} \left(v_t^\pi-\hat v(s_t,w)\right)^2
  • The factor 1/N1/N does not change the minimizing ww.

SGD Procedure​

  1. Sample a {state,value}\{\text{state},\text{value}\} pair from D\mathcal D.
  2. Apply the SGD update:
Δw=α(vπ−v^(s,w))∇wv^(s,w)\Delta w = \alpha \left(v^\pi-\hat v(s,w)\right) \nabla_w\hat v(s,w)
  • Sample from D\mathcal D -> calculate the error -> update ww -> repeat.
  1. Under appropriate conditions, SGD converges toward the Least Squares solution.
  • Then, what model should represent v^(s,w)\hat v(s,w)?
    • Linear function approximator
    • ANN
    • CNN

DNN, Deep neural network​

  • Universal function approximator
    • Linear FA limited to linear combinations of features v^(s,w)=x(s)Tw\hat{v}(s, w) = x(s)^T w
    • DNN can represent non-linear mappings of features. s→DNN(w)→v^(s,w)s \rightarrow \text{DNN}(\mathbf{w}) \rightarrow \hat{v}(s, \mathbf{w})
  • Combination of both Linear and Non-Linear transformations
    • z=Wx+bz = Wx + b
    • h=ReLU(z)h = \text{ReLU}(z)
  • It may require exponentially less nodes or parameters to represent the sample Linear function.
  • SGD can be used to learn parameters
    • prediction -> loss -> gradient -> SGD -> ww update.
  • It can generalize from observed states to unseen states.
  • It can handle continuous state spaces, which are common in real world problems.
    • s=(x,y,velocity,angle)s = (x, y, \text{velocity}, \text{angle})
    • s=(2.371,5.826,0.43,⋯ )→DNN→v^(s,w)s = (2.371, 5.826, 0.43, \cdots) \rightarrow \text{DNN} \rightarrow \hat{v}(s, \mathbf{w})
  • E2E learning (learn feature representation and policy together) can be more effective.
  • Function approximation using images, environments with visual observations.
  • DNNs can directly process pixel data and learn from raw images.
  • DNNs can be used in environments with continuous action spaces for approximating policies (Robotics)
  • It can achieve SOTA performance in several complex tasks.

CNN, Convolutional neural network​

  • CONV is the first layer to extract features from an input image.
    • Core building block of a CNN
    • A number of filters such as Edge Detectors are applied to the input image.
  • Padding: add extra pixels around the image to handle edge cases.
    • Valid Padding: no padding, output size is smaller than input size.
      • p=0p = 0.
      • Output size: (n−f+1)×(n−f+1)(n - f + 1) \times (n - f + 1)
      • ff: filter size.
    • Same Padding: add padding so that output size is the same as input size.
      • p=f−12p = \frac{f-1}{2}
  • Stride: the number of pixels the filter moves across the input image.
    • S=1S = 1: Move the filter by one pixel horizontally and vertically.
    • S=2S = 2: Move the filter by two pixels horizontally and vertically.
  • POOL: down sampling operation which reduces the dimensionality of a matrix.
    • It reduces the number of parameters for large image but retain the valuable information.
    • Max pooling: Max(7, 8, 9, 10) = 10
    • Average pooling: Avg(7, 8, 9, 10) = 8.5
    • Sum pooling: Sum(7, 8, 9, 10) = 34
  • FC: The output matrix after convolution layer is flattened and feed into a fully connected layer similar to ANN.
    • It's a traditional Multi-layer Perceptron/Neural Network.
    • For multi-class classification, Softmax activation function is usually used.
    • Output of the CONV and POOL layers represent a high-level features of the Input image.
    • FC layer uses this feature to classify the input image into the desired class.

Deep Reinforcement Learning​

  • Use DNNs to represent
    • Value and Q-Value function (Action-value function)
    • Policy (Policy Gradient methods)
    • Model
  • Use SGD to optimize loss function.
  • RL makes the target, SGD trains DNN to fit the target.
  • In TD: Δw=learning rate×TD error×gradient\Delta w = \text{learning rate} \times \text{TD error} \times \text{gradient}
    • TD error: Rt+1+γq^(st+1,at+1,w)⏟Target−q^(st,at,w)⏟Current Prediction\underbrace{R_{t+1} + \gamma \hat{q}(s_{t+1},a_{t+1},w)}_{\text{Target}} - \underbrace{\hat{q}(s_t,a_t,w)}_{\text{Current Prediction}}
  • In Q-Learning: max⁡a′Q(st+1,a′,w)\max_{a'} Q(s_{t+1},a',w) is the target.

Q-Learning with VFA​

  • Original Q-Learning converges to the optimal Q∗(s,a)Q^*(s, a) using look-up table.
  • VFA Q-Learning minimizes MSD Loss by SGD using target Q estimates instead of true Q.
    • so it can diverge due to the correlation between samples or Non-stationary targets.

Experience Replay​

Environment
│
│ experience
▼
(s, a, r, s')
│
▼
Replay Buffer D
┌──────────────────────┐
│ old experience │
│ old experience │
│ old experience │
│ old experience │
└──────────────────────┘
│
│ random sample
▼
Mini-batch
│
├──────────────► Current Q Network
│ │
│ ▼
│ Q(s,a)
│
└──────────────► Target calculation
│
▼
r + γ max Q(s',a')
│
▼
Target − Prediction
│
▼
SGD
│
▼
Update weights
  • DQN stores past transitions (s,a,r,s′)(s,a,r,s') in a replay buffer and randomly samples them for training, which reduces correlation between consecutive samples and improves training stability.
    • Sample (s,a,r,s′)(s, a, r, s') from D\mathcal{D}
    • Compute the target value of the samples s:(r+γmax⁡a′q^(s′,a′,w))s: (r + \gamma \max_{a'} \hat{q}(s',a',w))
    • Use SGD to update the network weight: Δw=α(r+γmax⁡a′q^(s′,a′,w)−q^(s,a,w))∇wq^(s,a,w)\Delta w = \alpha (r + \gamma \max_{a'} \hat{q}(s',a',w) - \hat{q}(s,a,w))\nabla_w \hat{q}(s,a,w)

Fixed Q-Targets​

[Same structure of network 2]

Current state s Next state s'
│ │
▼ ▼
Online Q Network Target Network
weights = w weights = w⁻
│ │
▼ ▼
Q(s,a;w) max Q(s',a';w⁻)
│ │
└────────── compare ────────────────┘
│
▼
Loss
│
▼
update only w
  • Improve stability by fixing the target weights used in the target calculation for multiple updates.
  • Target network uses different set of weights that the weights being updated.
  • w−w^-: set of weights used in the target.
  • ww: set of weights being updated.

r+γmax⁡a′Q(s′,a′,w−)r + \gamma \max_{a'} Q(s',a',\color{red}w^-\color{black})

  • Sample (s,a,r,s′)(s, a, r, s') from D\mathcal{D}
  • Compute the target value of the samples s:(r+γmax⁡a′Q(s′,a′,w−))s: (r + \gamma \max_{a'} Q(s',a',w^-))
  • Use SGD to update the network weight: Δw=α(r+γmax⁡a′Q(s′,a′,w−)−Q(s,a,w))∇wQ(s,a,w)\Delta w = \alpha (r + \gamma \max_{a'} Q(s',a',w^-) - Q(s,a,w))\nabla_w Q(s,a,w)

DQN​

DQN algorithm

DQN in Atari​

  • E2E learning of Q(s,a)valuesfrompixelsQ(s,a) values from pixels s$
  • Input state ss is a stack or raw pixels from last 4 frames.
  • Output is Q(s,a)Q(s,a) for 18 joystick/button positions
  • Reward is chance in score for that step.
  • Network Architecture and hyper-parameters are fixed across all games.
  • 4x84x84 stack of 4 previous frames -> 16 8x8 filters CONV -> 32 4x4 filters CONV -> 256 hidden units FC -> Fully connected linear output layer.

DQN Atari

RL 008

· 약 9분

RL Taxonomy​

Drawbacks of previous methods​

  • Large state space:
    • Go: 1017010^{170}
    • Backgammon: 102010^{20}
    • Atari games: 109 to 101110^9 \text{ to } 10^{11}
  • Scale-up model-free based techniques for prediction and control is challenging.
  • Value function used look-up table representation
    • All states has an entry in V(s)V(s)
    • All state-action pair (s,a)(s,a) has an entry in Q(s,a)Q(s,a)
  • Too many state, and stat-action pair to store in memory
  • Slow learning process for each states, due to large space.
  • Each states needs to be explored sufficiently.
  • For large MDPs
    • Function approximation: Almost near optimal value.
    • Estimate value function with function approximation.
      • v^(s,w)≈vπ(s)\hat{v}(s,w) \approx v_\pi(s)
      • q^(s,a,w)≈qπ(s,a)\hat{q}(s,a,w) \approx q_\pi(s,a)
    • Generalize from seen states to unseen states.
    • Using MC or TD learning techniques: Update parameter ww.

Function Approximation​

  • A technique for estimating unknown underlying function using historical or available observations.
  • Assumption: an underlying mapping function exists
    • f(x)≈f^(x)f(x) \approx \hat{f}(x)
  • Function: x→fyx \xrightarrow{f} y

Types of Value Function Approximation​

State-value: state ss → scalar v^(s,w)\hat{v}(s,w)

Action-value (s, a input): state ss and action aa → scalar q^(s,a,w)\hat{q}(s,a,w)

Action-value (s input, all actions out): state ss → q^(s,a1,w),…,q^(s,am,w)\hat{q}(s,a_1,w),\ldots,\hat{q}(s,a_m,w)

  • ww is the parameter vector of the function approximator.
    • e.g. Neural Network weights

Types of Function Approximator​

  • Tabular
    • V-Table: s→v(s)s \rightarrow v(s)
    • Q-Table: (s,a)→q(s,a)(s,a) \rightarrow q(s,a)
  • Decision Trees, Nearest Neighbors
    • s=[speed=49,distance=10]s = [\text{speed} = 49, \text{distance} = 10]
    • s→Decision Tree / KNN→v^(s)s \rightarrow \text{Decision Tree / KNN} \rightarrow \hat{v}(s)
  • Linear Function approximation
    • Linear Combination of Features
    • Values are linear function for features v^(s,w)=wTx(s)\hat{v}(s,w) = w^Tx(s)
    • x(s)=[speeddistancefuel]x(s) = \begin{bmatrix} \text{speed} \\ \text{distance} \\ \text{fuel} \end{bmatrix}
    • v^(s,w)=wTx(s)\hat{v}(s,w) = w^Tx(s)
    • v^(s,w)=w1x1(s)+⋯+wnxn(s)\hat{v}(s,w) = w_1x_1(s) + \cdots + w_n x_n(s)
  • Differentiable function approximation
    • v^(s,w)\hat{v}(s,w) is a differentiable function of ww, can be non-linear in ss
    • e.g. Neural Network, or CNN
      • ∂v^(s,w)∂w\frac{\partial \hat{v}(s,w)}{\partial w}
      • w←w−α∇wLw \leftarrow w - \alpha \nabla_wL
      • Pixels→CNNv^(s)\text{Pixels} \xrightarrow{CNN} \hat{v}(s)

Which FA to use?​

In principle, any FA that fits the RL framework can be used.

FANotes
TabularEasy; not scalable; does not generalise
LinearRequires good features
Differentiable (better choice)Scalable; not always well understood
Neural NetworksPerforms well
Deep Neural NetworksPopular choice; performs well
  • Need training methods that are suitable for non-stationary data.

ANN​

Logistic Regression​

L(a,y)=−ylog⁡(a)−(1−y)log⁡(1−a)\mathcal{L}(a, y) = -y \log(a) - (1-y) \log(1-a)

  • Loss function for Logistic Regression

Gradient Descent​

Goal: Find ww tht minimize J(w)J(w) or find a local minimum of J(w)J(w).

  • An iterative approach for error correction.
  • For one sample, L(a,y)=−ylog⁡(a)−(1−y)log⁡(1−a)\mathcal{L}(a, y) = -y \log(a) - (1-y) \log(1-a)
  • For mm samples,

J(w,b)=1m∑i=1mL(a(i),y(i))J(w, b) = \frac{1}{m} \sum_{i=1}^m \mathcal{L}(a^{(i)}, y^{(i)})

  • Find ww and bb that will minimize J(w,b)J(w, b)
    • min⁡w,bJ(w,b)\min_{w, b} J(w, b)
    • J(w)J(w) is loss function.

w←w−α∂J(w,b)∂w,b←b−α∂J(w,b)∂bw \leftarrow w - \alpha \frac{\partial J(w, b)}{\partial w}, \quad b \leftarrow b - \alpha \frac{\partial J(w, b)}{\partial b}

ΔwJ(w)=(∂J(w)∂w1,…,∂J(w)∂wn)\Delta w J(w) = \big(\frac{\partial J(w)}{\partial w_1}, \ldots, \frac{\partial J(w)}{\partial w_n}\big)

  • Adjust the ww in the direction of the -ve gradient.
    • w=w−αΔw,b=b−αΔbw = w - \alpha \Delta w, \quad b = b - \alpha \Delta b
    • where α\alpha is the learning rate.
    • and, Δw=∂J(w,b)∂w,Δb=∂J(w,b)∂b\Delta w = \frac{\partial J(w, b)}{\partial w}, \quad \Delta b = \frac{\partial J(w, b)}{\partial b}

ANN as a Function Approximator​

  • Need a method to estimate: Δw\Delta w
  • Method to incrementally adjust and update: ww
  • Representation of some aspects of RL environments as feature vector x(s)x(s)
  • Aspects can be approximated: V(s) or Q(s,a)V(s) \text{ or } Q(s, a)
    • Estimate value functions with function approximation.
    • V^(s,w)≈V(s)\hat{V}(s, \color{red}{w}\color{black}) \approx V(s)
    • Q^(s,a,w)≈Q(s,a)\hat{Q}(s, a, \color{red}{w}\color{black}) \approx Q(s, a)
  • A mechanism to plugin MC and TD for function approximation.

Value Function Approximation for policy evaluation​

VFA: Value Function Approximation

  • vπ(s)v_\pi(s) is given, so making it supervised.
  • v^(s,w)\hat{v}(s, w) is estimated value if it follows the policy π\pi by using ANN.
  • x→y^vsyx \rightarrow \hat{y} \quad \text{vs} \quad y (supervised learning)
  • s→v^(s,w)vsvπ(s)s \rightarrow \hat{v}(s, w) \quad \text{vs} \quad v_\pi(s) (Reinforcement learning)

J(w)=Eπ[(vπ(s)−v^(s,w))2] J(w) = \mathbb{E}_\pi[\big(v_\pi(s) - \hat{v}(s, w)\big)^2]

  • Find ww that minimizes J(w)J(w)
    • J(w)J(w): Loss function.
    • v^(s,w)\hat{v}(s, w): Guess from the value function approximation.
    • vπ(s)−v^(s,w)v_\pi(s) - \hat{v}(s, w): Error between the true value and the estimated value.
    • Eπ[⋅]\mathbb{E}_\pi[\cdot]: Expected average over all states ss according to the policy π\pi.
Δw=−12α∇wJ(w)Δw=αEπ[(vπ(s)−v^(s,w))⏟Error∇wv^(s,w)⏟Gradient]\begin{aligned} & \Delta w = -\frac{1}{2} \alpha \nabla_w J(w) \\ & \Delta w = \alpha \mathbb{E}_\pi[\underbrace{\big(v_\pi(s) - \hat{v}(s, w)\big)}_{Error} \underbrace{\nabla_w \hat{v}(s, w)}_{Gradient}] \end{aligned}
  • Δw=\Delta w = Step size X Error X Gradient

VFA with SGD​

Δw=α(vπ(s)−v^(s,w))∇wv^(s,w) \Delta w = \alpha (v_\pi(s) - \hat{v}(s, w)) \nabla_w \hat{v}(s, w)

  • Stochastic Gradient Descent sample the gradient
  • Sample a state randomly, find what vπ(s)v_\pi(s) is, and find the estimate
    • Δw=α[Error at s×Gradient at s]\Delta w = \alpha [\text{Error at } s \times \text{Gradient at } s]
    • Sample sts_t from π\pi, and update ww
  • Expected value update using SGD update is same as full gradient update
    • Random sampling will be eventually the same as full gradient update

Linear Value Function Approximation​

  • Represent Value function (state or action) by a linear combination of features
    • v^(s,w)=x(s)Tw=∑j=0nxj(s)wj\hat{v}(s, w) = x(s)^Tw = \sum_{j=0}^n x_j(s) w_j
  • Loss function: J(w)=Eπ[(vπ(s)−v^(s,w))2]J(w) = \mathbb{E}_\pi[\big(v_\pi(s) - \hat{v}(s, w)\big)^2]

Δw=α(vπ(s)−v^(s,w))⏟Errorx(s)⏟Feature\Delta w = \alpha \underbrace{\big(v_\pi(s) - \hat{v}(s, w)\big)}_{Error} \underbrace{x(s)}_{Feature}

  • Weight update: step size X Error X Feature value
  • SGD converges to global mininum

Incremental methods for prediction​

  • Real-world RL is not supervised, instead, it is guided by rewards.
  • No vπ(s)v_\pi(s) is given.
  • Instead, substitute a target for vπ(s)v_\pi(s)

Δw=α(Gt−v^(st,w))∇wv^(st,w) \Delta w = \alpha(G_t - \hat{v}(s_t, w)) \nabla_w \hat{v}(s_t, w)

  • Monte Carlo updates: target is the return GtG_t

Δw=α(Rt+1+γv^(st+1,w)⏟TD Target−v^(st,w))∇wv^(st,w) \Delta w = \alpha(\underbrace{R_{t+1} + \gamma \hat{v}(s_{t+1}, w)}_{\text{TD Target}} - \hat{v}(s_t, w)) \nabla_w \hat{v}(s_t, w)

  • TD updates: use TD Target

VFA for Monte Carlo​

  • MC return GtG_t is an unbiased, noisy sample of true value vπ(st)v_\pi(s_t)
    • if Gt=3,7,4,6,5,⋯G_t = 3, 7, 4, 6, 5, \cdots
    • but in average, 1N∑i=1NGt(i)≈vπ(s)\frac{1}{N} \sum_{i=1}^N G_t^{(i)} \approx v_\pi(s)
  • ⟨S1,G1⟩,⟨S2,G2⟩,⋯ ,⟨SN,GN⟩\langle S_1, G_1 \rangle, \langle S_2, G_2 \rangle, \cdots, \langle S_N, G_N \rangle is an estimate of vπ(s)v_\pi(s)
    • x→yx \rightarrow y (supervised learning)
    • st→Gts_t \rightarrow G_t (Reinforcement learning)
  • so it learns to v^(s,w)≈Gt\hat{v}(s, w) \approx G_t
Δw=α(Gt−v^(s,w))∇wv^(s,w)Δw=α(Gt−v^(s,w))x(s)\begin{aligned} & \Delta w = \alpha(G_t - \hat{v}(s, w)) \nabla_w \hat{v}(s, w) \\ & \Delta w = \alpha \big(G_t - \hat{v}(s, w)\big) x(s) \end{aligned}
  • In Linear VFA, v^(s,w)=wTx(s)\hat{v}(s,w) = w^Tx(s)
    • x(s)x(s) is the feature vector of state ss
    • ww is the weight vector
    • so ∇wv^(s,w)=∇w(wTx(s))=x(s)\nabla_w \hat{v}(s, w) = \nabla_w (w^Tx(s)) = x(s)
  • Update = Learning rate X Error X state features
Initialize w=0,k=1Loop:Sample k-th episode (sk1,ak1,rk1,...,SkLk) using policy πFor t=1,...Lk:if First Visit to (s) in episode k,thenGt(s)=∑j=tLkγk,jWeight update: w←w−α(Gt−v^(s,w))x(s)k=k+1\begin{aligned} & \text{Initialize } w = 0, k = 1 \\ & Loop: \\ & \quad \text{Sample k-th episode } (s_{k1}, a_{k1}, r_{k1}, ..., S_{kL_k}) \text{ using policy } \pi \\ & \quad \text{For } t = 1, ... L_k: \\ & \quad \quad \text{if First Visit to } (s) \text{ in episode } k, then \\ & \quad \quad \quad G_t(s) = \sum_{j=t}^{L_k} \gamma_{k,j} \\ & \quad \quad \quad \text{Weight update: } \quad w \leftarrow w - \alpha(G_t - \hat{v}(s,w))x(s) \\ & \quad \quad k = k + 1 \\ & \end{aligned}
  • Gt=Rt+1+γRt+2+γ2Rt+3+⋯+γLk−tRLkG_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots + \gamma^{L_k-t} R_{L_k}

VFA for TD Learning​

  • Use bootstrapping and sampling to approximate the target vπv_\pi
    • Sampling: Use a sampled transition St,At,Rt+1,St+1S_t, A_t, R_{t+1}, S_{t+1} instead of computing the full expectation over possible transitions.
    • Bootstrapping: Construct the TD target using the current estimate v^(St+1,w)\hat{v}(S_{t+1}, w), instead of waiting for the complete episodic return.

Rt+1+γv^(St+1,w)R_{t+1} + \gamma \hat{v}(S_{t+1}, w)

  • TD Target is a biased sample of true value vπ(St)v_\pi(S_t)
  • Can use supervised learning on a training set of ⟨S,R⟩\langle S, R \rangle paris
    • ⟨S1,R2+γv^(S2,w)⟩,⟨S2,R3+γv^(S3,w)⟩,⋯ ,⟨ST−1,RT⟩\langle S_1, R_2 + \gamma \hat{v}(S_2, w) \rangle, \langle S_2, R_3 + \gamma \hat{v}(S_3, w) \rangle, \cdots, \langle S_{T-1}, R_T \rangle

Δw=α(R+γv^(s′,w)−v^(s,w))∇wv^(s,w) \Delta w = \alpha(R + \gamma \hat{v}(s', w) - \hat{v}(s, w)) \nabla_w \hat{v}(s, w)

  • Linear VFA + TD(0) for prediction and policy evaluation
  • TD Error: δt=Rt+1+γv^(St+1,w)−v^(St,w)\delta_t = R_{t+1} + \gamma \hat{v}(S_{t+1}, w) - \hat{v}(S_t, w)
  • Δw=αδt∇wv^(St,w)\Delta w = \alpha \delta_t \nabla_w \hat{v}(S_t, w)
    • ∇wv^(s,w)=x(s)\nabla_w \hat{v}(s, w) = x(s)
    • Δw=αδtx(s)\Delta w = \alpha \delta_t x(s)
    • w←w−αδtx(s)w \leftarrow w - \alpha \delta_t x(s)
Initialize w=0Loop:Initialize sSample transition (s,a,r,s′) using policy πWeight update: w←w−α(R+γv^(s′,w)−v^(s,w))x(s)\begin{aligned} & \text{Initialize } w = 0 \\ & Loop: \\ & \quad \text{Initialize } s \\ & \quad \text{Sample transition } (s, a, r, s') \text{ using policy } \pi \\ & \quad \text{Weight update: } \quad w \leftarrow w - \alpha(R + \gamma \hat{v}(s', w) - \hat{v}(s, w))x(s) \\ & \end{aligned}

Overall​

  • Linear VFA: v^(s,w)=wTx(s)\hat{v}(s, w) = w^Tx(s)
  • MC Target = GtG_t
  • TD Target = Rt+1+γv^(s′,w)R_{t+1} + \gamma \hat{v}(s', w)
  • MC: w←w+α(Gt−v^(s,w))x(s)w \leftarrow w + \alpha(G_t - \hat{v}(s, w)) x(s)
  • TD: w←w+α(Rt+1+γv^(s′,w)−v^(s,w))x(s)w \leftarrow w + \alpha(R_{t+1} + \gamma \hat{v}(s', w) - \hat{v}(s, w))x(s)

IPPR 003

· 약 10분

Feature Detection​

  1. Detect invariant features of the image.
  2. Describe the local area around each feature.
  3. Match patterns of the feature descriptions.

Moravec conner detector​

E(u,v)=∑x,y[I(x,y)−I(x+u,y+v)]2E(u, v) = \sum_{x, y} [I(x, y) - I(x + u, y + v)]^2

  • One of the earliest corner detectors (1980)
  • Moravec detects a corner by shifting a small window in different directions and checking whether the image changes significantly in every direction.
    • Shifting a window in any direction should give a large change in intensity, measured in terms of Sum of Squared Differences (SSD).
  • (u,v)(u, v) is how much the window is shifted.
  • Larger EE indicates the image changes more after the shift.

Moravec corner detection

  • Flat: E≈0E \approx 0, No change in any direction
  • Edge: E≈1E \approx 1, Change in some direction
  • Corner: E≈40E \approx 40, Large change in every direction

Harris corner detector​

E(x,y)=∑u∑vW(u,v)⏟Window function[I(u+x,v+y)⏟Shifted Intensity−I(u,v)⏟Intensity]2 E(x, y) = \sum_{u}\sum_{v} \underbrace{W(u, v)}_{\text{Window function}} [\underbrace{I(u + x, v + y)}_{\text{Shifted Intensity}} - \underbrace{I(u, v)}_{\text{Intensity}}]^2

  • Improvement over Moravec change of intensify for a shifted windoe centered at (u,v)(u, v)

Harris corner detection

  • (x,y)=(1,0)→(x, y) = (1, 0) \rightarrow move 1px to the right.
  • (x,y)=(0,1)→(x, y) = (0, 1) \rightarrow move down 1px.
  • (x,y)=(2,1)→(x, y) = (2, 1) \rightarrow move 2px to the right and 1px down.
  • I(u,v)I(u, v): Pixel intensity of the original point.
  • I(u+x,v+y)I(u + x, v + y): Pixel intensity of the shifted point.
  • SSD: if I(u,v)=65I(u,v) = 65, and I(u+x,v+y)=124I(u + x, v+ y) = 124, then the SSD is (124−65)2=3481(124 - 65)^2 = 3481.
  • w(u,v)w(u, v): window function, usually apply gaussian weighting to the pixels around the center.
    • if we calculate all the (x,y)(x, y) step by step, it will be computationally expensive.
    • so we use Taylor Expansion to approximate the intensity change.

Taylor Expansion​

I(u+x,v+y)≈I(u,v)+Ix(u,v)x+Iy(u,v)yI(u + x, v + y) \approx I(u, v) + I_x(u, v)x + I_y(u, v)y

  • Let IxI_x and IyI_y be the partial derivatives of II
  • Approximates the intensity of the slightly shifted point, using the current intensity and gradient information.
  • Ix=∂I∂xI_x = \frac{\partial I}{\partial x}: How much the intensity changes when moving to the right or left a little bit.
  • Iy=∂I∂yI_y = \frac{\partial I}{\partial y}: How much the intensity changes when moving up or down a little bit.

E(x,y)≈∑u∑vw(u,v)[Ix(u,v)x+Iy(u,v)y]2E(x, y) \approx \sum_{u}\sum_{v} w(u, v) [I_x(u, v)x + I_y(u, v)y]^2

  • because I(u+x,v+y)≈I(u,v)+Ix(u,v)x+Iy(u,v)yI(u + x, v + y) \approx I(u, v) + I_x(u, v)x + I_y(u, v)y.
  • we can calculate intensity change by x/y gradient and the window shift.
  • (ax+by)2=a2x2+2abxy+b2y2=[x,y][a2ababb2][xy](ax + by)^2 = a^2x^2 + 2abxy + b^2y^2 = [x, y] \begin{bmatrix} a^2 & ab \\ ab & b^2 \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix}

E(x,y)=[x,y][∑u∑vw(u,v)Ix2∑u∑vw(u,v)IxIy∑u∑vw(u,v)IxIy∑u∑vw(u,v)Iy2]⏟A[xy]E(x,y) = [x, y] \underbrace{\begin{bmatrix} \sum_{u}\sum_{v} w(u, v) I_x^2 & \sum_{u}\sum_{v} w(u, v) I_xI_y \\ \sum_{u}\sum_{v} w(u, v) I_xI_y & \sum_{u}\sum_{v} w(u, v) I_y^2 \end{bmatrix}}_{A} \begin{bmatrix} x \\ y \end{bmatrix}

  • Eigenvector = direction of the change
  • Eigenvalue = magnitude of the change
  • if both λ1 and λ2≈0\lambda_1 \text{ and } \lambda_2 \approx 0, the point is flat.
  • if either λ1 or λ2≫0\lambda_1 \text{ or } \lambda_2 \gg 0 the point is an edge.
  • if both λ1 and λ2≪0\lambda_1 \text{ and } \lambda_2 \ll 0 the point is a corner.

R=det⁡(A)−k(trace(A))2R = \det(A) - k(\text{trace}(A))^2

  • det⁡(A)=λ1λ2\det(A) = \lambda_1 \lambda_2
    • it can check if the point is a corner by checking if λ1 and λ2\lambda_1 \text{ and } \lambda_2 are both large.
  • trace(A)=λ1+λ2\text{trace}(A) = \lambda_1 + \lambda_2
    • it can penalizes edge-like responses where one eigenvalue is large but the other is small.
  • R=λ1λ2−k(λ1+λ2)2R = \lambda_1 \lambda_2 - k(\lambda_1 + \lambda_2)^2
    • kk is an empirical constant, typically set 0.04≤k≤0.060.04 \leq k \leq 0.06.
    • A threshold is applied an corners detected, non-maxima are suppressed.
    • RR can be derived from eigenvalues of the matrix AA.
    • R≈0R \approx 0 the point is flat.
    • R<0R < 0 the point is an edge.
    • R≫0R \gg 0 the point is a corner.

Harris corner detection pipeline​

  • Compute the Harris response RR for every pixel.
  • Large positive RR indicates a strong corner response.
  • Apply a threshold to remove weak responses.
  • Apply non-maximum suppression to keep only local maxima.
  • Overlay the remaining points on the original image as detected corners.

Detector vs descriptor​

  • Detector: detect the location of the features in an image or video (WHERE).
  • Descriptor: descriptors summarize the appearance of the neighborhood (WHAT IT LOOKS LIKE).
  • A good feature detector should be:
    • make similar descriptors for similar features of the same object.
    • Invariance: the descriptor should be invariant to translation, rotation, scale, and illumination.

SIFT​

Scale-Invariant Feature Transform

  • It was proposed by Lowe in 1999, includes both a detector and a descriptor.
  • A method to detect and match local features despite changes in scale and rotation.
  • Core idea: build multiple blurred versions of the image, compute their differences, and find points that stand out across scales.
  1. Build a scale-space pyramid of Differences of Gaussians (DoG) and detect minima/maxima.
  2. Localize keypoints.
  3. Assign them an orientation.
  4. Compute the SIFT descriptor.

DoG pyramid

  • L(x,y,σ)=G(x,y,σ)∗I(x,y)L(x, y, \sigma) = G(x, y, \sigma) * I(x, y): Blurred image at scale σ\sigma.
  • D(x,y,σ)=L(x,y,kσ)−L(x,y,σ)D(x, y, \sigma) = L(x, y, k\sigma) - L(x, y, \sigma): Difference of Gaussians at scale σ\sigma.
  • Octave: a group of scale-space images at the same resolution.
  • After each octave, the image is typically downsampled by a factor of 2.

DoG octave

Key point localization​

Image→Gaussian scale space→DoG→DoG extrema→Filter low-contrast and edge responses→Keypoints\text{Image} \rightarrow \text{Gaussian scale space} \rightarrow \text{DoG} \rightarrow \text{DoG extrema} \rightarrow \text{Filter low-contrast and edge responses} \rightarrow \text{Keypoints}

  • Detect local maxima and minima in DoG scale space.
  • Remove low-contrast points because they are unstable and sensitive to noise.
  • Remove edge responses because their locations are poorly localized.
  • Use the ratio of principal curvatures to distinguish edges from stable corner/blob-like features.
  • Example: 832→729→536832 \rightarrow 729 \rightarrow 536

DoG Keypoints

  • (a): Original image (233x189)
  • (b): 832 DoG extrema
  • (c): 729 left after peak-value threshold
  • (d): left after testing the ratio of principal curvatures.

Orientation assignment​

  • For every keypoint, compute the gradient at each location in its local neighborhood.
  • The gradients are computed on the Gaussian-blurred image at the keypoint's scale, σ\sigma.
  • Gradient directions are quantized into 36 bins over 360∘360^\circ.
  • Each gradient contributes to the histogram according to its magnitude.
  • The dominant histogram bin is assigned as the keypoint's orientation.
    • [10,20,20,30,20]→20[10, 20, 20, 30, 20] \rightarrow 20
    • This orientation becomes the anchor direction for the SIFT descriptor.

SIFT descriptor​

SIFT descriptor = 128-dimensional vector

  • A 16x16 grid of locations of the gradient at σ\sigma scale around the keypoint.
  • The grid is divided into 4x4 sub-grids of 4x4 locations each.
  • For each sub-grid, an 8-bin histogram of the magnitude weighted gradient orientation is computed.
    • All 8 bins are retained.
  • The histogram from all the sub-grids are concatenated into the SIFT descriptor.
    • The dimensionality is given by 8 bins x 16 histograms = 128.

Image→Gaussian scale space→DoG→DoG extrema→Filter low-contrast and edge responses→Keypoints→Assign orientation→Build 128-D descriptor\text{Image} \rightarrow \text{Gaussian scale space} \rightarrow \text{DoG} \rightarrow \text{DoG extrema} \rightarrow \text{Filter low-contrast and edge responses} \rightarrow \text{Keypoints} \rightarrow \text{Assign orientation} \rightarrow \text{Build 128-D descriptor}

SIFT descriptor

  • SIFT Features encode information about at 16x16 area around the feature point at the appropriate scale.
  • It is scale, rotation, and translation invariant.
  • Similar features give similar SIFT values regardless of orientation, scale, and translation.

SIFT wolf

Applications of SIFT​

  • Object recognition: SIFT descriptors are extracted from an input image and matched to the SIFT descriptors of known objects in a database.
  • Stereo vision: SIFT descriptors from the left and right images are matched to create the disparity map.
  • Tracking: SIFT descriptors from successive frames are matched to track a target.
  • Object and action classification: histograms of SIFT descriptors are computed over single frames or whole videos and used as input for a classifier.

Object classification​

  • Object classification uses histograms of SIFT descriptors to characterize the class of an object.
  • A popular histogram representation is called Bag of Features (BoF).
    • BoF first requires creating a dictionary, also called a codebook, from the training set.
    • Once the dictionary is computed, a Bag of Features can be computed for any image.
    • The resulting Bag of Features is then used for classification.
# Example SIFT descriptors from training images
descriptors = [
[1.0, 1.2],
[0.9, 1.1],
[1.1, 0.8],

[5.0, 5.1],
[4.8, 5.2],
[5.2, 4.9],

[9.0, 1.0],
[8.8, 1.2],
]

# Representative descriptors after clustering
codebook = [
[1.0, 1.0], # codeword 1
[5.0, 5.0], # codeword 2
[9.0, 1.0], # codeword 3
]

# SIFT descriptors from a new image
new_image_descriptors = [
[1.2, 0.9],
[0.8, 1.1],
[5.1, 4.9],
[9.2, 1.1],
[8.9, 0.8],
]

# Nearest codeword assignments
assignments = [
0, # -> codeword 1
0, # -> codeword 1
1, # -> codeword 2
2, # -> codeword 3
2, # -> codeword 3
]

# Bag of Features histogram
bof = [2, 1, 2]

Dictionary creation​

  • Extract all SIFT descriptors from the training images.
  • Use a clustering algorithm, typically k-means, to group the descriptors into kk clusters.
  • The descriptor space is partitioned into kk regions.
    • Example: k=1000k=1000.
  • The resulting clusters form the dictionary/codebook.

Detection creation

Bag of Features​

  • Map all SIFT descriptors of an image to clusters in the dictionary.
  • Count the number of descriptors assigned to each cluster.
  • Form a histogram with kk bins.
  • Use this histogram as a measurement vector for a classifier.
  • Possible classifiers include Bayes, SVM, KNN, and neural networks.

Other Local Features​

  • SURF (Speeded Up Robust Features): another local feature method designed to provide robust features with faster computation.
  • GLOH (Gradient Location and Orientation Histogram): describes local image structure using gradient location and orientation histograms.
  • HOG (Histogram of Oriented Gradients): represents local regions using histograms of gradient orientations.
  • For classification, descriptors can be extracted either from detected interest points or from a regular grid.
  • Descriptors extracted from a regular grid are called dense features.

Spatio-temporal local features​

  • In video, local features can be extracted from each frame separately or as 3D local features.
  • Here, “3D” means x,y,tx, y, t, where tt is time.
  • These are called spatio-temporal features.
  • They describe the appearance of local cuboids across space and time.

Cuboids

Other Spatio-temporal local features​

  • HOG/HOF: Histogram of Optical Flow.
  • HOG3D: a spatio-temporal extension of HOG.
  • ESURF: Extended SURF.
  • MBH: Motion Boundary Histograms.
  • DTF: Dense Trajectory Features.
  • For classification, these descriptors can be computed either at detected points or over a regular grid.

Object Classification FLow​

Object Classification Flow

  • Local descriptors: An image is represented by many local feature descriptors such as SIFT or HOG. The result is a set of descriptors, not a single vector.
  • Encoding: Since different images can produce different numbers of descriptors, the set of descriptors is converted into one fixed-length vector. Bag of Features, VLAD, and Fisher Vector are different encoding methods for this purpose.
    • Bag of Features: Each descriptor is assigned to the nearest representative feature, and the number of descriptors assigned to each representative feature is counted.
    • VLAD: Instead of only counting assignments, VLAD stores how each descriptor differs from its nearest representative feature.
    • Fisher Vector: It represents how the descriptors differ from a learned feature distribution, capturing more detailed statistical information.
  • Classifier: The encoded fixed-length vector is given to a classifier, which outputs a class label such as car, person, or dog.
  • Main idea: SIFT describes many local regions, while BoF, VLAD, and Fisher Vector combine those local descriptions into one image-level vector for classification.

RL 007

· 약 7분

Temporal-Difference Learning​

Updates a guess towards a guess.

  • Model-free: No MDP Dynamics or Rewards
  • Learns directly from episodes of experience.
  • Bootstrapping: Estimate value function using estimated value from incomplete episodes.
    • Update estimate using another estimate.
  • Updates the estimate of VV immediately after each step.
  • Combines Monte Carlo and Dynamic Programming (Bootstrapping idea).

MC​

V(St)=V(St)+α[Gt⏟Goal−V(St)⏟Previous estimate]V(S_t) = V(S_t) + \alpha [\underbrace{G_t}_{\text{Goal}} - \underbrace{V(S_t)}_{\text{Previous estimate}} ]

  • Update V(St)V(S_t) towards the actual return.
  • α=1n\alpha = \frac{1}{n}: Every-visit MC.
    • gives equal weight to all past samples in the arithmetic mean.
  • Fixed α>1n\alpha > \frac{1}{n}: gives more weight to recent experience and reduces the influence of older episodes faster.
    • α=0.1,V(S)=10\alpha = 0.1, \quad V(S) = 10
    • V(S)←10+0.1(20−10)=11V(S) \leftarrow 10 + 0.1 (20 - 10) = 11
    • V(S)←11+0.1(30−11)=12.9V(S) \leftarrow 11 + 0.1 (30 - 11) = 12.9
    • Move 10% of the way towards the new value.

One-Step Bootstrapping​

TD(0)→TD(λ)→TD(1)≈MC\text{TD}(0) \rightarrow \text{TD}(\lambda) \rightarrow \text{TD}(1) \approx \text{MC}

  • λ\lambda controls how much longer-term return information is used in the TD update.
    • It controls how far into the future TD learns from.
  • λ=0\lambda = 0: uses one-step bootstrapping, corresponding to TD(0).
  • As λ\lambda increases, rewards further into the future have more influence on the update.
  • λ=1\lambda = 1: approaches the Monte Carlo return in episodic tasks.

V(St)=V(St)+α[Rt+1+γV(St+1)⏟TD target−V(St)⏟TD Error]V(S_t) = V(S_t) + \alpha [\underbrace{\underbrace{R_{t+1} + \gamma V(S_{t+1})}_{\text{TD target}} - V(S_t)}_{\text{TD Error}} ]

  • Only one immediate reward is used Rt+1R_{t+1}.
  • Everything after that is replaced by the current guess V(St+1)V(S_{t+1}) instead of actual future rewards.
  • It uses actual reward for the first step and the estimated value/guess for the rest.
MC
Sₜ ──Rₜ₊₁──> Sₜ₊₁ ──Rₜ₊₂──> ... ──> Terminal
│ │
└────────── episode 끝까지 기다림 ────────┘
↓
actual Gₜ
↓
V(Sₜ) update


TD(0)
Sₜ ──Rₜ₊₁──> Sₜ₊₁ ── ? ──> ...
│ │
│ └─ current V(Sₜ₊₁)
│
└── Rₜ₊₁ + γV(Sₜ₊₁)로 즉시 V(Sₜ) update

TD(0) Algorithm​

Loop for each episode:InitializeSLoop for each step of the episode:A←action given by policyπTake actionA,observeR,S′V(S)←V(S)+α[R+γV(S′)−V(S)]S←S′UntilS is terminal\begin{aligned} &\text{Loop for each episode:} \\ &\quad \text{Initialize} \quad S \\ &\quad \text{Loop for each step of the episode:} \\ &\quad \quad A \leftarrow \text{action given by policy} \quad \pi \\ &\quad \quad \text{Take action} \quad A, \quad \text{observe} \quad R, \quad S' \\ &\quad \quad V(S) \leftarrow V(S) + \alpha [R + \gamma V(S') - V(S)] \\ &\quad \quad S \leftarrow S' \\ &\quad \text{Until} \quad S \text{ is terminal} \\ \end{aligned}
  • No need to wait until the end of the episode to update the value function.

MC vs. TD​

AspectMonte Carlo (MC)Temporal-Difference (TD)
Learning sequenceLearns from complete episodesLearns from incomplete episodes
TargetActual return GtG_tEstimated return using bootstrapping
Update timingAfter the episode endsBefore the episode ends / step by step
Future informationUses actual future rewardsUses observed reward(s) + estimated future value
BootstrappingNoYes
BiasUnbiasedBiased
VarianceHighLow
EnvironmentEpisodic / terminating environmentsAlso works in continuing / non-terminating environments
Practical speedSlower updatesFaster updates in practice

RMS Error Comparison between MC and TD

  • In practice, TD is faster than MC because it can learn from incomplete episodes.

MC, TD, and DP

  • MC: Full sampled path to the end.
  • TD: Just one real step.
  • DP: Every branch, weighted by probability, no sampling.

Backup Methods

SARSA​

St,At,Rt+1,St+1,At+1S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}

  • Follows generalized Policy Iteration.
    • Policy Evaluation: TD Policy Evaluation Q≈qπQ \approx q_\pi
    • Policy Improvement: ϵ\epsilon-greedy policy improvement, allowing exploration.
    • Update happens after every time step.
  • Use TD methods for evaluation. Q(S,A)Q(S, A)
  • TD Evaluation + ϵ\epsilon-greedy Policy Improvement = SARSA

Q(St,At)=Q(St,At)+α[Rt+1+γQ(St+1,At+1)⏟TD target−Q(St,At)]Q(S_t, A_t) = Q(S_t, A_t) + \alpha [\underbrace{R_{t+1} + \gamma Q(S_{t+1}, A_{t+1})}_{\text{TD target}} - Q(S_t, A_t)]

  • (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}): transition from one state-action pair to the next.
  • The process repeatedly alternates between improving QQ and improving the policy.
  • The estimates gradually move toward the optimal action-value function q∗q_* and the optimal policy π∗\pi_*.
  • Unlike classical policy iteration, SARSA does not need to complete policy evaluation before improving the policy.

SARSA Example​

  • Q(St,At)=10Q(S_t,A_t)=10
  • Rt+1=2R_{t+1}=2
  • γ=0.9\gamma=0.9
  • α=0.5\alpha=0.5
  • Q(St+1,At+1)=8Q(S_{t+1},A_{t+1})=8
  • TD Target =2+0.9(8)=9.2=2+0.9(8)=9.2
  • TD Error =9.2−10=−0.8=9.2-10=-0.8
  • Updated Q(St,At)=10+0.5(−0.8)=9.6Q(S_t,A_t)=10+0.5(-0.8)=9.6

SARSA Algorithm​

Loop for each episode:InitializeSChooseAt from St using policy π derived from QLoop for each step of the episode:Take actionAt+1,observeRt+1,St+1Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)−Q(St,At)]St←St+1At←At+1UntilS is terminal\begin{aligned} &\text{Loop for each episode:} \\ &\quad \text{Initialize} \quad S \\ &\quad \text{Choose} A_t \text{ from } S_t \text{ using policy } \pi \text{ derived from } Q\\ &\quad \text{Loop for each step of the episode:} \\ &\quad \quad \text{Take action} \quad A_{t+1}, \quad \text{observe} \quad R_{t+1}, \quad S_{t+1} \\ &\quad \quad Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha [R_{t+1} + \gamma Q(S_{t+1}, A_{t+1}) - Q(S_t, A_t)] \\ &\quad \quad S_t \leftarrow S_{t+1} \\ &\quad \quad A_t \leftarrow A_{t+1} \\ &\quad \text{Until} \quad S \text{ is terminal} \\ \end{aligned}
  • As SARSA learns, each episode is completed faster.
  • As the Q-values improve, the agent learns better actions for each state and reaches the goal using fewer steps.

Q-Learning​

  • On-policy: SARSA, behavior policy is the same as the target policy.
  • Off-policy: Q-Learning, behavior policy is different from the target policy. Q(S,A)Q(S, A)
  • Update Q(St,At)Q(S_t, A_t) toward the value of the alternative, best action.

Q(St,At)=Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)⏟TD target−Q(St,At)] Q(S_t, A_t) = Q(S_t, A_t) + \alpha [\underbrace{R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a)}_{\text{TD target}} - Q(S_t, A_t)]

  • The Actual next action is replaced by the Best possible action.
  • Q(St,At)=10Q(S_t, A_t)=10
  • Rt+1=2R_{t+1}=2
  • γ=0.9\gamma=0.9
  • α=0.5\alpha=0.5
  • Q(St+1,a1)=8Q(S_{t+1}, a_1)=8
  • Q(St+1,a2)=11Q(S_{t+1}, a_2)=11
  • Q(St+1,a3)=5Q(S_{t+1}, a_3)=5
  • TD Target =2+0.9(11)=11.9=2+0.9(11)=11.9
  • TD Error =11.9−10=1.9=11.9-10=1.9
  • Updated Q(St,At)=10+0.5(1.9)=10.95Q(S_t, A_t)=10+0.5(1.9)=10.95

Q-Learning Algorithm​

Loop for each episode:InitializeSLoop for each step of the episode:At fromSt using policy π derived from QTake actionAt+1,observeRt+1,St+1Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)−Q(St,At)]St←St+1UntilS is terminal\begin{aligned} &\text{Loop for each episode:} \\ &\quad \text{Initialize} \quad S \\ &\quad \text{Loop for each step of the episode:} \\ &\quad \quad A_t \text{ from} S_t \text{ using policy } \pi \text{ derived from } Q\\ &\quad \quad \text{Take action} \quad A_{t+1}, \quad \text{observe} \quad R_{t+1}, \quad S_{t+1} \\ &\quad \quad Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha [R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a) - Q(S_t, A_t)] \\ &\quad \quad S_t \leftarrow S_{t+1} \\ &\quad \text{Until} \quad S \text{ is terminal} \\ \end{aligned}

Cliff Walking​

Cliff Walking

  • SARSA (on-policy) accounts for ε-greedy exploration near the cliff and learns the safer route.
  • Q-Learning (off-policy) learns the optimal route.
    • but occasionally falls off the cliff during exploration, hurting its online performance

Cliff Walking Rewards

AspectSARSAQ-Learning
Policy typeOn-policyOff-policy
Bootstrap targetQ(St+1,At+1)Q(S_{t+1},A_{t+1})max⁡aQ(St+1,a)\max_a Q(S_{t+1},a)
Next action usedAction actually takenBest possible action
LearnsValue of the behavior policy being followedOptimal policy π∗\pi_*
Cliff WalkingSafer pathOptimal but riskier path

RL 006

· 약 12분

Known MDP vs Unknown MDP​

AspectKnown MDPUnknown MDP
Environment Knowledge (P,RP, R)Full knowledge of state transition dynamics PP and reward function RRPP and RR are unknown; agent must explore the environment
Problem ApproachWell-defined optimization problem →\rightarrow Pure planning via computationTrial-and-error interaction →\rightarrow Must learn and optimize simultaneously
Primary GoalDirectly compute the optimal policy (π∗\pi_*)Learn and optimize policies without prior model knowledge
Representative MethodsValue Iteration, Policy Iteration (Dynamic Programming)Monte Carlo, Q-Learning, SARSA (Reinforcement Learning)
ParadigmModel-based (Planning)Model-free (Reinforcement Learning)

Model-based vs Model-free​

AspectModel-Based LearningModel-Free Learning
Model Access (P,RP, R)Has full access to transition dynamics PP and reward function RRNo access to environment dynamics (PP and RR are unknown)
Optimization ApproachDirect mathematical computation and planning using the known modelDirect learning and trial-and-error optimization through interaction
Estimation SourceComputes values and optimal policy π∗\pi_* via dynamic programming equationsEstimates vπ,qπv_\pi, q_\pi, and π∗\pi_* directly from sampled experience
Computation vs. SamplingPure computation / Planning (requires no real-time environment sampling)Sample-based learning (requires trajectories / episodic experience)
Typical MethodsPolicy Iteration, Value Iteration (DP)Monte Carlo Methods, TD Learning, Q-Learning, SARSA

Monte Carlo Methods​

  • A Computational technique that uses random sampling and statistical methods to solve complex problems and estimate numerical results.
    • Named after the Monte Carlo Casino in Monaco.
    • It means Estimate an unknown quantity by sampling, and averaging what you observe.
  • Used fo any estimation method whose operation involves a significant random component.
  • Used in mathematics, physics, engineering, finance, computer science, etc.
  • It is particularly valuable when an analytical solution is difficult or impossible to obtain.

Estimating π\pi by Sampling (Monte Carlo Simulation)​

  • Mechanism:
    • Generate uniform random points (x,y)∈[−1,1]×[−1,1](x, y) \in [-1, 1] \times [-1, 1].
    • Count points falling inside the unit circle (x2+y2≤1x^2 + y^2 \le 1).
    • Estimate π\pi via area proportions:
AreacircleAreasquare=π4π≈4×#points inside circle#total points\begin{aligned} \frac{\text{Area}_{circle}}{\text{Area}_{square}} = \frac{\pi}{4} \\ & \pi \approx 4 \times \frac{\text{\#points inside circle}}{\text{\#total points}} \end{aligned}
  • Empirical Validation:
    • Total samples (nn): 30003000 points
    • Estimated value: π=3.1386666666666665\pi = 3.1386666666666665
    • Relative error: −0.0931%-0.0931\% from true value (≈3.14159265\approx 3.14159265)

Monte Carlo

Monte Carlo Prediction​

vπ(s)=Eπ[Gt∣St=s]≈1N∑i=1N(s)G(i)v_\pi(s) = \mathbb{E}_{\pi}[G_t | S_t = s] \approx \frac{1}{N} \sum_{i=1}^{N(s)} G^{(i)}

  • 1N∑i=1N(s)G(i)\frac{1}{N} \sum_{i=1}^{N(s)} G^{(i)}: Mean of the returns/rewards
  • Model-Free Learning: Operates without prior knowledge of transition dynamics PP or reward function RR.
  • Learning from Complete Episodes: Learns state-value functions vπv_\pi exclusively from full trajectories under policy π\pi. Only works for episodic tasks where termination at step TT is guaranteed.
  • No Bootstrapping: Does not update estimates using other value estimates v(s′)v(s'); instead, updates rely solely on actual empirical returns observed at the end of the episode.
  • Empirical Mean Returns: The value of state ss is estimated by the sample average of all observed returns starting from ss:

An Episode of Experience & Return Formulation​

  • Trajectory Structure: S0→A0,R1S1→A1,R2S2⋯→AT−1,RTSTS_0 \xrightarrow{A_0, R_1} S_1 \xrightarrow{A_1, R_2} S_2 \dots \xrightarrow{A_{T-1}, R_T} S_T
  • Discounted Return (GtG_t): Gt=Rt+1+γRt+2+γ2Rt+3+⋯+γT−t−1RTG_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots + \gamma^{T-t-1} R_T
  • Discount Factor (γ=1\gamma = 1): For episodic tasks with terminal-only rewards (such as Blackjack), setting γ=1\gamma = 1 is standard practice because the episode length is finite.

First-Visit Monte Carlo​

  • First-Visit MC estimates the value function V(s)V(s) by averaging returns following only the first occurrence of state ss within each sampled episode.
  • Algorithmic Flow:
    • Initialize counters N(s)←0N(s) \leftarrow 0 and accumulate returns: G(s)←0∀s∈SG(s) \leftarrow 0 \quad \forall s \in S
    • Sample a complete episode i={Si,0,Ai,1,Ri,2,…,Si,Ti}i = \{S_{i,0}, A_{i,1}, R_{i,2}, \dots, S_{i,T_i}\} generated under policy π\pi
    • Compute return Gi,t=∑k=t+1Tiγk−t−1Ri,kG_{i,t} = \sum_{k=t+1}^{T_i} \gamma^{k-t-1} R_{i,k} from step tt to termination.
    • Only for the first time step tt where state ss appears in episode ii:
      • N(s)←N(s)+1N(s) \leftarrow N(s) + 1 (Increment counter for total first visits)
      • G(s)←G(s)+Gi,tG(s) \leftarrow G(s) + G_{i,t} (Increment total return)
      • V(s)←G(s)N(s)V(s) \leftarrow \frac{G(s)}{N(s)} (Update the value by mean return)

A→R1=1B→R2=2A→R3=1C→R4=1terminalA \xrightarrow{R_1=1} B \xrightarrow{R_2=2} A \xrightarrow{R_3 = 1} C \xrightarrow{R_4 = 1} \text{terminal}

State sN(s)N(s)G(s)G(s)V(s)=G(s)N(s)V(s) = \frac{G(s)}{N(s)}
A199.00
B188.00
C155.00

Every-Visit Monte Carlo​

  • Every-Visit MC treats every single occurrence of state ss within an episode as a valid data sample, accumulating its corresponding return into the empirical mean.
  • Algorithmic Flow:
    • Initialize counters N(s)←0N(s) \leftarrow 0 and accumulate returns: G(s)←0∀s∈SG(s) \leftarrow 0 \quad \forall s \in S
    • Sample a complete episode i={Si,0,Ai,1,Ri,2,…,Si,Ti}i = \{S_{i,0}, A_{i,1}, R_{i,2}, \dots, S_{i,T_i}\} generated under policy π\pi
    • Compute return Gi,t=∑k=t+1Tiγk−t−1Ri,kG_{i,t} = \sum_{k=t+1}^{T_i} \gamma^{k-t-1} R_{i,k} from step tt to termination.
    • For each time step tt where state ss appears in episode ii:
      • N(s)←N(s)+1N(s) \leftarrow N(s) + 1 (Increment counter for total visits)
      • G(s)←G(s)+Gi,tG(s) \leftarrow G(s) + G_{i,t} (Increment total return)
      • V(s)←G(s)N(s)V(s) \leftarrow \frac{G(s)}{N(s)} (Update the value by mean return)

A→R1=1B→R2=2A→R3=1C→R4=1terminalA \xrightarrow{R_1=1} B \xrightarrow{R_2=2} A \xrightarrow{R_3 = 1} C \xrightarrow{R_4 = 1} \text{terminal}

State sN(s)N(s)G(s)G(s)V(s)=G(s)N(s)V(s) = \frac{G(s)}{N(s)}
A29+6=157.50
B188.00
C155.00
DimensionFirst-Visit MCEvery-Visit MC
Returns used per episodeOnly the first occurrenceEvery occurrence
Sample independenceIndependent across episodes (i.i.d.)Correlated within an episode (mitigated by sampling)
Bias (finite samples)UnbiasedBiased, but bias→0\text{bias} \to 0
ConvergenceConsistent (Law of Large Numbers)Consistent (as episodes→∞\text{episodes} \to \infty)
ImplementationRequires a "seen this episode?" checkSimpler — no check needed
Practical UseStandard theoretical baselineFrequently preferred (uses all available data)

Incremental Mean​

μk=1k∑j=1kxj\mu_k = \frac{1}{k} \sum_{j=1}^{k} x_j

μk+1=1k+1∑j=1k+1xj=1k+1(∑j=1kxj+xk+1)=1k+1(kμk+xk+1)=μk+1k+1(xk+1−μk)\begin{aligned} \mu_{k+1} &= \frac{1}{k+1} \sum_{j=1}^{k+1} x_j \\ &= \frac{1}{k+1} \left( \sum_{j=1}^{k} x_j + x_{k+1} \right) \\ &= \frac{1}{k+1} \left( k \mu_k + x_{k+1} \right) \\ &= \mu_k + \frac{1}{k+1} (x_{k+1} - \mu_k) \end{aligned}
  • New estimate = Old estimate + step-size * (new sample - old estimate).
  • Memory efficient: Only need to store the old estimate (μk\mu_k) and the number of visits (kk).

Incremental Monte Carlo​

  • Updates the value function V(s)V(s) incrementally after each trajectory without requiring memory to store individual past returns.
  • Algorithmic Flow:
    • Initialize N(s)←0N(s) \leftarrow 0 and V(s)←0V(s) \leftarrow 0 for all s∈Ss \in S.
    • Episode sampling: Execute episode ii under policy π\pi and compute returns Gi,t=∑k=t+1Tiγk−t−1RkG_{i,t} = \sum_{k=t+1}^{T_i} \gamma^{k-t-1} R_{k}.
    • Incremental update: For each visited state ss at time step tt:
      • N(s)←N(s)+1N(s) \leftarrow N(s) + 1 (Increment counter for total visits)
      • V(s)←V(s)+α(Gi,t−V(s))V(s) \leftarrow V(s) + \alpha (G_{i,t} - V(s)) (Update the value by mean return)
      • Where Gi,t−V(s)G_{i,t} - V(s) represents the temporal difference (TD) error between the sampled return target and the current estimate.
  • Choice step size α\alpha
    • α=1N(s)\alpha = \frac{1}{N(s)}: Replicates the exact empirical sample-average of Every-Visit MC where all observed samples receive equal weight.
    • α=constant\alpha = \text{constant}: Implements an exponential recency-weighted running average that decays outdated experience, making it suited for non-stationary environments where MDP dynamics change over time.
  • Cons:
    • Requires a significant number of episodes to converge to the true value function.
    • Requires to terminate the episode.

Model-free Control​

  • The MDP model is unknown, or too large/complex to use directly.
  • But experience can be sampled.
  • Applications:
    • Robo soccer
    • Autonomous vehicles
    • Robotics
    • Game playing
    • Recommender systems
    • Finance & portfolio management

On-Policy vs Off-Policy​

DimensionOn-Policy LearningOff-Policy Learning
DefinitionEvaluates and improves the exact same policy currently used to generate action decisionsEvaluates/improves a target policy (π\pi) while behaving via a different behavior policy (bb)
Data GenerationTrajectories must be generated by the current active policy π\piTrajectories can come from exploratory policies, historical logs, or human demonstrations
Exploration Trade-offMust balance exploration directly within the target policy (e.g., ϵ\epsilon-greedy)Separates exploration (behavior policy) from exploitation/optimality (target policy)
Representative AlgorithmsGLIE Monte Carlo Control, SARSAQ-Learning, Deep Q-Networks (DQN)

General Policy Iteration​

  • Alternates between Policy Evaluation (V≈vπV \approx v_\pi or Q≈qπQ \approx q_\pi) and Policy Improvement (π←greedy\pi \leftarrow \text{greedy}).
  • This interplay drives the system asymptotically toward the optimal pair (v∗,π∗)(v_*, \pi_*) or (q∗,π∗)(q_*, \pi_*).

π′(s)=argmaxa∈A(R(s,a)+γ∑s′∈SP(s′∣s,a)V(s′))\pi'(s) = \text{argmax}_{a \in A} \big( \mathcal{R}(s, a) + \gamma \sum_{s' \in S} \mathcal{P}(s' | s, a) V(s') \big)

  • Why V(s)V(s) Fails in Model-Free Settings:
    • Finding the maximizing action over V(s)V(s) strictly requires the transition model P(s′∣s,a)P(s' \mid s, a) and reward function R(s,a)R(s, a).
    • In Model-Free RL, these dynamics are unavailable; hence, V(s)V(s) alone cannot guide policy updates without an explicit environment model.

GPI

π′(s)=argmaxa∈AQ(s,a)\pi'(s) = \text{argmax}_{a \in A}Q(s,a)

  • Model-Free Advantage:
    • By estimating Q(s,a)Q(s, a) directly through sample episodes, policy improvement requires no knowledge of PP or RR.
    • This fundamental shift makes Q(s,a)Q(s, a) estimation the standard paradigm for Model-Free Control (Monte Carlo Control, SARSA, Q-Learning).
V(s)V(s)Q(s,a)Q(s, a)
QuestionHow good is this state?How good is this action in this state?
Includes Action?NoYes
Policy EvaluationVery suitableSlightly more difficult
Policy ImprovementRequires a modelDirectly possible
Model-Free ControlInconvenientVery suitable

GPI with Q

  • This is why MC Control estimates qπ(s,a)q_\pi(s,a), not vπ(s)v_\pi(s).

Exploration Problem​

a=arg⁡max⁡aQ(s,a)a = \arg\max_a Q(s,a)
  • A greedy agent always chooses the action with the highest current estimated value.
  • But what if the current Q(s,a)Q(s,a) estimates are inaccurate?

Mystery Box Example​

Initially,

Q(red)=0,Q(blue)=0Q(\text{red}) = 0, \qquad Q(\text{blue}) = 0
  1. Open the red box:
    R=0→Q(red)=0R = 0 \rightarrow Q(\text{red}) = 0

  2. Open the blue box:
    R=+1→Q(blue)=1R = +1 \rightarrow Q(\text{blue}) = 1

  3. Keep opening the blue box:
    R=+1,+3,+2,…→Q(blue)≈2R = +1, +3, +2, \ldots \rightarrow Q(\text{blue}) \approx 2

  4. A purely greedy agent now keeps choosing the blue box because
    Q(blue)>Q(red)Q(\text{blue}) > Q(\text{red}).

  5. However, the red box may actually be better. For example,
    E[R∣red]=5\mathbb{E}[R \mid \text{red}] = 5.

    The agent does not know this because it sampled the red box only once.

Exploitation vs. Exploration​

  • Exploitation: Choose the action that currently has the highest estimated value.
  • Exploration: Try less-sampled or unfamiliar actions to discover whether they may actually be better.
  • In this example, the agent should occasionally explore the red box because it has not been sampled enough to confidently conclude that it is worse.

ϵ\epsilon-Greedy Exploration​

π(a∣s)={greedy action with high probabilityrandom action with probability ϵ\pi(a|s) = \begin{cases} \text{greedy action \quad with high probability} \\ \text{random action \quad with probability $\epsilon$} \\ \end{cases}
  • if ϵ=0.1\epsilon = 0.1, then the agent will choose the greedy action with probability 0.90.9 (Exploitation)
  • And the random action with probability 0.10.1 (Exploration).
  • Policy Improvement Theorem:
    • for any ϵ\epsilon-greedy policy π\pi
    • The ϵ\epsilon-greedy policy π′\pi' is as good or better than the original policy π\pi: vπ′(s)≥vπ(s)v_{\pi'}(s) \geq v_{\pi}(s)

Monte Carlo Control​

  • Traditional Policy Iteration:
    • Fix the policy π\pi.
    • Evaluate the current policy until QQ is sufficiently close to qπ(s,a)q_\pi(s,a).
    • Improve the policy using the estimated action values.
    • Repeat policy evaluation and policy improvement.
  • Monte Carlo Control:
    • Perform MC Policy Evaluation after every episode.
    • Improve the policy using ϵ\epsilon-greedy after every episode.
    • Q1→π1=ϵ-greedy(Q1)Q_1 \rightarrow \pi_1 = \epsilon\text{-greedy}(Q_1)
    • Q2→π2=ϵ-greedy(Q2)Q_2 \rightarrow \pi_2 = \epsilon\text{-greedy}(Q_2)
    • ⋯\cdots
    • Eventually approaches (q∗,π∗)(q_*, \pi_*) under appropriate convergence conditions.

MC Control

Evaluate a little→Improve→Evaluate a little→Improve→⋯\text{Evaluate a little} \rightarrow \text{Improve} \rightarrow \text{Evaluate a little} \rightarrow \text{Improve} \rightarrow \cdots

GLIE​

Greedy in the Limit with Infinite Exploration

  1. lim⁡k→∞Nk(s,a)=∞\lim_{k \to \infty} N_k(s,a) = \infty
  2. lim⁡k→∞πk(a∣s)=1(a=arg max⁡a′∈AQk(s,a′))\lim_{k \to \infty} \pi_k(a|s) = 1(a = \argmax_{a' \in A} Q_k(s,a'))
  • Explore enough early -> Explore less over time -> Eventually greedy.
    • Nk(s,a)N_k(s,a): How many times the state-action pair (s,a)(s,a) has been visited in the kk-th episode.
    • πk→greedy(Qk)\pi_k \rightarrow \text{greedy}(Q_k)
  • Infinite exploration first, greedy behavior in the limit.

GILE Monte Carlo Control​

  • Algorithm flow:
    • Run episode k={S0,A0,R1,…,ST}k = \{S_0, A_0, R_1, \dots, S_{T}\} with policy πk\pi_k.
    • For each state-action pair (s,a)(s,a) in the episode:
      • Nk(s,a)←Nk(s,a)+1N_k(s,a) \leftarrow N_k(s,a) + 1
      • Qk(s,a)←Qk(s,a)+1Nk(s,a)(Gk−Qk(s,a))Q_k(s,a) \leftarrow Q_k(s,a) + \frac{1}{N_k(s,a)} (G_k - Q_k(s,a))
    • Improve the policy based on the new QQ value.
      • ϵ←1k\epsilon \leftarrow \frac{1}{k}
      • π←ϵ-greedy(Q)\pi \leftarrow \epsilon\text{-greedy}(Q)
    • Repeat until convergence.
  • old estimate + step-size * (new sample - old estimate).
    • old estimate = Q(St,At)Q(S_t, A_t)
    • new sample = GtG_t
    • step-size = 1Nk(s,a)\frac{1}{N_k(s,a)}
  • Run Episode → Update Q → Reduce ϵ\epsilon → Improve Policy

DP vs MC​

  • Dynamic Programming:
    • Model-based
    • Bootstrapping: Updating a value estimate using another estimated value instead of waiting for the final outcome.
    • Lower variance
  • Monte Carlo:
    • Model-free
    • No bootstrapping: It uses rewards that actually occurred, not an estimated value of the next state.
    • Uses complete sampled returns
    • Requires episodic tasks
    • Higher variance

RL 005

· 약 7분

MDP​

(S,A,P,R,γ)(\mathcal{S}, \mathcal{A}, \mathcal{P}, \mathcal{R}, \gamma)

  • At each time step tt, the agent observes state St∈SS_t \in \mathcal{S} and chooses action At∈AA_t \in \mathcal{A}
  • Receives reward Rt+1∈RR_{t+1} \in \mathcal{R}
  • Transitions to a new state St+1S_{t+1}

Transition Dynamics​

Transition Probability

  • How the environment responds to an action, independent of the agent's policy
  • Policy: Whether to brake or accelerate when the traffic light is yellow.
  • Transition Dynamics: How much the car decelerates after braking, and what the resulting next state is.

P(s′∣s,a)=P(St+1=s′∣St=s,At=a)P(s'|s,a) = P(S_{t+1} = s'|S_t = s, A_t = a)

Policy​

  • A policy is the agent’s rule for choosing actions.
  • It tells the agent what action to take in a given state.
  • It defines agent's behavior.

Deterministic Policy:π(s)=a\text{Deterministic Policy}: \pi(s) = a

  • Direct mapping, and no randomness
  • All probability on one action

Stochastic Policy:π(a∣s)=P(At=a∣St=s)\text{Stochastic Policy}: \pi(a|s) = P(A_t = a | S_t = s)

  • A probability distribution over actions.
  • More general, all four Bellman Equations are stochastic, use π(a∣s)\pi(a|s) to represent the policy.
  • Policy is what the agent controls.

Value Functions​

vπ(s)=Eπ[Rt+1+γvπ(St+1)∣St=s]v_\pi(s) = \mathbb{E}_\pi[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t = s]

  • How good is this state?
  • Eπ[Gt∣St=s]\mathbb{E}_\pi[G_t | S_t = s]

qπ(s,a)=Eπ[Rt+1+γvπ(St+1)∣St=s,At=a]q_\pi(s,a) = \mathbb{E}_\pi[R_{t+1} + \gamma v_\pi(S_{t+1}) | S_t = s, A_t = a]

  • How good is this action in this state?
  • Eπ[Gt∣St=s,At=a]\mathbb{E}_\pi[G_t | S_t = s, A_t = a]

vπ(s)=∑a∈Aπ(a∣s)qπ(s,a)v_\pi(s) = \sum_{a \in \mathcal{A}} \pi(a|s) q_\pi(s,a)

  • The average value of the actions, weighted by the probability of choosing each action.
    • a1a_1 is brake
    • a2a_2 is accelerate
    • vπ(s)=0.8∗10+0.2∗20=10v_\pi(s) = 0.8 * 10 + 0.2 * 20 = 10
qπ(s,a)=R(s,a)+γ∑s′∈SP(s′∣s,a)vπ(s′)q_\pi(s,a) = \mathcal{R}(s,a) + \gamma \sum_{s' \in \mathcal{S}} P(s'|s,a) v_\pi(s')
  • The value of taking action aa in state ss: the immediate reward plus the discounted expected value of the possible next states.

Four Types of Bellman Equations​

vπ(s)=∑aπ(a∣s)qπ(s,a)qπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a)vπ(s′)vπ(s)=∑aπ(a∣s)[R(s,a)+γ∑s′P(s′∣s,a)vπ(s′)]qπ(s,a)=R(s,a)+γ∑s′P(s′∣s,a)∑a′π(a′∣s′)qπ(s′,a′)\begin{aligned} &v_\pi(s) = \sum_{a} \pi(a|s) q_\pi(s,a) \\ &q_\pi(s,a) = \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_\pi(s') \\ &v_\pi(s) = \sum_{a} \pi(a|s) \left[ \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_\pi(s') \right] \\ &q_\pi(s,a) = \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) \sum_{a'} \pi(a'|s') q_\pi(s',a') \end{aligned}
  • Evaluate a state: vπ(s)v_\pi(s)
  • Evaluate an action: qπ(s,a)q_\pi(s,a)
  • Calculate Bellman by only vv: Third equation
  • Calculate Bellman by only qq: Fourth equation

Dynamic Programming​

Optimization method for sequential problem

  • Dynamic: Sequential or Temporal component
  • Programming: Optimizing a program or policy
  • Sub Problem
  • Optimal Solution

Prediction and Control​

  • Prediction: Evaluate a given policy vπ(s)v_\pi(s)
  • Control: Find the optimal policy π∗\pi_*

Policy Improvement​

  • π→vπ→π′\pi \to v_\pi \to \pi'
  • π′=greedy(vπ)\pi' = \text{greedy}(v_\pi)
  • Evaluate current policy, Improve it greedily, then get a better policy

Policy Improvement

Modified Policy Iteration​

  • Policy iteration can be computationally expensive
  • MPI: cut off the policy evaluation after a few iterations kk then step to policy improvement.
    • k=1⇒Value iterationk = 1 \Rightarrow \text{Value iteration}
    • k=3,4⇒Modified Policy iterationk = 3,4 \Rightarrow \text{Modified Policy iteration}
    • kis large enough⇒Policy iterationk \quad \text{is large enough} \Rightarrow \text{Policy iteration}

Poisson Distribution Formulation​

P(X=n)=λne−λn!P(X = n) = \frac{\lambda^n e^{-\lambda}}{n!}

  • How many times an event occurs within a fixed interval of time (or space) when we only know the long-term average rate (λ\lambda).
  • nn: The actual number of requests or returns (n∈{0,1,2,…}n \in \{0, 1, 2, \ldots\})
  • λ\lambda: The expected/average number of requests or returns
  • ee: Euler's number (2.71828)
  • n!n!: Factorial of nn

Deterministic Value Iteration​

v∗(s)=max⁡a(R(s,a)+γ∑s′P(s′∣s,a)v∗(s′))v_*(s) = \max_{a} \left( \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_*(s') \right)

  • If solutions to sub-problems v∗(s′)v_*(s') are known, the optimal value v∗(s)v_*(s) for the current state can be computed directly.
  • Value signals propagate backwards across the state space from states with terminal rewards.

Value Iteration​

vk+1(s)=max⁡a(R(s,a)+γ∑s′P(s′∣s,a)vk(s′))v_{k+1}(s) = \max_{a} \left( \mathcal{R}(s,a) + \gamma \sum_{s'} P(s'|s,a) v_k(s') \right)

  • Infinite (∞\infty) iterations are required to converge exactly to v∗v_*.
  • In practical implementations, iteration terminates when the maximum value change between iterations is less than a small threshold θ\theta.

Dynamic Programming ALgorithms​

ProblemBellman EquationAlgorithm
PredictionBellman Expectation:
vk+1(s)=∑a∈Aπ(a∣s)(R(s,a)+γ∑s′∈SP(s′∣s,a)vk(s′))v_{k+1}(s) = \sum_{a \in A} \pi(a \mid s) \left( R(s, a) + \gamma \sum_{s' \in S} P(s' \mid s, a) v_k(s') \right)
Iterative Policy Evaluation
ControlBellman Expectation + Greedy Policy Improvement:
vk+1(s)=∑a∈Aπ(a∣s)(R(s,a)+γ∑s′∈SP(s′∣s,a)vk(s′))v_{k+1}(s) = \sum_{a \in A} \pi(a \mid s) \left( R(s, a) + \gamma \sum_{s' \in S} P(s' \mid s, a) v_k(s') \right)
π′=greedy(Vπ)\pi' = \text{greedy}(V_\pi)
Policy Iteration
ControlBellman Optimality:
vk+1(s)=max⁡a(R(s,a)+γ∑s′∈SP(s′∣s,a)vk(s′))v_{k+1}(s) = \max_a \left( R(s, a) + \gamma \sum_{s' \in S} P(s' \mid s, a) v_k(s') \right)
Value Iteration

Efficiency of DP​

  • Strengths:
    • A foundational and efficient framework widely used for solving MDPs.
    • Mathematically guaranteed to converge to an optimal policy in polynomial time in terms of the number of states and actions.
    • Exponentially faster than exhaustive direct search across the policy space (∣A∣∣S∣|A|^{|S|}).
  • Limitations:
    • Can become computationally impractical for extremely large or complex environments.
    • Curse of Dimensionality: As the number of state variables (dimensions) increases, the total state space size (∣S∣|S|) expands exponentially, leading to severe computational and memory bottlenecks.

Asynchronous Dynamic Programming​

  • Comparison with Synchronous Methods: Standard DP methods sweep through the entire state space systematically in every iteration. Asynchronous DP backs up individual states independently in arbitrary order.
  • In-place Value Updates: Directly overwrites values in a single memory array, allowing immediate propagation of newly updated state values to subsequent calculations.
  • Computational Gain & Convergence:
    • Significantly reduces computation by avoiding exhaustive full-state sweeps.
    • Guaranteed to converge to the optimal value function v∗v_*, provided that all states continue to be selected and updated indefinitely.

Real-Time Dynamic Programming (RTDP)​

  • Interaction-Driven Online Updates: Solves sub-problems on-the-fly by focusing updates specifically on states that are directly relevant to the agent's current trajectory.
  • Target Applications: Large-scale environments where full state-space iteration is intractable (e.g., robotics, autonomous control systems, game AI).
  • Core Characteristics:
    • Online Decision Making: Makes and refines decisions while operating directly in the environment.
    • Lazy Evaluation: Computes values only for visited or critical state subsets rather than unvisited distant states.
    • Adaptive Exploration: Guides search toward high-reward trajectories through active interaction.
    • Approximate MDP Solution: Yields near-optimal policies for relevant regions without solving the global MDP.

Approximate Dynamic Programming (ADP)​

  • Motivation: Addresses the curse of dimensionality where tabular representation of states and exact value computation become computationally infeasible.
  • Function Approximation Methods: Parameterizes and estimates the value function using scalable statistical and machine learning models:
    • Linear models, deep neural networks, decision trees, and general regression techniques.
  • Error Management Mechanisms:
    • Eligibility Traces: Accelerates credit assignment and temporal consistency across multi-step transitions.
    • Experience Replay: Stores transition tuples in a replay buffer and samples them randomly to break data correlation and stabilize value approximation.

IPPR 005

· 약 2분

Pattern recognition​

  • recognizing patterns of interest oin data
  • applications
    • image and video analysis
    • speech analysis
    • natural language processing
    • genomic research and bioinformatics
    • data mining and analytics for business, finance, marketing, trade
    • network traffic analysis
    • analysis of Web data
    • social media analysis

ML Problems​

  • Classification: predict a categorical value from an array of numerical/categorical features.
    • The input is assigned to the class with the highest score/probability.
  • Regression: predict a numerical value from an array of numerical/categorical features.
  • Clustering: group numerical data homogeneously into clusters.

Probabilistic Classifier​

  • The class scores are simply bounded between 0 and 1 and add up to 1 over all classes.
  • probability of class cc given input xx, or p(c∣x)p(c|x).
    • p(c=apple∣x)=0.7p(c = \text{apple}|x) = 0.7
    • p(c=banana∣x)=0.2p(c = \text{banana}|x) = 0.2
    • p(c=orange∣x)=0.1p(c = \text{orange}|x) = 0.1
  • All contemporary deep learning classifiers are probabilistic.
  • Training objective: assign the largest possible probability to the correct labels.

Hyperparameters​

  • Type of model: logistic regression, CNN, random forest, SVM etc.
  • Size of a mask (3x3, 5x5) or of feature vector (100, 200)
  • Number of clusters
  • All discrete choices and any coefficient within the loss function.

Datasets​

  • Training set: it is used with the loss function to automatically find the optimal parameters for various, arbitrarily chosen values of the hyperparameters
  • Validation set: it is used to find the best values for the hyperparameters (best performance evaluation metric)
  • Test set: it is used with the chosen parameters and hyperparameters to measure and report the final model’s accuracy/performance
  • K-means
  • K-medoids, or PAM (partitioning around medoids)
  • Other female-named clustering algorithms:
    • AGNES
    • DIANA
    • DAISY

Models​

  • U-Net: Classify individual pixels rather than entire images
  • SMILETrack: track objects in video having a certain shape

SMILETrack

  • OpenAI CLIP: Trained with pairs of images and captions, and at run time is able to classify images into any category of choice

CLIP

  • Stable Diffusion

RL 004

· 약 16분

Bellman Equation​

vπ(s)=Eπ[Rt+1⏟Immediate Reward+γvπ(St+1)⏟Discounted Future Value  |  St=s⏟Starting at state s]v_\pi(s) = \mathbb{E}_\pi \left[ \underbrace{R_{t+1}}_{\text{Immediate Reward}} + \gamma \underbrace{v_\pi(S_{t+1})}_{\text{Discounted Future Value}} \;\middle|\; \underbrace{S_t = s}_{\text{Starting at state s}} \right]

  • Fundamental concept in RL using a recursive equation to express a way to compute the value of a state based on the values of its successor states.
v(s)=E[Rt+1+γRt+2+γ2Rt+3+…  |  St=s]=E[Rt+1+γ(Rt+2+γRt+3+… )⏟Gt+1  |  St=s]=E[Rt+1+γGt+1  |  St=s]=E[Rt+1+γv(St+1)  |  St=s]=E[Rt+1∣St=s]⏟Immediate Reward R(s)+γ E[v(St+1)∣St=s]⏟Expected Next State Value(∵E[X+γY]=E[X]+γE[Y])=R(s)+γ∑s′P(s′∣s)v(s′)⏟Transition Dynamics(∵E[g(X)]=∑xP(x)g(x))\begin{aligned} v(s) &= \mathbb{E} \left[ R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \dots \;\middle|\; S_t = s \right] \\[8pt] &= \mathbb{E} \left[ R_{t+1} + \gamma \underbrace{\left( R_{t+2} + \gamma R_{t+3} + \dots \right)}_{G_{t+1}} \;\middle|\; S_t = s \right] \\[8pt] &= \mathbb{E} \left[ R_{t+1} + \gamma G_{t+1} \;\middle|\; S_t = s \right] \\[8pt] &= \mathbb{E} \left[ R_{t+1} + \gamma v(S_{t+1}) \;\middle|\; S_t = s \right] \\[8pt] &= \underbrace{\mathbb{E}[R_{t+1} \mid S_t = s]}_{\text{Immediate Reward } \mathcal{R}(s)} + \gamma \, \underbrace{\mathbb{E}[v(S_{t+1}) \mid S_t = s]}_{\text{Expected Next State Value}} && (\because \mathbb{E}[X + \gamma Y] = \mathbb{E}[X] + \gamma\mathbb{E}[Y]) \\[10pt] &= \mathcal{R}(s) + \gamma \underbrace{\sum_{s'} \mathcal{P}(s' \mid s) v(s')}_{\text{Transition Dynamics}} && \left(\because \mathbb{E}[g(X)] = \sum_x P(x)g(x)\right) \end{aligned}

Bellman Equation Example​

Bellman Example

v(sBL)=7+γ(0.1⋅v(sBL)+0.5⋅(sTL)+0.4⋅(sBR))v(s_{\text{BL}}) = 7 + \gamma(0.1 \cdot v(s_{\text{BL}}) + 0.5 \cdot(s_{TL}) + 0.4 \cdot(s_{BR}))

Bellman Equation in Matrix Form​

v=R+γPvv = \mathcal{R} + \gamma \mathcal{P} v

[v(s1)⋮v(sn)]⏟V of a particular state=[R(s1)⋮R(sn)]⏟Immediate Reward+γ[P11⋯P1n⋮⋱⋮Pn1⋯Pnn]⏟Transition Matrix[v(s1)⋮v(sn)]⏟V of future state\begin{aligned} \underbrace{ \begin{bmatrix} v(s_1) \\ \vdots \\ v(s_n) \end{bmatrix}}_{\text{V of a particular state}} = \underbrace{\begin{bmatrix} \mathcal{R}(s_1) \\ \vdots \\ \mathcal{R}(s_n) \end{bmatrix}}_{\text{Immediate Reward}} + \gamma \underbrace{\begin{bmatrix} \mathcal{P}_{11} & \cdots & \mathcal{P}_{1n} \\ \vdots & \ddots & \vdots \\ \mathcal{P}_{n1} & \cdots & \mathcal{P}_{nn} \end{bmatrix}}_{\text{Transition Matrix}} \underbrace{\begin{bmatrix} v(s_1) \\ \vdots \\ v(s_n) \end{bmatrix}}_{\text{V of future state}} \end{aligned}

Solving the Bellman Equation​

Linear System of Equations​

v=R+γPvv−γPv=R(I−γP)v=Rv=(I−γP)−1R\begin{aligned} \mathcal{v} &= \mathcal{R} + \gamma \mathcal{P}\mathcal{v} \\ \mathcal{v} - \gamma \mathcal{P}\mathcal{v} &= \mathcal{R} \\ (I - \gamma \mathcal{P})\mathcal{v} &= \mathcal{R} \\ \mathcal{v} &= (I - \gamma \mathcal{P})^{-1} \mathcal{R} \end{aligned}
  • Computational Complexity: O(n3)O(n^3)
  • For small MDPs: direct solution is possible (up to 100 states)
  • For large MDPs:
    • Iterative methods
    • Dynamic Programming
    • Monte Carlo Tree
    • TD learning

State-Value Function​

vπ(s)⏟Value of state s=Eπ⏟Follows policy π[Rt+1⏟Immediate Reward+γvπ(St+1)⏟Discounted Value of Next State  |  St=s⏟Starting at state s]\begin{aligned} \underbrace{v_\pi(s)}_{\text{Value of state } s} = \underbrace{\mathbb{E}_\pi}_{\text{Follows policy } \pi} \left[ \underbrace{R_{t+1}}_{\text{Immediate Reward}} + \gamma \underbrace{v_\pi(S_{t+1})}_{\text{Discounted Value of Next State}} \;\middle|\; \underbrace{S_t = s}_{\text{Starting at state } s} \right] \end{aligned}
  • Evaluates the expected return starting from state ss and following policy π\pi thereafter.
  • How good is it to be in state ss?
  • vπ(s)v_\pi(s): Expected cumulative return starting from state ss under policy π\pi.
  • Eπ\mathbb{E}_\pi: Expectation over action selections (At∼πA_t \sim \pi) and transition dynamics (St+1∼PS_{t+1} \sim \mathcal{P}).
  • Rt+1R_{t+1}: Immediate reward received upon transitioning out of state ss.
  • γvπ(St+1)\gamma v_\pi(S_{t+1}): Discounted expected value of the next successor state St+1S_{t+1}.
  • St=sS_t = s: Condition that the agent starts at state ss at time step tt.

vπ(s)=∑a∈Aπ(a∣s)qπ(s,a)v_{\pi}(s) = \sum_{a \in \mathcal{A}} \pi(a \mid s) q_{\pi}(s, a)

  • The value of state ss is the policy-weighted average of the values of all possible actions that can be taken from that state.
  • vπ(s)v_{\pi}(s): Expected cumulative return starting from state ss under policy π\pi.
  • π(a∣s)\pi(a \mid s): Probability of taking action aa in state ss under policy π\pi.
  • qπ(s,a)q_{\pi}(s, a): Value of taking action aa in state ss under policy π\pi.

Action-Value Function​

qπ(s,a)⏟Action-Value of (s,a)=Eπ⏟Follows policy π[Rt+1⏟Immediate Reward+γqπ(St+1,At+1)⏟Discounted Next Action-Value  |  St=s,At=a⏟Starting at s taking action a]\begin{aligned} \underbrace{q_\pi(s, a)}_{\text{Action-Value of } (s, a)} = \underbrace{\mathbb{E}_\pi}_{\text{Follows policy } \pi} \left[ \underbrace{R_{t+1}}_{\text{Immediate Reward}} + \gamma \underbrace{q_\pi(S_{t+1}, A_{t+1})}_{\text{Discounted Next Action-Value}} \;\middle|\; \underbrace{S_t = s, A_t = a}_{\text{Starting at } s \text{ taking action } a} \right] \end{aligned}
  • Evaluates the expected return of taking an arbitrary action aa in state ss, and subsequently following policy π\pi from step t+1t+1 onward.
  • How good is it to take action aa in state ss?
  • qπ(s,a)q_\pi(s, a): Value of taking action aa in state ss under policy π\pi (Q-value).
  • Eπ\mathbb{E}_\pi: Expectation over the next transition (St+1∼PS_{t+1} \sim \mathcal{P}) and the subsequent action (At+1∼πA_{t+1} \sim \pi).
  • Rt+1R_{t+1}: Immediate reward resulting from the state-action pair (s,a)(s, a).
  • γqπ(St+1,At+1)\gamma q_\pi(S_{t+1}, A_{t+1}): Discounted expected value of the successor state-action pair (St+1,At+1)(S_{t+1}, A_{t+1}).
  • St=s,At=aS_t = s, A_t = a: Condition that both the initial state and the initial action are fixed at time tt.
vπ(s)=∑a∈Aπ(a∣s)(Rsa+γ∑s′∈SPss′avπ(s′))\begin{aligned} v_\pi(s) = \sum_{a \in \mathcal{A}} \pi(a \mid s) \left( \mathcal{R}_s^a + \gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a v_\pi(s') \right) \end{aligned}
  • Evaluates state ss directly by averaging over all possible action branches (π\pi) and their subsequent environmental transitions (P\mathcal{P}).
  • Rsa\mathcal{R}_s^a: Immediate reward resulting from the state-action pair (s,a)(s, a).
  • γ∑s′∈SPss′avπ(s′)\gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a v_\pi(s'): Discounted expected value of the successor state s′s' resulting from the state-action pair (s,a)(s, a).
  • Pss′a\mathcal{P}_{ss'}^a: Probability of transitioning from state ss to state s′s' when action aa is taken.
  • S\mathcal{S}: Set of all possible states.
  • A\mathcal{A}: Set of all possible actions.
  • π(a∣s)\pi(a \mid s): Probability of taking action aa in state ss under policy π\pi.
  • vπ(s′)v_\pi(s'): Value of state s′s' under policy π\pi.

Bellman Expectation Equation​

qπ(s,a)=Rsa+γ∑s′∈SPss′a∑a′∈Aπ(a′∣s′)qπ(s′,a′)\begin{aligned} q_\pi(s, a) = \mathcal{R}_s^a + \gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a \sum_{a' \in \mathcal{A}} \pi(a' \mid s') q_\pi(s', a') \end{aligned}
  • Evaluates the state-action pair (s,a)(s, a) by summing immediate reward and the expected value of future action pairs (s′,a′)(s', a'), averaged across transition dynamics P\mathcal{P} and next-step policy choices π\pi.
  • Rsa\mathcal{R}_s^a: Immediate reward resulting from the state-action pair (s,a)(s, a).
  • γ∑s′∈SPss′a∑a′∈Aπ(a′∣s′)qπ(s′,a′)\gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a \sum_{a' \in \mathcal{A}} \pi(a' \mid s') q_\pi(s', a'): Discounted expected value of the successor state-action pair (s′,a′)(s', a') resulting from the state-action pair (s,a)(s, a).
  • Pss′a\mathcal{P}_{ss'}^a: Probability of transitioning from state ss to state s′s' when action aa is taken.
  • S\mathcal{S}: Set of all possible states.
  • A\mathcal{A}: Set of all possible actions.
  • π(a′∣s′)\pi(a' \mid s'): Probability of taking action a′a' in state s′s' under policy π\pi.
vπ(s)→Action Policy πqπ(s,a)↑↓Environment Transition Pvπ(s′)←Environment Transition Pqπ(s′,a′)\begin{matrix} v_\pi(s) & \xrightarrow{\text{Action Policy } \pi} & q_\pi(s, a) \\ \uparrow & & \downarrow \text{Environment Transition } \mathcal{P} \\ v_\pi(s') & \xleftarrow{\text{Environment Transition } \mathcal{P}} & q_\pi(s', a') \end{matrix}

Optimal Value Function​

V∗(s)=max⁡πvπ(s)V_*(s) = \max_\pi v_\pi(s)

  • The optimal State-Value Function V∗(s)V_*(s)
  • Maximum value function over all policies, or maximum possible reward that can be achieved from state ss.

q∗(s,a)=max⁡πqπ(s,a)q_*(s, a) = \max_\pi q_\pi(s, a)

  • The Optimal Action-Value Function q∗(s,a)q_*(s, a)
  • Maximum action-value function over all policies, or given state ss and action taken aa, what is the maximum reward that can be achieved from there onwards.

Optimal Policy​

π∗≥π  ⟺  vπ∗(s)≥vπ(s)∀s∈S\pi_* \geq \pi \iff v_{\pi_*(s)} \geq v_\pi(s) \quad \forall s \in \mathcal{S}

  • If certain policy is better than another policy, then the value of the better policy is greater than or equal to the value of others in all states.

Theorem fo any MDP​

  • Existence of an Optimal Policy: There always exists at least one optimal policy π∗\pi_* that is better than or equal to all other policies across all states (π∗≥π,  ∀π\pi_* \ge \pi, \; \forall \pi).
  • Uniqueness of the Optimal State-Value Function: Although multiple distinct optimal policies may exist (e.g., when two different paths yield the exact same maximum expected return), all optimal policies achieve the exact same unique optimal state-value function (vπ∗(s)=v∗(s)v_{\pi_*}(s) = v_*(s)).
  • Uniqueness of the Optimal Action-Value Function: Similarly, all optimal policies achieve the exact same unique optimal action-value function (qπ∗(s,a)=q∗(s,a)q_{\pi_*}(s, a) = q_*(s, a)).

Finding an Optimal Policy​

π∗(a∣s)={1if a=arg⁡max⁡a∈Aq∗(s,a)0otherwise\pi_*(a \mid s) = \begin{cases} 1 & \text{if } a = \arg\max_{a \in \mathcal{A}} q_*(s, a) \\ 0 & \text{otherwise} \end{cases}
  • If q∗(s,a)q_*(s, a) is known, optimal policy is achieved.
  • A deterministic optimal policy always exists for any MDP.

Bellman Optimality Equation​

Bellman Optimality Equation for v∗v_*​

v∗(s)⏟Optimal Value of State s=max⁡a∈Aq∗(s,a)⏟Optimal Value of Action a\begin{aligned} \underbrace{v_*(s)}_{\text{Optimal Value of State } s} = \max_{a \in \mathcal{A}} \underbrace{q_*(s, a)}_{\text{Optimal Value of Action } a} \end{aligned}
  • State-Value to Action-Value (s→as \rightarrow a)
  • The optimal state-value is achieved by greedily picking the single action that yields the maximum optimal action-value.
q∗(s,a)⏟Optimal Action-Value=Rsa⏟Immediate Reward+γ∑s′∈SPss′av∗(s′)⏟Expected Optimal Future Value\begin{aligned} \underbrace{q_*(s, a)}_{\text{Optimal Action-Value}} = \underbrace{\mathcal{R}_s^a}_{\text{Immediate Reward}} + \gamma \underbrace{\sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a v_*(s')}_{\text{Expected Optimal Future Value}} \end{aligned}
  • Action-Value to Next State-Value (a→s′a \rightarrow s')
  • Once the action aa is committed, the outcome is governed by the environment dynamics Pss′a\mathcal{P}_{ss'}^a, requiring an expectation (average) over possible successor states s′s'.
v∗(s)⏟Optimal Value of State s=max⁡a∈A(Rsa⏟Immediate Reward+γ∑s′∈SPss′av∗(s′)⏟Expected Optimal Future Value)\begin{aligned} \underbrace{v_*(s)}_{\text{Optimal Value of State } s} = \max_{a \in \mathcal{A}} \left( \underbrace{\mathcal{R}_s^a}_{\text{Immediate Reward}} + \gamma \underbrace{\sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a v_*(s')}_{\text{Expected Optimal Future Value}} \right) \end{aligned}
  • Bellman Optimality Equation for v∗v_* (s→a→s′s \rightarrow a \rightarrow s')
  • Combines the agent's deterministic maximization (max⁡a\max_a) with the environment's stochastic transition (∑s′Pss′a\sum_{s'} \mathcal{P}_{ss'}^a).
    • It means a structure where the best choice I can make (max⁡\max) embeds the probabilistic outcomes of the world (∑\sum) in its calculation.
  • Non-Linear System: Because of the max⁡\max operator, this system of equations cannot be solved directly via matrix inversion (I−γP)−1(I - \gamma\mathcal{P})^{-1}
    • it must be solved iteratively via Dynamic Programming (Value Iteration) or Reinforcement Learning.

Bellman Optimality Equation for q∗q_*​

q∗(s,a)⏟Optimal Action-Value=Rsa⏟Immediate Reward+γ∑s′∈SPss′a⏟Transition Dynamicsmax⁡a′∈Aq∗(s′,a′)⏟Optimal Successor Action\begin{aligned} \underbrace{q_*(s, a)}_{\text{Optimal Action-Value}} = \underbrace{\mathcal{R}_s^a}_{\text{Immediate Reward}} + \gamma \underbrace{\sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a}_{\text{Transition Dynamics}} \underbrace{\max_{a' \in \mathcal{A}} q_*(s', a')}_{\text{Optimal Successor Action}} \end{aligned}
  • Bellman Optimality Equation for q∗q_* ((s,a)→s′→a′(s, a) \to s' \to a')
  • Action Commitment: The initial state ss and action aa are fixed, receiving immediate reward Rsa\mathcal{R}_s^a.
  • Stochastic Transition: The agent transitions to successor state s′s' according to the environment's transition probability Pss′a\mathcal{P}_{ss'}^a.
  • Greedy Successor Action (max⁡a′\max_{a'}): Upon landing in state s′s', the agent greedily selects the action a′a' that yields the maximum possible optimal action-value q∗(s′,a′)q_*(s', a').
  • Core Foundation of Q-Learning: This equation directly forms the update target for off-policy algorithms like Q-Learning and DQN

Solving Bellman optimality equation​

  • Non-Linear equation: The optimality equations embed the non-linear max⁡\max operator, they cannot be linearized into standard matrix inversions.

Dynamic Programming Approaches​

πk+1(s)=arg⁡max⁡a∈A[Rsa+γ∑s′∈SPss′avπk(s′)]\begin{aligned} \pi_{k+1}(s) = \arg\max_{a \in \mathcal{A}} \left[ \mathcal{R}_s^a + \gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a v_{\pi_k}(s') \right] \end{aligned}
  • Policy Iteration: Alternates between full Policy Evaluation and Policy Improvement until the policy stabilizes (πk+1=πk\pi_{k+1} = \pi_k).
vk+1(s)←max⁡a∈A[Rsa+γ∑s′∈SPss′avk(s′)]\begin{aligned} v_{k+1}(s) \leftarrow \max_{a \in \mathcal{A}} \left[ \mathcal{R}_s^a + \gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a v_k(s') \right] \end{aligned}
  • Value Iteration: Turns the Bellman Optimality Equation directly into an iterative update rule, bypassing explicit policy evaluation steps.

Temporal-Difference Control Approaches​

Q(St,At)←Q(St,At)+α[Rt+1+γmax⁡aQ(St+1,a)⏟Off-policy Target from q∗−Q(St,At)]\begin{aligned} Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \left[ \underbrace{R_{t+1} + \gamma \max_{a} Q(S_{t+1}, a)}_{\text{Off-policy Target from } q_*} - Q(S_t, A_t) \right] \end{aligned}
  • Q-Learning (Off-Policy TD Control): Learns optimal action-values q∗q_* directly from experience tuples (St,At,Rt+1,St+1)(S_t, A_t, R_{t+1}, S_{t+1}) by approximating the Bellman Optimality Equation via bootstrapping.
Q(St,At)←Q(St,At)+α[Rt+1+γQ(St+1,At+1)⏟On-policy Target from qπ−Q(St,At)]\begin{aligned} Q(S_t, A_t) \leftarrow Q(S_t, A_t) + \alpha \left[ \underbrace{R_{t+1} + \gamma Q(S_{t+1}, A_{t+1})}_{\text{On-policy Target from } q_\pi} - Q(S_t, A_t) \right] \end{aligned}
  • SARSA (On-Policy TD Control): Learns action-values qπq_\pi for the current policy from experience transitions (St,At,Rt+1,St+1,At+1)(S_t, A_t, R_{t+1}, S_{t+1}, A_{t+1}), steadily improving the policy toward optimality.

Policy Evaluation​

  • Evaluate a given policy π\pi is a prediction problem.
  • Iterative application of Bellman Expectation backup.
Input:π:Policy to be evaluatedParameters:θ>0:Small threshold determining estimation accuracyγ∈[0,1]:Discount factorInitialize:V(s)∈R,∀s∈SV(terminal)=0Repeat:Δ←0For each s∈S:v←V(s)V(s)←∑a∈Aπ(a∣s)(Rsa+γ∑s′∈SPss′aV(s′))Δ←max⁡(Δ,  ∣v−V(s)∣)Until Δ<θOutput:V≈vπ\begin{aligned} &\textbf{Input:} \\ &\quad \pi : \text{Policy to be evaluated} \\[6pt] &\textbf{Parameters:} \\ &\quad \theta > 0 : \text{Small threshold determining estimation accuracy} \\ &\quad \gamma \in [0, 1] : \text{Discount factor} \\[6pt] &\textbf{Initialize:} \\ &\quad V(s) \in \mathbb{R}, \quad \forall s \in \mathcal{S} \\ &\quad V(\text{terminal}) = 0 \\[8pt] &\textbf{Repeat:} \\ &\quad \Delta \leftarrow 0 \\ &\quad \textbf{For each } s \in \mathcal{S}: \\ &\quad\quad v \leftarrow V(s) \\ &\quad\quad V(s) \leftarrow \sum_{a \in \mathcal{A}} \pi(a \mid s) \left( \mathcal{R}_s^a + \gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a V(s') \right) \\ &\quad\quad \Delta \leftarrow \max \left( \Delta, \; |v - V(s)| \right) \\ &\textbf{Until } \Delta < \theta \\[8pt] &\textbf{Output:} \\ &\quad V \approx v_\pi \end{aligned}
  • π\pi: Target policy being evaluated (π(a∣s)\pi(a \mid s) is the action selection probability).
  • θ\theta: Small threshold (θ>0\theta > 0) defining the stopping criterion for convergence.
  • γ\gamma: Discount factor (γ∈[0,1]\gamma \in [0, 1]) for future rewards.
  • V(s)V(s): Current estimated value of state ss (with V(terminal)=0V(\text{terminal}) = 0).
  • Δ\Delta: Maximum absolute value change across all states during the current sweep (max⁡∣v−V(s)∣\max |v - V(s)|).
  • Rsa\mathcal{R}_s^a: Expected immediate reward from taking action aa in state ss.
  • Pss′a\mathcal{P}_{ss'}^a: Transition probability to successor state s′s' from state ss via action aa.
  • vπv_\pi: True state-value function under policy π\pi that V(s)V(s) converges to.

Policy Improvement​

π′(s)=arg⁡max⁡a∈A[Rsa+γ∑s′∈SPss′aVπ(s′)]⏟qπ(s,a)\begin{aligned} \pi'(s) = \arg\max_{a \in \mathcal{A}} \underbrace{\left[ \mathcal{R}_s^a + \gamma \sum_{s' \in \mathcal{S}} \mathcal{P}_{ss'}^a V_\pi(s') \right]}_{q_\pi(s, a)} \end{aligned}
  • Computing Value-function for a policy helps to find better policies.
  • Evaluate the policy π\pi, find Vπ(s)V_\pi(s)
  • Improve the policy by greedy action: π′=greedy(Vπ)\pi' = \text{greedy}(V_\pi)
  • π\pi: Current baseline policy before improvement.
  • Vπ(s)V_\pi(s): True state-value function evaluated under policy π\pi.
  • π′\pi': New, improved policy updated via greedy action selection.
  • arg⁡max⁡a\arg\max_{a}: The operation of selecting the action aa that maximizes the subsequent expected return (qπ(s,a)q_\pi(s, a)).
  • Rsa\mathcal{R}_s^a: Immediate expected reward earned by taking action aa in state ss.
  • γ\gamma: Discount factor (γ∈[0,1]\gamma \in [0, 1]).
  • Pss′a\mathcal{P}_{ss'}^a: Transition probability to successor state s′s' from state ss via action aa.

Policy Iteration Algorithm​

Policy Iteration = Evaluate -> Improve -> Repeat

1. InitializationV(s)∈R and π(s)∈A(s) arbitrarily for all s∈S2. Policy EvaluationLoop:Δ←0Loop for each s∈S:v←V(s)V(s)←∑s′,rp(s′,r∣s,π(s))[r+γV(s′)]Δ←max⁡(Δ,  ∣v−V(s)∣)until Δ<θ(θ>0, small positive threshold)3. Policy Improvementpolicy-stable←trueFor each s∈S:old-action←π(s)π(s)←arg⁡max⁡a∈A(s)∑s′,rp(s′,r∣s,a)[r+γV(s′)]if old-action≠π(s) then policy-stable←falseif policy-stable then stop and return V≈v∗ and π≈π∗else go to 2\begin{aligned} &\textbf{1. Initialization} \\ &\quad V(s) \in \mathbb{R} \text{ and } \pi(s) \in \mathcal{A}(s) \text{ arbitrarily for all } s \in \mathcal{S} \\[6pt] &\textbf{2. Policy Evaluation} \\ &\quad \textbf{Loop:} \\ &\quad\quad \Delta \leftarrow 0 \\ &\quad\quad \textbf{Loop for each } s \in \mathcal{S}: \\ &\quad\quad\quad v \leftarrow V(s) \\ &\quad\quad\quad V(s) \leftarrow \sum_{s', r} p(s', r \mid s, \pi(s)) \left[ r + \gamma V(s') \right] \\ &\quad\quad\quad \Delta \leftarrow \max \left( \Delta, \; |v - V(s)| \right) \\ &\quad \textbf{until } \Delta < \theta \quad \text{($\theta > 0$, small positive threshold)} \\[6pt] &\textbf{3. Policy Improvement} \\ &\quad \textit{policy-stable} \leftarrow \text{true} \\ &\quad \textbf{For each } s \in \mathcal{S}: \\ &\quad\quad \textit{old-action} \leftarrow \pi(s) \\ &\quad\quad \pi(s) \leftarrow \arg\max_{a \in \mathcal{A}(s)} \sum_{s', r} p(s', r \mid s, a) \left[ r + \gamma V(s') \right] \\ &\quad\quad \textbf{if } \textit{old-action} \neq \pi(s) \textbf{ then } \textit{policy-stable} \leftarrow \text{false} \\[4pt] &\quad \textbf{if } \textit{policy-stable} \textbf{ then stop and return } V \approx v_* \text{ and } \pi \approx \pi_* \\ &\quad \textbf{else go to 2} \end{aligned}
  • Policy Evaluation (Prediction): What happens if I follow this policy?
  • Vπ(s)V_\pi(s): How good is each state?
  • Qπ(s,a)Q_\pi(s,a): What happens if I take an action aa?
  • Policy Improvement: Which action is better?
  • Optimal Policy: Repeat until no change

Value function diagram

  • R(s1)=0.5(+10)+0.1(+7)+0.1(+5)+0.3(0)=6.2\mathcal{R}(s_1) = 0.5(+10) + 0.1(+7) + 0.1(+5) + 0.3(0) = \mathbf{6.2}
  • R(s2)=0.5(0)+0.1(0)+0.4(−1)=−0.4\mathcal{R}(s_2) = 0.5(0) + 0.1(0) + 0.4(-1) = \mathbf{-0.4}
  • R(s3)=0.5(0)+0.5(0)=0\mathcal{R}(s_3) = 0.5(0) + 0.5(0) = \mathbf{0}
  • R(s4)=0.3(0)+0.2(0)+0.5(0)=0\mathcal{R}(s_4) = 0.3(0) + 0.2(0) + 0.5(0) = \mathbf{0}
  • R(s5)=0.3(0)+0.7(−2)=−1.4\mathcal{R}(s_5) = 0.3(0) + 0.7(-2) = \mathbf{-1.4}
v(s1)=6.2+γ[0.1v(s2)+0.5v(s3)+0.1v(s4)](∵v(s6)=0)v(s2)=−0.4+γ[0.4v(s1)+0.1v(s2)+0.5v(s3)]v(s3)=0+γ[0.5v(s2)+0.5v(s3)]v(s4)=0+γ[0.5v(s1)+0.2v(s4)+0.3v(s5)]v(s5)=−1.4+γ[0.7v(s1)+0.3v(s5)]\begin{aligned} v(s_1) &= 6.2 + \gamma \left[ 0.1 v(s_2) + 0.5 v(s_3) + 0.1 v(s_4) \right] \quad (\because v(s_6) = 0) \\ v(s_2) &= -0.4 + \gamma \left[ 0.4 v(s_1) + 0.1 v(s_2) + 0.5 v(s_3) \right] \\ v(s_3) &= 0 + \gamma \left[ 0.5 v(s_2) + 0.5 v(s_3) \right] \\ v(s_4) &= 0 + \gamma \left[ 0.5 v(s_1) + 0.2 v(s_4) + 0.3 v(s_5) \right] \\ v(s_5) &= -1.4 + \gamma \left[ 0.7 v(s_1) + 0.3 v(s_5) \right] \end{aligned} [v(s1)v(s2)v(s3)v(s4)v(s5)]=(I−γ[00.10.50.100.40.10.50000.50.5000.5000.20.30.70000.3])−1[6.2−0.400−1.4]\begin{bmatrix} v(s_1) \\ v(s_2) \\ v(s_3) \\ v(s_4) \\ v(s_5) \end{bmatrix} = \left( \mathbf{I} - \gamma \begin{bmatrix} 0 & 0.1 & 0.5 & 0.1 & 0 \\ 0.4 & 0.1 & 0.5 & 0 & 0 \\ 0 & 0.5 & 0.5 & 0 & 0 \\ 0.5 & 0 & 0 & 0.2 & 0.3 \\ 0.7 & 0 & 0 & 0 & 0.3 \end{bmatrix} \right)^{-1} \begin{bmatrix} 6.2 \\ -0.4 \\ 0 \\ 0 \\ -1.4 \end{bmatrix}

v(s2)[1−0.1γ−0.5γ22−γ]=−0.4+0.4γv(s1)v(s_2) \left[ 1 - 0.1\gamma - \frac{0.5\gamma^2}{2 - \gamma} \right] = -0.4 + 0.4\gamma v(s_1)

RL 003

· 약 10분

Markov Property​

  • The future is independent of the past given the present state.
  • The current state is sufficient to determine the future, without history.

Markov State​

P[St+1∣St]=P[St+1=s′∣St=s]P[S_{t+1} | S_t] = P[S_{t+1} = s' | S_t = s]

  • tt: Time step
  • St+1S_{t+1}: Next state
  • StS_t: Current state
  • S1,…,StS_1, \ldots, S_t: History (All previous states)

State Transition Probability​

Pss′=P[St+1=s′∣St=s]P_{ss'} = P[S_{t+1} = s' | S_t = s]

  • Likelihood or probability of moving from one state ss to another state s′s' in the next time step t+1t+1.
  • ss: Markov State
  • s′s': Successor State
  • tt: Time step
  • State transition matrix PP defines the transitions probabilities between all states ss to all successor states s′s'.

State Transition Matrix​

P=s1…sn←(to state)s1⋮sn[P11…P1n⋮⋱⋮Pn1…Pnn]↑(from state)\mathcal{P} = \begin{array}{rl} & \begin{matrix} \textcolor{red}{\boldsymbol{s_1}} & \textcolor{red}{\boldsymbol{\dots}} & \textcolor{red}{\boldsymbol{s_n}} \end{matrix} \quad \leftarrow \text{(to state)} \\ \begin{matrix} \textcolor{red}{\boldsymbol{s_1}} \\ \textcolor{red}{\boldsymbol{\vdots}} \\ \textcolor{red}{\boldsymbol{s_n}} \end{matrix} & \hspace{-10pt} \begin{bmatrix} \mathcal{P}_{11} & \dots & \mathcal{P}_{1n} \\ \vdots & \ddots & \vdots \\ \mathcal{P}_{n1} & \dots & \mathcal{P}_{nn} \end{bmatrix} \\ \begin{matrix} \uparrow \\[-2pt] \mathclap{\text{(from state)}} \end{matrix} & \end{array}
  • State transition matrix PP defines the transition probabilities between all states ss to all successor states s′s'.
  • Probability of moving from state sns_n to s1s_1 is Pn1\mathcal{P}_{n1}.

Math cal​

Reinforcement Learning and Math Major Symbols

  • P\mathcal{P}: Transition Probability Matrix
  • S\mathcal{S}: State Space
  • A\mathcal{A}: Action Space
  • R\mathcal{R}: Reward Function
  • L\mathcal{L}: Loss Function
  • N(μ,σ2)\mathcal{N}(\mu, \sigma^2): Normal Distribution
  • D\mathcal{D}: Dataset
  • H\mathcal{H}: Entropy / Hypothesis Space

Markov Process​

Markov Chain

  • What is going to be happened next?
  • it goes through a sequence of states overtime.
  • Stochastic Process: The next state St+1S_{t+1} is determined by the current state StS_t and the transition probability matrix PP that exhibits the Markov Property.
  • Current state is independent of the past states.
  • Memoryless: History of states leading up to the current state is not necessary to predict the next/future state.
  • MP: ⟨S,P⟩\langle\mathcal{S},\mathcal{P}\rangle, What states comes next?, Observer's Perspective.
  • MRP: ⟨S,P,R,γ⟩\langle\mathcal{S},\mathcal{P},\mathcal{R},\gamma\rangle, How good/How much reward is this state in the long run?, Evaluator's Perspective.
  • MDP: ⟨S,A,P,R,γ⟩\langle\mathcal{S},\mathcal{A},\mathcal{P},\mathcal{R},\gamma\rangle, What action should I take right now to maximize the long-term reward?, Decision Maker's Perspective.

Pss′=P[St+1=s′∣St=s]\mathcal{P}_{ss'} = P[S_{t+1} = s' | S_t = s]

  • SS: a finite set of states.
  • P\mathcal{P}: a state transition matrix, defines the transitions probabilities from all states ss to all successor states s′s'.
  • NO REWARD, NO ACTIONS.

Transition Diagram​

Moon Rover Transition Diagram

  • Box: where it ends
  • Arrow: transitions
  • Circle: states
  • Number: probability of transitioning to the state
P=[00.10.50.100.30.40.10.500000.50.50000.5000.20.300.70000.30000001]\mathcal{P} = \begin{bmatrix} 0 & 0.1 & 0.5 & 0.1 & 0 & 0.3 \\ 0.4 & 0.1 & 0.5 & 0 & 0 & 0 \\ 0 & 0.5 & 0.5 & 0 & 0 & 0 \\ 0.5 & 0 & 0 & 0.2 & 0.3 & 0 \\ 0.7 & 0 & 0 & 0 & 0.3 & 0 \\ 0 & 0 & 0 & 0 & 0 & 1 \end{bmatrix}
  • S1: Calibration Site
  • S2: Mineral Site
  • S3: Water Site
  • S4: Drill Site
  • S5: Alien Remain Site
  • S6: Lander Site

Markov Chain Episode​

  • A sequence of states from a starting state to a terminal state.
  • S1,S3,S2,S1,S6S_1, S_3, S_2, S_1, S_6
  • S1,S3,S3,S2,S1,S4,S4,S1,S6S_1, S_3, S_3, S_2, S_1, S_4, S_4, S_1, S_6

Episodic Task vs Continuous Task​

FeatureEpisodic TasksContinuing Tasks
TerminationHas a well-defined terminal state (TT)Runs indefinitely without termination (T=∞T = \infty)
Real-World Examples• Video games (e.g., Super Mario: level clear or death)
• Navigation (reaching destination)
• Board games (e.g., Chess: checkmate/draw)
• Smart thermostat (HVAC temperature control)
• 24/7 industrial robotic process control
• Automated trading & server load management
Execution FlowEnvironment resets to a start state once finishedOperates continuously without automatic resets
  • Episodic Tasks: Tasks with a defined end/terminal state.
  • Continuing Tasks: Tasks without a defined end/terminal state.
  • It may require different MDP formulation and solution methods for each type of task.

Markov Reward Process​

Markov Chain + Reward

⟨S,P,R,γ⟩\langle\mathcal{S},\mathcal{P},\mathcal{R},\gamma\rangle

  • SS: a finite set of states.
  • P\mathcal{P}: a state transition matrix (Transition Dynamics)
  • R\mathcal{R}: a reward function to compute expected reward from a state.
    • Rs=E[Rt+1∣St=s]\mathcal{R}_s = \mathbb{E}[R_{t+1} | S_t = s]
    • In the state ss, how much reward can you expect to get in the next time step?
  • γ\gamma: a discount factor, to balance the immediate and future rewards.
    • γ∈[0,1]\gamma \in [0, 1]

Reward diagram

Return​

Gt=Rt+1+Rt+2+⋯+RTG_t = R_{t+1} + R_{t+2} + \cdots + R_T

  • GtG_t: Goal Reward
    • The sum of the rewards received from time step tt.
  • Rt+1,Rt+2,…,RTR_{t+1}, R_{t+2}, \ldots, R_T: the sequence of rewards received after time step tt
  • TT: terminal state
  • tt: time step

Discount​

  • The present value of future rewards.
  • γ=0\gamma = 0: Myopic evaluation for maximizing immediate reward.
  • γ=1\gamma = 1: Far-sighted/Long-term evaluation for maximizing future reward.

Discounted Return​

Gt=Rt+1+γRt+2+γ2Rt+3+⋯+γT−t−1RT=∑k=0∞γkRt+k+1G_t = R_{t+1} + \gamma R_{t+2} + \gamma^2 R_{t+3} + \cdots + \gamma^{T-t-1} R_T = \sum_{k=0}^{\infty} \gamma^k R_{t+k+1}

  • GtG_t: Discounted Return
  • γ=1\gamma = 1: Undiscounted Markov Reward Process, if all sequences terminate (like games)

Value Function​

v(s)=E[Gt∣St=s]v(s) = \mathbb{E}[G_t | S_t = s]

  • The expected return from state ss.
  • How much total reward can you expect to get starting from this state?
  • A function returning the expected cumulative reward starting from state ss

Markov Decision Process​

Markov Reward Process + Actions(Decisions)

⟨S,A,P,R,γ⟩\langle\mathcal{S},\mathcal{A},\mathcal{P},\mathcal{R},\gamma\rangle

  • SS: a finite set of states.
  • A\mathcal{A}: a finite set of actions.
  • P\mathcal{P}: a state transition matrix
    • Pss′a=P[St+1=s′∣St=s,At=a]\mathcal{P}_{ss'}^a = P[S_{t+1} = s' | S_t = s, A_t = a]
  • R\mathcal{R}: a reward function
    • Rsa=E[Rt+1∣St=s,At=a]\mathcal{R}_s^a = \mathbb{E}[R_{t+1} | S_t = s, A_t = a]
  • γ\gamma: a discount factor

MDP

Policy​

π(a∣s)=P[At=a∣St=s]\pi(a | s) = P[A_t = a | S_t = s]

  • Policy specifies what actions to take in each state.
    • π(left∣wall)=0.8\pi(\text{left} | \text{wall}) = 0.8
    • π(right∣wall)=0.2\pi(\text{right} | \text{wall}) = 0.2
    • π(straight∣wall)=0.0\pi(\text{straight} | \text{wall}) = 0.0
    • The agent's playbook for any given state.
  • It fully defines the behavior of the agent.
  • MDP's policy does not depends on history, only on the current state.

Value Function of a Policy​

vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb{E}_{\pi}[G_t | S_t = s]

  • The state value function vπ(s)v_\pi(s) is the expected return starting from state ss and following policy π\pi.
  • How good it is to be in state ss (under policy π\pi)?

qπ(s,a)=Eπ[Gt∣St=s,At=a]q_\pi(s, a) = \mathbb{E}_{\pi}[G_t | S_t = s, A_t = a]

  • The expected return of taking action aa in state ss, taking action aa and then following policy π\pi.
  • qq: a quality of action aa in state ss (under policy π\pi).
FeatureState-Value Function (vπ(s)v_\pi(s))Action-Value Function (qπ(s,a)q_\pi(s, a))
Decision FlowFollows policy π\pi right from state ssCommits to action aa first, then follows policy π\pi
Intuitive Question"How good is it to be in this state?""How good is it to take this specific action in this state?"

Solving MDPs​

Goal: Find optimal policy π∗\pi_* that maximizes the expected return.

  • Using Value Iteration or Policy Iteration.
  • Updating value functions and policies iteratively until convergence.
  • Evaluation: Compute the value function vπ(s)v_\pi(s) for a given policy π\pi.
  • Improvement: Update the policy π\pi to choose better actions based on the updated value function.
    • To converge to the optimal value function and policy v∗,π∗v^*, \pi^*

POMDPs​

MDPs with hidden states.

⟨S,A,O⏟공간 (Spaces),P,R,Z⏟함수 / 규칙 (Functions),γ⏟상수 (Discount Factor)⟩\langle \underbrace{\mathcal{S}, \mathcal{A}, \mathcal{O}}_{\text{공간 (Spaces)}}, \underbrace{\mathcal{P}, \mathcal{R}, \mathcal{Z}}_{\text{함수 / 규칙 (Functions)}}, \underbrace{\gamma}_{\text{상수 (Discount Factor)}} \rangle

  • SS: a finite set of states
  • A\mathcal{A}: a finite set of actions
  • O\mathcal{O}: a finite set of observations
    • e.g. driving in foggy weather.
  • P\mathcal{P}: a state transition matrix
  • R\mathcal{R}: a reward function
  • Z\mathcal{Z}: an observation function
    • Zs′,oa=P[Ot+1=o∣St+1=s′,At=a]\mathcal{Z}_{s', o}^a = P[O_{t+1} = o | S_{t+1} = s', A_t = a]
    • an observation function specifying the probability of receiving observation oo given state s′s' and action aa
    • After taking action aa and landing in state s′s', how likely is the agent to observe oo?
  • γ\gamma: a discount factor
  • e.g.
    • Robot navigation with noisy/uncalibrated sensors.
    • Autonomous Driving with Sensor uncertainty due to bad weather conditions and unexpected events.

Finite Horizon MDPs​

  • Finite Time Steps (TT): A sequential decision-making process restricted to a fixed, finite number of steps (TT) to maximize cumulative rewards.
  • Target Applications: Well-suited for problems with explicit deadlines or time-varying environment dynamics.
  • Decision Basis: Optimal decisions are made using current state (StS_t), available actions (AtA_t), transition probabilities (P\mathcal{P}), and immediate rewards (R\mathcal{R}).
  • Representative Example: A robot navigating a grid world with a limited step count or battery budget to reach a goal while avoiding obstacles.
  • Discount Factor (γ\gamma): Because the horizon TT is finite, the cumulative return cannot diverge to infinity, allowing the use of undiscounted formulations (γ=1\gamma = 1).
  • Time-Dependent (Non-Stationary) Policy:
    • Unlike infinite-horizon MDPs, the optimal action depends explicitly on the remaining time steps (T−tT - t).
    • Policy Notation: πt(s)\pi_t(s) (indexed by time step tt).
    • Intuition: An agent may play conservatively early on, but take high-risk, high-reward actions right before the deadline.
DimensionFinite-Horizon MDPInfinite-Horizon MDP
Time Horizon (TT)T<∞T < \infty (Explicit terminal step)T→∞T \to \infty (Perpetual / ongoing)
Policy NatureNon-Stationary (πt(s)\pi_t(s), changes over time)Stationary (π(s)\pi(s), time-invariant)
Discount Factor (γ\gamma)γ≤1\gamma \le 1 (γ=1\gamma = 1 is valid)Typically γ<1\gamma < 1 required for convergence
Objective Functionmax⁡E[∑t=0TγtRt+1]\max \mathbb{E} \left[ \sum_{t=0}^{T} \gamma^t R_{t+1} \right]max⁡E[∑t=0∞γtRt+1]\max \mathbb{E} \left[ \sum_{t=0}^{\infty} \gamma^t R_{t+1} \right]

Limitations of MDPs​

  • Markovian Assumption: Assumes future transitions depend solely on the current state StS_t, ignoring past historical trajectories and temporal dependencies that matter in real-world dynamics (e.g., momentum, acceleration).
    • State augmentation, frame stacking, RNN/Transformer, POMDP
  • Complete Knowledge Requirement: Assumes exact a priori knowledge of transition probabilities P\mathcal{P} and reward functions R\mathcal{R}, which are rarely accessible without sample-based learning in complex environments.
    • Model-free RL: Q-learning, SARSA, Policy Gradient
  • Finite State and Action Spaces: Restricted to discrete and countable sets, whereas real-world robotics and physical control tasks typically involve continuous states and actions.
    • Function approximation, Actor-Critic: DDPG, TD3, SAC, PPO
  • Curse of Dimensionality: Tabular value and policy storage scale exponentially as state dimensions grow (∣S∣×∣A∣|\mathcal{S}| \times |\mathcal{A}|), making high-dimensional environments (e.g., raw pixel inputs) computationally intractable.
    • Deep RL: neural approximation of VV, QQ, or π\pi
  • Partial Observability: Assumes full access to the true ground-truth state (Ot=StO_t = S_t), failing to account for real-world sensor noise, occlusions, and incomplete observations.
    • POMDP, belief-state estimation, recurrent policies