Certainly! Below is the Python translation of the MATLAB MaxEnt IRL code you provided. This includes necessary functions and adjustments for Python, as well as guidance on how to load your CSV data and process it into trajectories of 20 days.
Please ensure you have the necessary dependencies installed:
pip install numpy scipy pandas
import numpy as np
from scipy.optimize import minimize
import pandas as pd
import time
def maxentdefaultparams(algorithm_params):
# Create default parameters
default_params = {
'seed': 0,
'laplace_prior': 0,
'all_features': 1,
'true_features': 0
}
# Set parameters
algorithm_params = filldefaultparams(algorithm_params, default_params)
return algorithm_params
def filldefaultparams(params, default_params):
for key in default_params:
if key not in params:
params[key] = default_params[key]
return params
def linearvalueiteration(mdp_data, r, vinit=None):
states = mdp_data['states']
actions = mdp_data['actions']
VITR_THRESH = 1e-4
# Initialize value function
if vinit is not None:
v = vinit
else:
v = np.zeros(states)
diff = 1.0
while diff >= VITR_THRESH:
# Copy previous value function
vp = v.copy()
# Compute Q-function
q = r + mdp_data['discount'] * np.sum(
mdp_data['sa_p'] * vp[mdp_data['sa_s'].astype(int)], axis=2)
# Compute softmax
v = maxentsoftmax(q)
diff = np.max(np.abs(v - vp))
# Compute policy
logp = q - v[:, np.newaxis]
p = np.exp(logp)
return v, q, p, logp
def maxentsoftmax(q):
# Calculate max for stability
maxx = np.max(q, axis=1, keepdims=True)
# Compute softmax values
v = maxx + np.log(np.sum(np.exp(q - maxx), axis=1, keepdims=True))
return v.squeeze()
def maxentdiscounted(r, F, muE, mu_sa, mdp_data, initD, laplace_prior=0):
# Compute constants
actions = mdp_data['actions']
# Convert to full reward
wts = r.copy()
r_full = F @ r
# Solve for policy
_, _, policy, logpolicy = linearvalueiteration(
mdp_data, np.tile(r_full[:, np.newaxis], (1, actions)))
# Compute value by summing log probabilities
val = np.sum(logpolicy * mu_sa)
# Add Laplace prior
if laplace_prior:
val -= laplace_prior * np.sum(np.abs(wts))
# Invert for descent
val = -val
# Compute gradient
D = linearmdpfrequency(mdp_data, {'p': policy}, initD)
dr = muE - F.T @ D
if laplace_prior:
dr -= laplace_prior * np.sign(wts)
# Invert for descent
dr = -dr
return val, dr
def linearmdpfrequency(mdp_data, mdp_solution, initD, prevD=None):
states = mdp_data['states']
actions = mdp_data['actions']
transitions = mdp_data['sa_p'].shape[2]
VITR_THRESH = 1e-4
if prevD is not None:
D = prevD.copy()
else:
D = np.zeros(states)
if initD is None or len(initD) == 0:
# Initialize uniform initial state distribution
initD = np.ones(states) / states
diff = 1.0
while diff >= VITR_THRESH:
Dp = D.copy()
Dp_expanded = Dp[:, np.newaxis, np.newaxis]
Dpi = mdp_solution['p'][:, :, np.newaxis] * mdp_data['sa_p'] * Dp_expanded * mdp_data['discount']
# Flatten arrays for accumulation
Dpi_flat = Dpi.flatten()
sa_s_flat = mdp_data['sa_s'].flatten().astype(int)
# Accumulate next state frequencies
D_next = np.zeros(states)
np.add.at(D_next, sa_s_flat, Dpi_flat)
D = initD + D_next
diff = np.max(np.abs(D - Dp))
return D
def linearmdpsolve(mdp_data, r):
# Run value iteration to compute value function and policy
v, q, p, _ = linearvalueiteration(mdp_data, r)
# Return solution
mdp_solution = {'v': v, 'q': q, 'p': p}
return mdp_solution
def maxentrun(algorithm_params, mdp_data, mdp_model, feature_data,
example_samples, true_features, verbosity):
# Fill in default parameters
algorithm_params = maxentdefaultparams(algorithm_params)
# Set random seed
np.random.seed(algorithm_params['seed'])
# Initialize variables
states = mdp_data['states']
actions = mdp_data['actions']
transitions = mdp_data['sa_p'].shape[2]
N = len(example_samples)
T = len(example_samples[0])
# Choose mdp_solve function based on mdp_model
mdp_solve = linearmdpsolve
# Build feature membership matrix
if algorithm_params['all_features']:
F = feature_data['splittable']
# Add dummy feature
F = np.hstack([F, np.ones((states, 1))])
elif algorithm_params['true_features']:
F = true_features
else:
F = np.eye(states)
# Count features
features = F.shape[1]
# Compute feature expectations
muE = np.zeros(features)
ex_s = np.zeros((N, T), dtype=int)
ex_a = np.zeros((N, T), dtype=int)
mu_sa = np.zeros((states, actions))
for i in range(N):
for t in range(T):
ex_s[i, t] = example_samples[i][t][0]
ex_a[i, t] = example_samples[i][t][1]
mu_sa[ex_s[i, t], ex_a[i, t]] += 1
state_vec = np.zeros(states)
state_vec[ex_s[i, t]] = 1
muE += F.T @ state_vec
# Generate initial state distribution for infinite horizon
initD = np.zeros(states)
for i in range(N):
for t in range(T):
s = ex_s[i, t]
a = ex_a[i, t]
initD[s] += 1
for k in range(transitions):
sp = mdp_data['sa_s'][s, a, k]
initD[sp] -= mdp_data['discount'] * mdp_data['sa_p'][s, a, k]
# Objective function for optimization
def fun(r):
return maxentdiscounted(r, F, muE, mu_sa, mdp_data, initD,
algorithm_params['laplace_prior'])
# Set up optimization options
options = {'disp': verbosity != 0}
# Initialize reward
r0 = np.random.rand(features)
# Run optimization
start_time = time.time()
res = minimize(fun, r0, method='L-BFGS-B', jac=True, options=options)
r = res.x
time_elapsed = time.time() - start_time
if verbosity != 0:
print(f'Optimization completed in {time_elapsed} seconds.')
# Convert to full reward
wts = r
r_full = F @ r
# Solve MDP with learned reward
r_mat = np.tile(r_full[:, np.newaxis], (1, actions))
soln = mdp_solve(mdp_data, r_mat)
v = soln['v']
q = soln['q']
p = soln['p']
# Construct return structure
irl_result = {
'r': r_mat,
'v': v,
'p': p,
'q': q,
'r_itr': [r_mat],
'model_itr': [wts],
'model_r_itr': [r_mat],
'p_itr': [p],
'model_p_itr': [p],
'time': time_elapsed
}
return irl_result
Loading Your CSV Data and Preparing Trajectories
Assuming your CSV file has columns named state, action, and next_state, we can load the data using pandas and prepare the trajectories as follows:
# Load CSV data
data = pd.read_csv('your_data.csv')
# Adjust indices for zero-based indexing if necessary
data['state'] -= 1
data['action'] -= 1
data['next_state'] -= 1
# Determine the number of trajectories
trajectory_length = 20
num_samples = len(data) // trajectory_length
# Create example samples
example_samples = []
for i in range(num_samples):
trajectory = []
for j in range(trajectory_length):
idx = i * trajectory_length + j
state = data.loc[idx, 'state']
action = data.loc[idx, 'action']
trajectory.append((int(state), int(action)))
example_samples.append(trajectory)
# Handle any remaining data
remaining = len(data) % trajectory_length
if remaining > 0:
trajectory = []
for idx in range(num_samples * trajectory_length, len(data)):
state = data.loc[idx, 'state']
action = data.loc[idx, 'action']
trajectory.append((int(state), int(action)))
if len(trajectory) == trajectory_length:
example_samples.append(trajectory)
Preparing mdp_data, feature_data, and Other Inputs
You need to define mdp_data and feature_data according to your problem specifics.
Example mdp_data:
# Define the number of states and actions
states = data['state'].nunique()
actions = data['action'].nunique()
transitions = 1 # Set to 1 if deterministic; adjust accordingly
# Initialize transition probabilities and next states
sa_p = np.zeros((states, actions, transitions))
sa_s = np.zeros((states, actions, transitions), dtype=int)
# Build transition probabilities and next states from data
for idx, row in data.iterrows():
s = int(row['state'])
a = int(row['action'])
sp = int(row['next_state'])
sa_p[s, a, 0] = 1.0 # Assuming deterministic transitions
sa_s[s, a, 0] = sp
# Define mdp_data
mdp_data = {
'states': states,
'actions': actions,
'sa_p': sa_p,
'sa_s': sa_s,
'discount': 0.99 # Set your discount factor
}
Example feature_data:
If you have specific features for your states, you can define them. Otherwise, use identity features:
# Use identity features if no specific features are provided
feature_data = {
'splittable': np.eye(states)
}
Running the MaxEnt IRL Algorithm
Set up algorithm_params and call maxentrun:
algorithm_params = {}
algorithm_params = maxentdefaultparams(algorithm_params)
# Verbose output
verbosity = 1
# Assuming MDP model is linear
mdp_model = 'linear'
# No true features provided
true_features = None
# Run the algorithm
irl_result = maxentrun(
algorithm_params, mdp_data, mdp_model,
feature_data, example_samples, true_features, verbosity
)
Notes:
- The code assumes that states and actions are numbered from 0 to (N-1).
- The transition probabilities
sa_p and next states sa_s should be constructed based on your data and the specifics of your MDP.
- Ensure that your data does not contain any inconsistencies, like undefined states or actions.
- The reward function learned (
irl_result['r']) and the policy (irl_result['p']) can be used to analyze the behavior inferred by the algorithm.
Missing Functions:
All functions from the MATLAB code have been translated into Python. If you have any custom functions or require further adjustments (e.g., handling stochastic transitions, custom features), please provide the details, and we can incorporate them accordingly.
Let me know if you need any assistance with specific parts of the code or further customization for your dataset!