Certainly! Here's the translation of the provided MATLAB code into Python, including the necessary functions and detailed explanations.
import numpy as np
from scipy.optimize import minimize
def maxent_default_params(algorithm_params):
"""
Fill in default parameters for the MaxEnt algorithm.
"""
# Create default parameters.
default_params = {
'seed': 0,
'laplace_prior': 0,
'all_features': 1,
'true_features': 0
}
# Fill in any missing parameters with defaults.
algorithm_params = fill_default_params(algorithm_params, default_params)
return algorithm_params
def fill_default_params(algorithm_params, default_params):
"""
Helper function to fill in default parameters.
"""
for key, value in default_params.items():
algorithm_params.setdefault(key, value)
return algorithm_params
def maxent_discounted(r, F, muE, mu_sa, mdp_data, initD, laplace_prior=0):
"""
Compute MaxEnt objective and gradient for the discounted infinite-horizon case.
"""
# Extract actions count from MDP data.
actions = mdp_data['actions']
# Convert to full reward vector.
wts = r.copy()
r_full = np.dot(F, r)
# Create the per-state-action reward matrix.
r_sa = np.tile(r_full[:, np.newaxis], (1, actions))
# Perform value iteration to get policy and log-policy.
V, Q, policy, log_policy = linear_value_iteration(mdp_data, r_sa)
# Compute the objective value by summing over log probabilities of the examples.
val = np.sum(log_policy * mu_sa)
# Add Laplace prior for regularization (L1 penalty).
if laplace_prior:
val -= laplace_prior * np.sum(np.abs(wts))
# Invert the value for minimization routines (since we are maximizing the objective).
val = -val
# Compute the gradient if needed.
# Compute state visitation frequencies D under the policy.
D = linear_mdp_frequency(mdp_data, {'p': policy}, initD)
# Compute the gradient.
dr = muE - np.dot(F.T, D)
# Add gradient of Laplace prior.
if laplace_prior:
dr -= laplace_prior * np.sign(wts)
# Invert the gradient for minimization routines.
dr = -dr
return val, dr
def maxent_run(algorithm_params, mdp_data, mdp_model,
feature_data, example_samples, true_features, verbosity):
"""
Ziebart's Maximum Entropy IRL algorithm with optional prior on reward values.
"""
# Fill in default parameters.
algorithm_params = maxent_default_params(algorithm_params)
# Set random seed.
np.random.seed(algorithm_params['seed'])
# Initialize variables.
sa_p = mdp_data['sa_p'] # Transition probabilities.
states, actions, _ = sa_p.shape
N = len(example_samples) # Number of example trajectories.
# Build feature membership matrix.
if algorithm_params['all_features']:
F = feature_data['splittable']
# Add a dummy feature (bias term).
F = np.hstack([F, np.ones((states, 1))])
elif algorithm_params['true_features']:
F = true_features
else:
F = np.eye(states) # Identity matrix if no features provided.
# Count the number of features.
features = F.shape[1]
# Initialize feature expectations.
muE = np.zeros(features)
mu_sa = np.zeros((states, actions))
# Collect examples state-action counts and feature expectations.
for trajectory in example_samples:
for (s, a) in trajectory:
mu_sa[s, a] += 1
muE += F[s, :]
# Generate initial state distribution for infinite horizon.
# Compute the initial state distribution from the first states in the examples.
initD = np.zeros(states)
for trajectory in example_samples:
s, _ = trajectory[0]
initD[s] += 1
# Normalize the initial distribution.
initD /= initD.sum()
# Define the objective function and gradient for optimization.
def objective_function(r):
val, dr = maxent_discounted(r, F, muE, mu_sa, mdp_data, initD, algorithm_params['laplace_prior'])
return val, dr
# Set up optimization options.
options = {'disp': verbosity != 0}
# Initialize reward weights randomly.
r_init = np.random.rand(features)
# Run the optimization using L-BFGS-B algorithm.
res = minimize(fun=lambda r: objective_function(r)[0],
x0=r_init,
method='L-BFGS-B',
jac=lambda r: objective_function(r)[1],
options=options)
# Retrieve the optimized weights.
wts = res.x
# Compute the full reward function.
r = np.dot(F, wts)
# Replicate rewards for all actions.
r_sa = np.tile(r[:, np.newaxis], (1, actions))
# Solve the MDP with the computed reward function.
soln = mdp_solve(mdp_data, r_sa)
v = soln['v']
q = soln['q']
p = soln['p']
# Construct the result.
irl_result = {
'r': r_sa,
'v': v,
'p': p,
'q': q,
'r_itr': [r_sa],
'model_itr': [wts],
'model_r_itr': [r_sa],
'p_itr': [p],
'model_p_itr': [p],
'time': res.nit, # Number of iterations taken by optimizer.
}
return irl_result
def maxent_softmax(q_sa):
"""
Compute the column-wise softmax of a matrix q_sa.
"""
# Subtract the maximum value to prevent numerical overflow.
max_q = np.max(q_sa, axis=1, keepdims=True)
exp_q = np.exp(q_sa - max_q)
sum_exp_q = np.sum(exp_q, axis=1, keepdims=True)
v = max_q + np.log(sum_exp_q)
return v.squeeze()
def linear_value_iteration(mdp_data, r_sa):
"""
Perform value iteration for MaxEnt IRL.
"""
sa_p = mdp_data['sa_p'] # Transition probabilities (S x A x S).
discount = mdp_data['discount']
states, actions, _ = sa_p.shape
# Initialize the value function.
V = np.zeros(states)
max_iter = 1000
eps = 1e-5
for _ in range(max_iter):
V_prev = V.copy()
# Compute Q-values.
Q = r_sa + discount * np.einsum('saS,S->sa', sa_p, V)
# Update the value function using the softmax operator.
V = maxent_softmax(Q)
# Check for convergence.
if np.max(np.abs(V - V_prev)) < eps:
break
# Compute the final Q-values.
Q = r_sa + discount * np.einsum('saS,S->sa', sa_p, V)
# Compute log-policy.
log_policy = Q - V[:, np.newaxis]
# Compute the policy probabilities.
policy = np.exp(log_policy)
policy /= policy.sum(axis=1, keepdims=True)
return V, Q, policy, log_policy
def linear_mdp_frequency(mdp_data, policy, initD):
"""
Compute the expected discounted visitation frequencies D under the policy.
"""
sa_p = mdp_data['sa_p'] # Transition probabilities (S x A x S).
discount = mdp_data['discount']
states, _, _ = sa_p.shape
# Construct the state-to-state transition matrix under the policy.
P_pi = np.zeros((states, states))
for s in range(states):
for a in range(mdp_data['actions']):
P_sa = sa_p[s, a, :] # Transition probabilities from state s using action a.
P_pi[s, :] += policy['p'][s, a] * P_sa
# Solve D = (I - gamma * P_pi)^(-1) * initD
I = np.eye(states)
try:
inv_matrix = np.linalg.inv(I - discount * P_pi)
except np.linalg.LinAlgError:
# Use pseudo-inverse if the matrix is singular.
inv_matrix = np.linalg.pinv(I - discount * P_pi)
D = np.dot(inv_matrix, initD)
return D
def mdp_solve(mdp_data, r_sa):
"""
Solve the MDP given the rewards.
"""
# Here we can reuse linear_value_iteration to get the value function and policy.
V, Q, p, _ = linear_value_iteration(mdp_data, r_sa)
# Return the solution as a dictionary.
return {'v': V, 'q': Q, 'p': p}
def maxent_transfer(prev_result, mdp_data, mdp_model, feature_data, true_feature_map, verbosity):
"""
Transfer learned reward function to a new state space.
"""
# Get the learned weights.
wts = prev_result['model_itr'][-1]
# Decide which features to use.
if len(wts) == true_feature_map.shape[1]:
F = true_feature_map
elif len(wts) == feature_data['splittable'].shape[1] + 1:
F = feature_data['splittable']
F = np.hstack([F, np.ones((mdp_data['states'], 1))])
else:
F = np.eye(mdp_data['states'])
# Compute the reward function for the new MDP.
r = np.dot(F, wts)
r_sa = np.tile(r[:, np.newaxis], (1, mdp_data['actions']))
# Solve the MDP with the new reward function.
soln = mdp_solve(mdp_data, r_sa)
v = soln['v']
q = soln['q']
p = soln['p']
# Build the IRL result.
irl_result = {
'r': r_sa,
'v': v,
'p': p,
'q': q,
'model_itr': [wts],
'r_itr': [r_sa],
'model_r_itr': [r_sa],
'p_itr': [p],
'model_p_itr': [p],
'time': 0,
'score': 0
}
return irl_result
Explanation of the code and functions:
-
maxent_default_params: This function sets default values for any missing parameters in algorithm_params.
-
fill_default_params: A helper function that fills in default parameter values in a dictionary.
-
maxent_discounted: Computes the MaxEnt objective value and gradient for the infinite horizon discounted case. It includes the Laplace prior for regularization if needed.
-
maxent_run: The main function that runs the MaxEnt IRL algorithm. It initializes parameters, processes the examples to compute feature expectations, defines the optimization objective, and uses L-BFGS-B optimization to find the optimal reward weights.
-
maxent_softmax: Computes the softmax (log-sum-exp) of a matrix in a numerically stable way, which is essential for the MaxEnt value iteration.
-
linear_value_iteration: Performs the value iteration algorithm specific to MaxEnt IRL by incorporating the softmax in the Bellman backup.
-
linear_mdp_frequency: Computes the expected discounted state visitation frequencies under a given policy by solving a linear system.
-
mdp_solve: Solves the MDP given the rewards. It uses the value iteration method from MaxEnt to compute the policy and value functions.
-
maxent_transfer: Transfers the learned reward weights to a new state space using provided features and solves the new MDP.
Note on data structures and usage:
-
mdp_data: This is expected to be a dictionary containing MDP information, such as 'sa_p' for state-action transition probabilities, 'discount' factor, 'actions' count, and possibly other MDP-specific data.
-
feature_data: Should be a dictionary containing feature representations, particularly 'splittable' features.
-
example_samples: A list of example trajectories. Each trajectory is a list of (state, action) tuples.
-
true_features: The true feature representation of the states if available.
-
prev_result: The result from a previous run of the IRL algorithm, used in the transfer function.
Example usage:
Assuming you have your MDP data, feature data, and example trajectories set up, you can run the MaxEnt IRL algorithm as follows:
# Define your algorithm parameters.
algorithm_params = {
'seed': 42,
'laplace_prior': 0.1,
'all_features': True,
'true_features': False
}
# Run the MaxEnt IRL algorithm.
irl_result = maxent_run(algorithm_params, mdp_data, 'mdp_model_name',
feature_data, example_samples, true_features, verbosity=1)
Important considerations:
-
The code assumes that all the necessary MDP data and feature representations are properly defined and passed to the functions.
-
The MDP solving function mdp_solve and the MDP model used in maxent_run need to be consistent with your environment.
-
The code uses numpy for numerical computations and scipy's optimizer for the optimization step.
-
The transition probabilities sa_p in mdp_data should be a numpy array of shape (S, A, S), where S is the number of states and A is the number of actions.
Additional dependencies:
To ensure the code runs correctly, make sure to have the following imports at the top of your script:
import numpy as np
from scipy.optimize import minimize
Final remarks:
This code provides a complete translation of the MATLAB MaxEnt IRL implementation into Python. It includes necessary functions and handles the computation of the objective function, gradient, state visitation frequencies, policy computation, and value iteration specific to MaxEnt IRL. Adjustments may be needed depending on the specifics of the MDP and data structures used in your implementation.