===== PDF PAGE 1 =====
         Inverse Reinforcement Learning with Switching Rewards and History

                  Dependency for Characterizing Animal Behaviors





                     Jingyang Ke 1 Feiyang Wu 1 Jiyi Wang 1 Jeffrey E. Markowitz 1 2 Anqi Wu 1





                          Abstract                                  1. Introduction

                                                                    Historically, decision making in neuroscience has been stud-

       Traditional approaches to studying decision-

                                                                    ied using simplified assays where animals perform repet-

       making in neuroscience focus on simplified be-

                                                                    itive, stereotyped actions (such as licks, nose pokes, or

       havioral tasks where animals perform repeti-

                                                                    lever presses) in response to sensory stimuli to obtain an

       tive, stereotyped actions to receive explicit re-

                                                                    explicit reward. While this approach has its advantages, it

       wards. While informative, these methods con-

                                                                    has limited our understanding of decision making to scenar-

       strain our understanding of decision-making to

                                                                    ios where animals are instructed to achieve an explicit goal

       short timescale behaviors driven by explicit goals.

                                                                    over brief timescales, usually no more than tens of seconds.

       In natural environments, animals exhibit more

                                                                    In contrast, in natural environments, animals exhibit much

       complex, long-term behaviors driven by intrin-

                                                                    more complex behaviors that are not confined to structured,

       sic motivations that are often unobservable. Re-

                                                                    stereotyped trials. For example, a freely moving mouse may

       cent works in time-varying inverse reinforce-

                                                                    immediately rush toward the scent of food when hungry, but

       ment learning (IRL) aim to capture shifting mo-

                                                                    after eating, it might seek out a quiet spot to rest for an ex-

       tivations in long-term, freely moving behaviors.

                                                                    tended period. Thus, real-world animal behaviors form long

       However, a crucial challenge remains: animals

                                                                    sequences composed of multiple decision-making processes.

       make decisions based on their history, not just

                                                                    Each decision-making process involves a series of states

       their current state. To address this, we intro-

                                                                    and actions aimed at achieving a goal, and such decision

       duce SWIRL (SWitching IRL), a novel frame-

                                                                    switching is unlikely to occur on very short timescales in

       work that extends traditional IRL by incorporating

                                                                    simplified assays. Additionally, many of the goals animals

       time-varying, history-dependent reward functions.

                                                                    pursue in natural settings are generated by intrinsic motiva-

       SWIRL models long behavioral sequences as tran-

                                                                    tions and thus unobservable. To truly understand animal’s

       sitions between short-term decision-making pro-

                                                                    decision-making in a naturalistic context, we need methods

       cesses, each governed by a unique reward func-

                                                                    to uncover animals’ intrinsic motivations during multiple

       tion. SWIRL incorporates biologically plausi-

                                                                    decision-making processes.

       ble history dependency to capture how past deci-

       sions and environmental contexts shape behavior,             Inverse reinforcement learning (IRL), which infers agents’

       offering a more accurate description of animal               policies and intrinsic reward functions based on their inter-

       decision-making. We apply SWIRL to simulated                 actions with the environment (Ng & Russell, 2000; Abbeel

       and real-world animal behavior datasets and show             & Ng, 2004; Ziebart et al., 2008; 2010; Wu et al., 2024),

       that it outperforms models lacking history de-               has been shown to be effective in capturing animal decision-

       pendency, both quantitatively and qualitatively.             making intentions by learning reward functions from be-

       This work presents the first IRL model to incor-             havioral trajectories (Sezener et al., 2014; Yamaguchi et al.,

       porate history-dependent policies and rewards to             2018; Pinsler et al., 2018; Hirakawa et al., 2018). However,

       advance our understanding of complex, naturalis-             traditional IRL assumes a single static reward function over

       tic decision-making in animals.                              time, limiting its ability to account for shifts in intrinsic moti-

                                                                    vations. To address this limitation, recent IRL variants have

   1

                                                                    aimed to uncover heterogeneous and time-varying reward

    Georgia Institute of Technology, Atlanta, GA, USA 2 Emory       functions (Babes-Vroman et al., 2011; Surana & Srivastava,

University, Atlanta, GA, USA. Correspondence to: Anqi Wu <an-

qiwu@gatech.edu>.                                                   2014; Nguyen et al., 2015; Ashwood et al., 2022a; Zhu et al.,

                                                                    2024). Despite these advancements, a significant challenge

Proceedings of the 42 nd International Conference on Machine        remains unaddressed: animals make decisions based on their

Learning, Vancouver, Canada. PMLR 267, 2025. Copyright 2025         history, not just their current state (Kennedy, 2022; Hattori

by the author(s).



                                                                1


===== PDF PAGE 2 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



et al., 2019). For example, in perceptual decision-making          that SWIRL outperforms alternative models when history

tasks, mice are found to make new decision based on reward,        dependency is not included, both quantitatively and qualita-

state and decision history (Ashwood et al., 2022b). Incor-         tively. This underscores the necessity of incorporating this

porating historical context into the modeling could offer a        biologically plausible element when modeling long-term be-

more accurate representation of animal behavior.                   haviors. Additionally, for the first time, we will present the

                                                                   application of non-Markovian reward functions and state-

To address the absence of history dependency in time-

                                                                   action reward functions to model freely-moving animals,

varying IRL models, we introduce a novel framework called

                                                                   contrasting with previous works that only assume a single

SWitching IRL (SWIRL). Similar to Zhu et al. (2024),

                                                                   state-based reward.

SWIRL models long recordings of animal behaviors as a

sequence of short-term decision-making processes. Each

decision-making process is treated as a Markov decision            2. Related Work

process (MDP) with a unique reward function that can be in-

                                                                   IRL for animal behavior understanding. IRL has been

ferred using IRL. The segmentation of a long recording into

                                                                   widely used to infer animals’ behavioral strategies and

switching decision-making processes is unknown; therefore,

                                                                   decision-making policies when the reward is unknown. For

each process is regarded as being associated with a hidden

                                                                   instance, Pinsler et al. (2018) applies IRL to uncover the un-

mode that must also be inferred. Most importantly, SWIRL

                                                                   known reward functions of pigeons, explains and reproduces

incorporates biologically plausible history dependency,

                                                                   their flock behavior, and introduces a method to learn a

drawing on insights from animal behavior. The history

                                                                   leader-follower hierarchy. Similarly, Hirakawa et al. (2018)

dependency is added at two levels: the transitions between

                                                                   uses IRL to learn reward functions from animal trajectories,

decision-making processes (decision-level) and the actions

                                                                   identifies environmental features preferred by shearwaters,

taken to achieve a single goal within a decision-making

                                                                   and demonstrates differences in male and female migration

process (action-level). Decision-level dependency is

                                                                   route preferences based on the estimated rewards. In another

reflected in the transitions between decision-making

                                                                   study, Yamaguchi et al. (2018) applies IRL to C. elegans

processes over extended sequences of time bins, suggesting

                                                                   thermotactic behavior, revealing distinct behavioral strate-

that an animal’s current choice is shaped by its previous

                                                                   gies for fed and unfed worms. Additionally, Sezener et al.

decisions and environmental feedback. Additionally, we

                                                                   (2014) maps reward functions for rats freely moving in a

posit that these transitions are influenced by the animal’s

                                                                   square area, showing how these rewards changed before and

location. For example, after a mouse drinks from a water

                                                                   after training. While these studies demonstrate the utility of

port, if it stays nearby, it is more likely to seek another

                                                                   IRL in uncovering behavioral strategies of freely moving an-

goal. Conversely, if it is far from the port, indicating

                                                                   imals, they share a key limitation: they all assume a single re-

it has been away for some time, it may become thirsty

                                                                   ward function governs all animal behaviors, which does not

again and return to search for water. For action-level

                                                                   account for the complexities of long-term decision-making.

history dependency, we will model the policy and reward

functions as dependent on trajectory history within each           Heterogeneous and time-varying IRL. Recent works have

decision-making process, using a non-Markovian decision            extended traditional IRL, which assumes a constant reward,

framework. Such a dependency has been studied by existing          to models with time-varying or multiple reward functions

reinforcement learning research, which often characterizes         driving behavioral trajectories. For example, Babes-Vroman

exploration with reward functions based on historical states       et al. (2011) introduced Multi-intention IRL, which infers

and actions (Houthooft et al., 2016; Sharafeldin et al.,           multiple reward functions across different trajectories but

2024). Importantly, SWIRL is the first to incorporate              still assumes a single reward function within each trajec-

history-dependent policies and rewards into IRL.                   tory. On the other hand, the Dynamic IRL (DIRL) method

                                                                   (Ashwood et al., 2022a) models reward functions as a lin-

One key aspect we want to highlight in this paper is that

                                                                   ear combination of feature maps with time-varying weights,

the proposed SWIRL model has intriguing connections to

                                                                   addressing the issue of varying rewards within a trajectory.

traditional behavioral analysis methods in the animal neu-

                                                                   However, DIRL requires trajectories to be highly similar or

roscience literature. In Sec. 3.5, we will demonstrate that

                                                                   clustered beforehand, significantly limiting its applicabil-

our SWIRL model offers a more generalized and princi-

                                                                   ity. Moreover, it cannot capture switching decision-making

pled approach to characterize animal behaviors compared to

                                                                   processes over long-term periods where each process may

existing autoregressive dynamics models (Wiltschko et al.,

                                                                   vary in length. Additionally, BNP-IRL (Surana & Srivas-

2015; Mazzucato, 2022; Stone, 2023; Weinreb et al., 2024).

                                                                   tava, 2014), locally consistent IRL (Nguyen et al., 2015) and

In the Results section, we will apply our SWIRL to a sim-          multi-intention inverse Q-learning (IQL) (Zhu et al., 2024)

ulated dataset as well as two real-world animal behavior           all extended the multi-intention IRL framework to allow

datasets. For both animal datasets, we will demonstrate            for changing reward functions within trajectories, making





                                                               2


===== PDF PAGE 3 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



them the closest models to our proposed SWIRL. How-                                                              Hidden modes

ever, all models do not account for both decision-level and

action-level history dependency, an important biologically

plausible factor that SWIRL incorporates to achieve more                                                              Action

accurate behavior modeling. In our experiments, we will use

multi-intention IQL and locally consistent IRL as baseline                                                             States

models, as they are special cases of SWIRL.

                                                                      Figure 1. SWIRL graphical model. Green dotted lines repre-

Dynamics-based behavior analysis in animal neuro-                     sent transitions of the hidden modes depend on the previous state

science. Traditional approaches to analyzing animal behav-            (decision-level dependency). Blue dotted lines represent that po-

ior in neuroscience often rely on autoregressive dynamics             lices depend on past states (action-level dependency).

models. For instance, MoSeq and related works (Wiltschko

et al., 2015; Weinreb et al., 2024) assume that animal be-            from an expert agent π ∗ , comprising a set of state-action

havior consists of multiple segments modeled by a hidden              pairs {(s∗t , a∗t )}. The goal is to estimate the policy and

markov model (HMM), with each segment evolving through                reward that generated these state-action pairs, often

an autoregressive process. Stone (2023) introduces a switch-          referred to as expert demonstrations in IRL literature.

ing linear dynamical system (SLDS), similar to an ARHMM,              We assume that we have collected N expert trajectories,

but with an additional layer of continuous latent states be-          denoted as D = {ξ1 , ξ2 , . . . , ξN }. Each trajectory con-

tween the behavioral trajectories and the hidden states repre-        sists of a sequence of state-action pairs, represented as

senting behavioral segments. We argue that if each segment            ξn = {(s∗1 , a∗1 ), (s∗2 , a∗2 ), . . .}, with Tn time steps, which

lasts only a few seconds, it represents meaningful action             may vary across trajectories.

motifs, such as grooming and sniffing. However, if a seg-

ment is significantly longer and reflects a decision-making           3.3. Switching Inverse Reinforcement learning

process, traditional dynamics-based models may not be suit-

able for identifying these long-term segments. However,               Our SWIRL model is built on the HM-MDP. Instead of

these dynamics-based models are not entirely independent              explicitly knowing the reward for each mode, we will use

of SWIRL. We will demonstrate that SWIRL generalizes                  IRL to infer these rewards. Mathematically, at each time

purely dynamics-based models by relying on a more princi-             step t, we represent the agent’s internal reward function rzt

pled IRL framework to identify multiple decision-making               with an additional dependency on the hidden mode zt . This

processes. Our goal is to offer insights that bridge these            means that the agent receives a reward rzt based on its cur-

traditional and new models for animal behavioral analysis.            rent hidden mode zt , which indicates the decision-making

                                                                      state the animal is in (e.g., water seeking or home seeking),

                                                                      with rzt representing the corresponding intrinsic motiva-

3. Methods                                                            tion. Consequently, the optimal policy πt is determined by

3.1. Hidden-Mode Markov Decision Process                              rzt . However, SWIRL goes beyond merely embedding IRL

                                                                      within HM-MDP: We also introduce two levels of history

A discounted Hidden-Mode Markov Decision Process (HM-                 dependency into the model. The full graphical model is

MDP) is defined by the tuple M = (Z, S, A, P, Pz , r, γ).             depicted in Fig. 1.

Here, Z represents a finite set of hidden modes z, S de-

notes the finite state space, and A indicates the finite action       The decision-level dependency is characterized by the idea

space. rz represents the reward function r under hidden               that animals make new decisions based on their previous

mode z. The discount factor γ is constrained to the interval          choices. The transitions between decision-making processes

[0, 1]. Starting from an initial state s0 , the agent (animal)        already account for this decision-level dependency since

selects an action a based on its policy (behavioral strategy)         Pz (zt+1 |zt ). However, the hidden modes with such a clas-

π and subsequently receives a reward determined by rz ,               sical transition are generated through an open-loop process:

z ∈ Z := {z1 , z2 , . . . , zm }, where m represents the total        the mode zt+1 depends solely on the preceding mode zt ,

number of modes. The agent then transitions to the next               with zt+1 |zt being independent of the observation state st .

state s′ according to the transition kernel P(s′ |s, a), while        Consequently, if a discrete switch should occur when the an-

the agent’s hidden mode also transitions to z ′ based on the          imal enters a specific region of the state space, the classical

transition probability Pz (z ′ |z).                                   transition will fail to capture this dependency. To address

                                                                      this, we extend the transition model to include the state st as

3.2. Inverse Reinforcement Learning                                   a condition, resulting in Pz (zt+1 |zt , st ), which effectively

                                                                      captures the desired relationship between decisions and the

Inverse Reinforcement Learning (IRL) addresses the                    animal’s location.

scenario where we have gathered multiple trajectories

                                                                      For action-level history dependency, we treat both the re-



                                                                  3


===== PDF PAGE 4 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



ward and policy under a hidden mode z as functions de-                          Detailed SWIRL algorithm and EM derivation are provided

pendent on the previous L states, specifically rz : S L ×                       in Appendix A.1 & A.2.

A → R and πz : S L → A, where L ∈ N and S L

                                                                                It is worth noting that this EM derivation seeks to maxi-

denotes the cartesian product of L state spaces. To sim-

                                                                                mize the log-likelihood of policy πzt (at |sLt ; rz ) given the

plify the notation, we denote an element of S L as sL , so

                                                                                posterior of zt (Eq. 3). This procedure can be incorporated

that rz (sL , a) := rz (s1 , s2 , . . . , sL , a) and πz (a|sL ) :=

                                                                                into the Maximum Entropy IRL (MaxEnt IRL) (Ziebart

πz (a|s1 , s2 , . . . , sL ), and pad both functions with dummy

                                                                                et al., 2008; 2010) framework, since optimizing the reward

variables if the current time step is less than L. While it

                                                                                by maximizing log π corresponds to the Lagrangian dual

is also possible to incorporate previous actions into the re-

                                                                                of the standard MaxEnt IRL approach (Zeng et al., 2022).

ward function, we focus on state-only rewards for simplicity,

                                                                                As a result, SWIRL can leverage a variety of IRL methods

which is a common practice in IRL. Nonetheless, this frame-

                                                                                within the MaxEnt IRL framework: SWIRL can be inte-

work naturally extends from a single-state dependency to a

                                                                                grated with model-based methods to infer the policy used

history of states.

                                                                                to optimize the reward, such as Soft-Q iteration (Haarnoja

Furthermore, we can view the decision process as being non-                     et al., 2017), or model-free methods, such as Soft-Q learn-

Markovian, meaning that the current decision or action de-                      ing (Haarnoja et al., 2017) and Soft Actor-Critic (Haarnoja

pends not only on the current state but also on the history of                  et al., 2018). Alternatively, we can also convert the MaxEnt

previous states and actions. Noticeably, there are various ap-                  IRL problem to a model-free inverse Q-learning problem,

proaches to address non-Markovian decision processes, in-                       such as IQ-Learn (Garg et al., 2021). Although model-free

cluding state augmentation (Sutton, 1991), recurrent neural                     methods are often more general and scalable, we find that

networks (Bakker, 2001; Hausknecht & Stone, 2015), Neu-                         the model-based Soft-Q iteration approach is more suitable

ral Turing Machines (Parisotto & Salakhutdinov, 2017) and                       for our behavioral neuroscience study setting, where envi-

so forth. In this paper, we adopt the most common approach–                     ronment sizes tend to be small, data availability is limited,

state augmentation; however, the framework can also be                          and the accuracy requirement for reward recovery is high.

implemented using more advanced and scalable methods.                           Accordingly, we use the Soft-Q iteration approach in our

                                                                                main experiments. Nevertheless, in Appendix C.1 we also

3.4. SWIRL Inference Procedure                                                  demonstrate that SWIRL can be integrated with the model-

                                                                                free IQ-Learn to achieve solid performance, illustrating

The goal of inference is to learn the hidden modes z and                        SWIRL’s potential in broader applications.

the model parameters θ = (Pz , rz , πz , p(s1 ), p(z1 )) given

the collected trajectories D. Here, p(s1 ) and p(z1 ) repre-

                                                                                3.5. Connection to Dynamics-based Behavior Methods

sent the probabilities of the initial state and hidden mode,

respectively. The variables rz and πz denote the reward and                     Traditional methods for analyzing animal behavior in neu-

policy associated with the hidden mode z, while Pz is the                       roscience often use autoregressive dynamics models, with

transition matrix between hidden modes. We can maximize                         the autoregressive hidden Markov model (ARHMM) being

the likelihood of the demonstration trajectories D to learn                     the most prevalent (Wiltschko et al., 2015; Weinreb et al.,

the optimal θ∗ , such that θ∗ = argmaxθ log P (D|θ) (MLE).                      2024). ARHMMs assume that the animal behavior con-

However, achieving this objective requires marginalizing                        sists of multiple segments represented by a hidden Markov

over the hidden modes z, which is intractable. To address                       model, where each segment evolves through an autoregres-

this issue, we employ the Expectation-Maximization (EM)                         sive process. Using the notation established earlier, we

algorithm, alternating between inferring the posterior distri-                  denote hidden modes as zt at time t, following the transi-

butions of the hidden modes and updating the parameters                         tion p(zt+1 |zt ). At each time step t, the observation state

with the following auxiliary function:                                          st follows conditionally linear (or affine) dynamics, deter-

                                                                                mined by the discrete mode zt . This can be expressed as

                                  X

   G(θ, θ̂) = log p(s1 ) +             p(z1 |ξ, θ̂) log p(z1 )        (1)       st+1 = Azt st + vt , where Azt is the linear dynamics associ-

                                   z                                            ated with zt and vt represents Gaussian noise. If zt changes,

        T

        X −1                                                                    the linear dynamics will also change accordingly. More

    +          log P(st+1 |st , at )                                  (2)       generally, we can represent the dynamics as p(st+1 |st , zt ).

        t=1                                                                     Consequently, the overall generative model for the ARHMM

        T X

        X                                                                       can be summarized as follows: (1) zt ∼ p(zt |zt−1 ), and (2)

    +              p(zt |ξ, θ̂) log πzt (at |sL

                                              t ; rz )                (3)       st+1 ∼ p(st+1 |st , zt ). Let’s outline the generative model of

        t=1 zt                                                                  SWIRL without P      history dependency: (1) zt ∼ p(zt |zt−1 ),

        T

        X −1    X                                                               and (2) st+1 ∼ at p(st+1 |st , at )π(at |st , zt ). The term

    +                  p(zt , zt+1 |ξ, θ̂) log Pz (zt+1 |zt , st ).   (4)       π(at |st , zt ) arises because the policy is derived from rzt .

        t=1 zt ,zt+1                                                            Consequently, the primary distinction between ARHMM



                                                                            4


===== PDF PAGE 5 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



and SWIRL lies in the dynamics used to generate st+1 .                   4. Results

We can show that SWIRL is a more generalized ver-                        Throughout the experiment section, we use the following

sion of ARHMM. In a deterministic MDP, where                             terminology to denote our proposed algorithms and the base-

p(st+1 |st , at ) is a delta function and each action at                 line models we compare:

       P determines st+1 , st+1 directly implies at .

uniquely                                                                 • MaxEnt (Ziebart et al., 2008; 2010): Maximum Entropy

Thus,      at p(st+1 |st , at )π(at |st , zt ) = π(at |st , zt ) =       IRL where the reward function is only a function of the

p(st+1 |st , zt ).   This effectively reduces SWIRL to                   current state and action. It is a single-mode IRL approach

ARHMM. In the second real-world experiment (Sec. 4.3),                   with a single reward function.

the MDP setup satisfies these assumptions. In such a                     • Multi-intention IQL (Zhu et al., 2024): learns time-

case, ARHMM can be seen as performing policy learn-                      varying reward functions based on HM-MDP. It is a SWIRL

ing through behavioral cloning without learning a reward                 model with no history dependency.

function, whereas SWIRL employs IRL to learn the policy.                 • Locally Consistent IRL (Nguyen et al., 2015): learns

Having established this connection, we can view SWIRL as                 time-varying reward functions based on HM-MDP. It is a

a more generalized version of ARHMM, as it permits the                   SWIRL model with no action-level history dependency.

MDP to be stochastic and allows multiple actions to result               • ARHMM (Wiltschko et al., 2015): learns the segmen-

in the same preceding state. Additionally, explicitly mod-               tation of animal behaviors using autoregressive dynamics

eling the policy introduces a reinforcement learning frame-              combined with a hidden Markov model.

work that better represents the decision-making processes                • rARHMM (Linderman et al., 2016): recurrent ARHMM

of animals and reveals the underlying reward function. For               whose transition probability of the hidden modes also relies

SWIRL with history dependency, we can further connect it                 on the state.

to the recurrent ARHMM (Linderman et al., 2016), which                   • I-1, I-2: the baseline variant of our proposed SWIRL

expands p(zt+1 |zt ) to p(zt+1 |zt , st ).                               method which assumes the transition kernel Pz is indepen-

                                                                         dent of the state. The reward and policy depend either on the

Another advanced version of the ARHMM is the switching                   current state (in the case of I-1) or on both the current and

linear dynamical system (SLDS), which assumes that the                   previous states (in the case of I-2). Note that I-1 represents

state st is unobserved. Instead, the observed variable yt is             the simplest version of SWIRL, which corresponds to Multi-

a linear transformation of st . Thus, the complete genera-               intention IQL. Thus, we use I-1 to denote Multi-intention

tive model for SLDS consists of: (1) zt ∼ p(zt |zt−1 ), (2)              IQL. The model can incorporate an arbitrary history length

st+1 ∼ p(st+1 |st , zt ), and (3) yt+1 ∼ p(yt+1 |st+1 ). This            L for the policy and reward; in this paper, we use L = 1

suggests that the representation st capturing the primary                and L = 2.

dynamics is, in fact, a latent representation of the observa-            • S-1, S-2: our proposed SWIRL method where Pz is state

tion yt . Building on this concept, we can extend SWIRL                  dependent. The suffix follows the same setup as above. S-1

into a latent variable model, where st serves as the latent              corresponds to Locally Consistent IRL.

representation of the true observation state yt . This corre-

sponds to the setup of Partial Observation Markov Decision               SWIRL code can be found at https://github.com/

Process (POMDP) in the literature. While SWIRL is not                    BRAINML-GT/SWIRL.

a POMDP method in the formal sense (e.g., modeling be-

lief states or latent dynamics explicitly), it does address              4.1. Application to a simulated gridworld environment

non-Markovian behavior by augmenting the state space                     We begin by testing our method on simulated trajectories

with recent history (e.g., using st , st−1 , st−2 , . . . ). This        within a 5 × 5 gridworld environment, where each state al-

is a commonly used strategy to handle partial observability              lows for five possible actions: up, down, left, right, and stay.

or non-Markovianity—similar in spirit to how LSTMs or                    The agent alternates between two reward maps: a home

memory-based policies are used in POMDP settings. There-                 reward map and a water map (see Fig. 2A). Following the

fore, SWIRL leverages temporal context in a manner similar               design of real animal experiments (Rosenberg et al., 2021),

to methods designed for POMDPs. This extension will link                 we assume that the water port provides water to the agent

SWIRL to representation learning in reinforcement learning,              only once per visit. Therefore, under the water reward map,

which can be explored further in future work.                            the agent receives a reward for (1) visiting the water state

Thus, we argue that SWIRL offers a more generalized and                  if it was not in the water state previously or (2) leaving the

principled approach to studying animal behavior compared                 water state. The home reward map returns a reward at the

to commonly used dynamics-based models, as one can draw                  home state. This leads to a non-Markovian reward func-

inspiration from the development of (latent) dynamics mod-               tion that relies on both the current state and the previous

els to enhance advanced IRL methods for analyzing animal                 state. We employed soft-Q iteration to determine the optimal

decision-making processes.                                               policy for each reward function and generated 200 trajecto-





                                                                     5


===== PDF PAGE 6 =====
               Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



   A              true        discovered                             B

home reward









                                                                                                                                                             Test segment accuracy

                                              r     st       s t-1









                                                                     R correlation

                                                  current   right









                                                                                                                    Test LL

                                                  current   above

                  true        discovered

                                                  current    left

water reward









                                                  current   below



                                                  current current



                                                                                     MaxEnt I-1   I-2   S-1   S-2             MaxEnt I-1   I-2   S-1   S-2                           I-1   I-2   S-1   S-2









 Figure 2. Simulation experiment on a 5 × 5 gridworld. (A) Comparison between the true and discovered reward maps. The color scale

 represents reward values ranging from 0 to 1. The home reward is defined as r(st ), while the water reward depends on both the current

 and previous locations, r(st , st−1 ). To present the water reward, each location is divided into five groups, as detailed in the table on the

 far right. For example, the polygon in the first row represents the reward value when st is the current location and st−1 is the location to

 the right. Light grey indicates an impossible transition where no reward exists. (B) Box plots illustrating the Pearson correlation between

 the true and recovered reward maps, test log-likelihood, and test segmentation accuracy over 10 runs. The x-axis represents the five

 different models. Outlier selection method is described in Appendix B.8.





 ries based on the learned policy, using a history-dependent                                      To assess the robustness of SWIRL, in Appendix B.7, we

 hidden-mode switching dynamic Pz (zt+1 |zt , st ). Accord-                                       evaluated the performance of SWIRL (S-2) under increasing

 ingly, the agent is more likely to switch to the home map                                        levels of random perturbations in this gridworld dataset. We

 after visiting the water port and to switch to the water map                                     found that SWIRL can tolerate moderate levels of noise or

 after returning home. Each trajectory consists of 500 steps.                                     incomplete data (with 30% of the states and actions in train-

                                                                                                  ing data permuted), making it suitable for real-world animal

 We then used SWIRL to learn the reward functions and the

                                                                                                  behavior datasets where such challenges are common.

 transition dynamics between them, based on 80% of the

 generated trajectories. As a baseline, we employed the Max-

 imum Entropy IRL (MaxEnt) method and tested four varia-                                          4.2. Application to long, non-stereotyped mouse

 tions of the SWIRL models (I-1, I-2, S-1, S-2), with I-1 rep-                                         trajectories

 resenting multi-intention IQL. Fig. 2A displays a compari-                                       We then applied SWIRL to the long, non-stereotyped trajec-

 son between the true and discovered reward functions, while                                      tories of mice navigating a 127-node labyrinth environment

 Fig. 2B presents boxplots showing the Pearson correlation                                        with water restrictions (Rosenberg et al., 2021). In this ex-

 between the true and recovered reward functions, along with                                      periment, a cohort of 10 water-deprived mice moved freely

 the test log-likelihood (LL) and test segmentation accuracy                                      in the dark for 7 hours. A water reward was provided at an

 (which measures the ability to predict the correct segments                                      end node (Fig. 3A), but only once every 90 seconds at most.

 for home and water modes). The test performance was eval-                                        Similar to the simulated experiment, the 90-second condi-

 uated using the remaining 20% of the trajectories. Notably,                                      tion forces the mice to leave the port after drinking water,

 accurate reward recovery was only achieved with the S-2                                          leading to a non-Markovian internal reward function. For

 model. All four SWIRL variations outperformed MaxEnt,                                            our analysis, we segmented the raw node visit data into 238

 indicating the presence of more than one hidden model.                                           trajectories, each comprising 500 time points. This data for-

 Both the state dependency of hidden-mode transitions                                             mat presents a considerably greater challenge compared to

 (decision-level dependency) and the history dependency                                           the same dataset processed with more handcrafted methods

 reward function (action-level dependency) contributed to                                         in previous IRL applications (Ashwood et al., 2022a; Zhu

 further improvements in test LL and segmentation accu-                                           et al., 2024), which were limited to clustered, stereotyped

 racy. Specifically, only the state-dependent models (S-1,                                        trajectories of only about 20 time points in length.

 S-2) could accurately and robustly recover test segments,

 while the independent models (I-1, I-2) exhibited lower                                          4.2.1. SWIRL INFERRED INTERPRETABLE

 accuracy with higher variance. This is attributed to the non-                                           HISTORY- DEPENDENT REWARD MAPS

 Markovian reward design, where the agent can only receive

 water once per visit. Notably, S-2, the full SWIRL model                                         We applied SWIRL to 80% of the 238 mouse trajectories

 incorporating both decision-level and action-level dependen-                                     from the water-restricted labyrinth experiments. Accord-

 cies, demonstrated the best performance across all metrics.                                      ing to Rosenberg et al. (2021), mice quickly learned the

                                                                                                  labyrinth environment and began executing optimal paths





                                                                                             6


===== PDF PAGE 7 =====
      Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



A                      B                                             C              r=0.4           D        water               home              explore

                                                                                                                            1                  1                 1

    start        end                                                                        r=1.0

                                                                                   r=1.0

                                                                       water







                       Test LL

                                                                                   r=1.0

                                                                                            r=0.4

                                                                                   r=0.7

                                                                       explore

                                                                                                                            0                  0                 0

                                 MaxEnt I-1   I-2       S-1   S-2

E                                                                                                   F        water              home               explore       end

 I-1

 I-2

                                                                                                              🏠                  🏠                  🏠

S-1                                                                                                                     💧                  💧                 💧

S-2

                                                 time

               water         home      explore          water port visit   home visit                                                                            start





Figure 3. Water-restricted labyrinth experiment. (A) Setup for the labyrinth experiment. (B) Boxplot showing held-out test LL over

10 runs, with the x-axis representing the five different models. Outlier selection method is described in Appendix B.8. (C) History

dependency inferred by SWIRL (S-2), as reflected in reward maps of the water mode and the explore mode. (D) Inferred reward maps

from SWIRL (S-2) under three hidden modes: water, home, and explore. To enhance visualization, the inferred reward r(st , st−1 ) was

averaged over st−1 to produce r(st ). (E) Segments of a trajectory from held-out test data, predicted by four SWIRL models. The orange

dot indicates when the mouse visits the water port, while the red cross denotes the mouse’s visit to state 0 (home) at that time. (F)

Trajectories segmented into hidden modes based on SWIRL (S-2) predictions.





from the entrance to the water port within the first hour of                                            a substantial reward (0.7). This observation aligns with the

the experiment. Therefore, we assume the mice acted opti-                                               water port design, as mice can only obtain water once every

mally concerning the internal reward function guiding their                                             90 seconds. Consequently, it makes sense that the mice

behavior. We tested a number of hidden modes Z from 2 to                                                would want to leave the water port after reaching it.

5 in Appendix B.6.1 and found Z = 3 to be the best fit. Fig.

3B displays the held-out test LL for MaxEnt and the SWIRL                                               4.2.2. SWIRL INFERRED INTERPRETABLE

variations based on the remaining 20% of trajectories. The                                                     HISTORY- DEPENDENT HIDDEN - MODE SEGMENTS

state dependency in hidden-mode switching dynamics and

                                                                                                        We then visualized all mouse trajectories based on the

the history dependency in the reward function contributed to

                                                                                                        hidden-mode segments predicted by SWIRL (S-2) (Fig. 3F).

improved test performance. The final SWIRL model (S-2)

                                                                                                        In segments classified as water mode, mice start from var-

successfully recovered a water reward map, a home reward

                                                                                                        ious locations in the labyrinth and move toward the water

map, and an explore reward map (Fig. 3D). For better visu-

                                                                                                        port. In segments identified as home mode, mice begin from

alization, we averaged the S-2-recovered history-dependent

                                                                                                        distant nodes and head toward the center of the labyrinth

rewards across previous states and normalized the reward

                                                                                                        (home). In segments categorized as explore mode, mice

values to a range of (0, 1). In the water reward map, mice

                                                                                                        start from junction nodes or the water port and explore end

received a high reward for visiting the water port. In the

                                                                                                        nodes. This result demonstrates that SWIRL can identify

home reward map, there was a high reward for visiting state

                                                                                                        sub-trajectories of varying lengths from raw data spanning

0 at the center of the labyrinth, which also served as the

                                                                                                        500 time points, allowing us to visualize them together and

entrance and exit. Mice occasionally went to state 0 to enter

                                                                                                        reveal clustered behavioral strategies. This capability has

or leave the labyrinth and sometimes passed by on their way

                                                                                                        not been achieved by previous studies on freely moving

to other nodes. In the explore reward map, mice received a

                                                                                                        animal behavior over extended recording periods, and we

high reward for exploring areas of the labyrinth other than

                                                                                                        conducted this analysis without prior knowledge of the lo-

state 0.

                                                                                                        cations of the water port or home.

Importantly, SWIRL recovered an interpretable history-

                                                                                                        We also provide a detailed visualization of the hidden-mode

dependent reward map for the water port (Fig. 3C). In the

                                                                                                        segments from an example trajectory in the held-out test

water mode, mice always receive a high reward for reaching

                                                                                                        data and compare the segmentation performance of the four

the port, irrespective of where they were before. On the

                                                                                                        SWIRL variations (Fig. 3E). In the S-2 segments, visits to

contrary, in the explore mode the reward depends on their

                                                                                                        the water port (indicated by orange dots) consistently occur

previous location: if the mouse was already at the water

                                                                                                        near the end of a water mode segment, while visits to state

port, leaving it is valued more (1.0) than staying (0.4); if the

                                                                                                        0 (home) (indicated by red crosses) typically happen at the

mouse came from elsewhere, reaching the port still provides





                                                                                                7


===== PDF PAGE 8 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



conclusion of a home mode segment. Notably, home mode                to compare the performance of SWIRL with ARHMM and

segments that do not include a visit to state 0 can still be         its variant, rARHMM.

valid, as these segments may end at state 1 or 2. In contrast,

                                                                     We applied SWIRL, rARHMM, ARHMM, and MaxEnt to

the I-1, I-2, and S-1 segments exhibit instances of water

                                                                     80% of the trajectories and assessed the held-out test LL

segments that do not involve a visit to the water port, along

                                                                     on the remaining 20% (Fig. 4B). All four SWIRL models

with many home segments that lack clear interpretability.

                                                                     outperformed ARHMM and rARHMM on this dataset, indi-

Overall, S-2 successfully identifies robust segments of rea-

                                                                     cating that learning rewards is more beneficial for behavior

sonable length, avoiding the numerous rapid switches seen

                                                                     segmentation and explaining the behavior trajectories. In-

in the other variations. We attribute this to both the state

                                                                     terestingly, the history dependency in the reward function

dependency of hidden mode transitions and the history de-

                                                                     resulted in lower test LL, as S-1 and I-1 demonstrated higher

pendency in rewards. This suggests that mice are unlikely to

                                                                     test LL than S-2 and I-2. We believe this is attributable to

make quick changes in their decisions; instead, they make

                                                                     the merging of consecutive identical syllables and the selec-

choices based on their current location and take into account

                                                                     tion of the top 9 syllables during the preprocessing phase

at least two locations while navigating the maze.

                                                                     for this dataset. As a result of these steps, the actual time

Furthermore, in Appendix B.6.2, we found S-3 and S-4 ex-             interval between st−1 and st may vary significantly, lead-

hibited even higher test LL than S-2, suggesting the presence        ing to a poorly defined time concept that complicates the

of longer action-level history dependency (L > 2) in this            model’s ability to capture the history dependency in the re-

labyrinth dataset. This observation aligns with the partially        ward function. However, we can use SWIRL with different

observable nature of this 127-node labyrinth: The mouse              variations as a hypothesis-testing tool. The variation yield-

may not know the whole environment, so it likely relies on           ing the highest test LL may be regarded as more accurately

a longer history of prior states to guide its decision-making.       reflecting the dynamics and structure of the data. Conse-

However, hidden mode predictions of S-3 and S-4 are very             quently, these results suggest that the behavior trajectories

close to that of S-2, suggesting that S-2 is already powerful        exhibit only Markovian dependency rather than long-term

enough for hidden mode prediction.                                   non-Markovian dependency. Since S-1 remains higher than

                                                                     I-1, we conclude that the state dependency in the hidden

4.3. Application to mouse spontaneous behavior                       mode transition contributes to explaining the data.

     trajectories                                                    The best SWIRL model (S-1) recovered reward maps and

We also employed SWIRL on a dataset in which mice wan-               hidden-mode segments provide insights into the variability

dered an empty arena without explicit rewards (Markowitz             of dopamine impacts on animal spontaneous behavior: As

et al., 2023). In this experiment, mouse behaviors were              illustrated in Fig. 4A, the reward maps exhibit some similar-

recorded via depth camera video, and dopamine fluctuations           ities along with meaningful differences. For certain reward

in the dorsolateral striatum were monitored. The dataset             maps, there is a relatively high correlation (e.g., 0.40 and

includes behavior “syllables” inferred by MoSeq (Wiltschko           0.48) with dopamine fluctuations during the corresponding

et al., 2015), which indicate the type of behavior exhibited         modes. This suggests that dopamine fluctuations can reflect

by the mice during specific time periods (e.g., grooming,            a certain extent of reward during hidden modes 1 and 4.

sniffing, etc.). Consequently, trajectories consist of behav-        Furthermore, the plot of hidden mode segments across all

ioral syllables, with each time point representing a syllable.       trajectories (Fig. 4C) shows how each spontaneous behav-

We selected 159 trajectories, each comprising 300 time               ior trajectory is temporally segmented into distinct latent

points, by retaining only the 9 most frequent syllables and          modes, each governed by one of the five learned reward

merging consecutive identical syllables into a single time           functions (h1–h5). Early in the trajectories, we observe

point. This method, also used in previous reinforcement              a higher prevalence of h1, h2, and h4, while h3 and h5

learning studies on this dataset (Markowitz et al., 2023), en-       increasingly dominate toward the later stages. This tempo-

sures that each syllable has sufficient data for learning and        ral pattern aligns well with the findings from prior work

allows the model to concentrate on the transitions between           (Markowitz et al., 2023), which reported that mice exhibit

different syllables.                                                 greater activity at the beginning of spontaneous behavior

The MDP for this experiment comprises 9 states and 9 ac-             sequences and progressively slow down and disengage over

tions, where the state represents the current syllable and the       time. The reward maps provide mechanistic insight into

action signifies the next syllable. As mentioned in Sec. 3.5,        these transitions: h1 encourages selective transitions into

the ARHMM can be viewed as a variant of SWIRL that                   pause while still supporting other state transitions, represent-

learns the policy through behavior cloning. In other words,          ing a modulated rest phase; h2 discourages passivity, with

the policy for this MDP aligns with the emission probability         low reward for transitions into pause and strong suppression

of the ARHMM. This setup offers an excellent opportunity             of grooming; and h4 favors transitions into sniffing, reflect-





                                                                 8


===== PDF PAGE 9 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



                A                  h1, DA corr=0.40 h2, DA corr=0.04 h3, DA corr=0.18 h4, DA corr=0.48 h5, DA corr=0.27

                       pause

                        walk

                         rear





               state

                      groom



                           sniff

                          sniff

                            run



                                   pause

                                    walk





                                            groom



                                                     sniff



                                                      run

                                                             pause

                                                              walk





                                                                      groom



                                                                               sniff



                                                                                run

                                                                                       pause

                                                                                        walk





                                                                                                groom



                                                                                                         sniff



                                                                                                          run

                                                                                                                           pause

                                     rear









                                                                                         rear

                                                               rear









                                                                                                                            walk





                                                                                                                                    groom



                                                                                                                                             sniff



                                                                                                                                              run

                                                                                                                             rear









                                                                                                                                                     pause

                                                                                                                                                      walk

                                                                                                                                                       rear



                                                                                                                                                              groom



                                                                                                                                                                       sniff



                                                                                                                                                                        run

                                                                                                                                                                      sniff

                                                    sniff









                                                                              sniff









                                                                                                        sniff









                                                                                                                                            sniff

                                        action

                 B                                                                                      C

                                                                                                                                                                  hidden mode 1



                                                                                         I-1                                                                      hidden mode 2









                                                                                                            trajectories

                                                                                         I-2

                Test LL









                                                                                         S-1                                                                      hidden mode 3

                                                                                         S-2

                                                                                         ARHMM

                                                                                                                                                                  hidden mode 4

                                                                                         rARHMM

                                                                                                                                                                  hidden mode 5





                                                                                     MaxEnt: -2.206

                                    2           3            4                   5

                                            number of hidden modes                                                    0                time            300





Figure 4. Mouse spontaneous behavior experiment. (A) SWIRL (S-1) inferred reward maps for five hidden modes. h1 denotes hidden

mode 1, and so on. For better visualization, reward values are normalized to a range of (0, 1). DA corr represents the Pearson correlation

between the inferred reward map and the averaged dopamine fluctuation levels. (B) Held-out test LL for each model across different

number of hidden modes over 10 runs. The shaded area represents the total area that falls between one standard deviation above and

below the mean. (C) Inferred hidden-mode segments for all trajectories, with each row representing a trajectory.





ing exploratory drive. In contrast, h3 and h5 strongly reward                                       combined with its connection to traditional dynamics-based

transitions into pause and suppress departures from it, in-                                         behavior analysis methods in neuroscience, make SWIRL

dicating globally suppressive states that enforce behavioral                                        well-suited for behavioral neuroscience applications. Future

quiescence. The increasing expression of h3 and h5 over                                             extensions of SWIRL to partially observable Markov deci-

time reflects the mice’s natural progression from active to                                         sion processes (POMDPs) could further broaden its utility,

inactive states, supporting the interpretation that the learned                                     offering enhanced insight into complex and nuanced animal

rewards capture underlying behavioral structure consistent                                          behaviors.

with known temporal dynamics.

                                                                                                    Beyond its relevance to neuroscience study, SWIRL also

While the non-Markovian action-level history dependency                                             benefits the broader machine learning community. It of-

introduced by SWIRL does not demonstrate superior per-                                              fers a flexible framework with history-dependent switch-

formance in this particular experiment, the findings show-                                          ing reward functions that can be integrated with various

case SWIRL’s unique contribution to neuroscience research.                                          model-free IRL algorithms. For example, in Appendix C.1,

Specifically, SWIRL serves as a powerful tool for hypothesis                                        we highlight SWIRL’s potential to be integrated with IQ-

testing in behavioral datasets, enabling researchers to vali-                                       Learn, a state-of-the-art scalable model-free IRL method

date or challenge hypotheses regarding decision-level depen-                                        that has been employed in training large language models

dency as well as non-Markovian action-level dependency.                                             (Wulfmeier et al., 2024). Future development of SWIRL

This versatility further confirms SWIRL’s great potential in                                        that emphasizes scalability, such as incorporating RNNs or

advancing our understanding of complex behaviors.                                                   transformer-based policy model will be particularly valuable

                                                                                                    for areas such as robotics and large language models, where

5. Discussion                                                                                       adaptable IRL strategies are increasingly in demand.



We introduce SWIRL, a novel IRL framework designed

to capture history-dependent switching reward functions

in complex animal behaviors. Our framework can infer

interpretable switching reward functions from lengthy, non-

stereotyped behavioral tasks, achieving reasonable hidden-

mode segmentation—a feat that, to the best of our knowl-

edge, has not been accomplished previously. Those abilities,



                                                                                                9


===== PDF PAGE 10 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



Impact Statement                                                     Garg, D., Chakraborty, S., Cundy, C., Song, J., and Ermon,

                                                                       S. Iq-learn: Inverse soft-q learning for imitation. In

SWIRL has the potential to advance neuroscience research               Ranzato, M., Beygelzimer, A., Dauphin, Y., Liang, P., and

by helping uncover connections between complex animal                  Vaughan, J. W. (eds.), Advances in Neural Information

decision-making and corresponding brain activities. In a               Processing Systems, volume 34, pp. 4028–4039. Curran

broader context, SWIRL’s capacity to learn multiple history-           Associates, Inc., 2021.

dependent switching reward functions can also enable en-

hanced policy learning and explainability in fields such as          Haarnoja, T., Tang, H., Abbeel, P., and Levine, S. Rein-

robotics and large language models. However, as with all               forcement learning with deep energy-based policies. In

methods that analyze complex behaviors, careful considera-             International conference on machine learning, pp. 1352–

tion of data privacy, fairness, and responsible deployment is         1361. PMLR, 2017.

imperative to ensure ethical use.

                                                                     Haarnoja, T., Zhou, A., Abbeel, P., and Levine, S. Soft actor-

Acknowledgements                                                       critic: Off-policy maximum entropy deep reinforcement

                                                                       learning with a stochastic actor. In Dy, J. and Krause,

This work was supported by National Science Foundation                 A. (eds.), Proceedings of the 35th International Confer-

NSF2336055 (AW), a Career Award at the Scientific Inter-               ence on Machine Learning, volume 80 of Proceedings

face from the Burroughs Wellcome Fund (JEM), the David                 of Machine Learning Research, pp. 1861–1870. PMLR,

and Lucille Packard Foundation (JEM), and the Sloan Foun-             10–15 Jul 2018. URL https://proceedings.mlr.

dation (AW & JEM).                                                     press/v80/haarnoja18b.html.



References                                                           Hattori, R., Danskin, B., Babic, Z., Mlynaryk, N.,

                                                                       and Komiyama, T.        Area-specificity and plastic-

Abbeel, P. and Ng, A. Y. Apprenticeship learning via inverse           ity of history-dependent value coding during learn-

  reinforcement learning. In Proceedings of the Twenty-                ing.    Cell, 177(7):1858–1872.e15, 2019.        ISSN

 First International Conference on Machine Learning,                   0092-8674. doi: https://doi.org/10.1016/j.cell.2019.04.

  ICML ’04, pp. 1, New York, NY, USA, 2004. Asso-                      027. URL https://www.sciencedirect.com/

  ciation for Computing Machinery. ISBN 1581138385.                    science/article/pii/S0092867419304465.

  doi: 10.1145/1015330.1015430. URL https://doi.

  org/10.1145/1015330.1015430.                                       Hausknecht, M. and Stone, P. Deep recurrent q-learning for

                                                                       partially observable mdps. In AAAI 2015 Fall Symposium,

Ashwood, Z., Jha, A., and Pillow, J. W. Dynamic inverse                2015.

  reinforcement learning for characterizing animal behav-

  ior. In Oh, A. H., Agarwal, A., Belgrave, D., and Cho,             Hirakawa, T., Yamashita, T., Tamaki, T., Fujiyoshi, H.,

  K. (eds.), Advances in Neural Information Processing                 Umezu, Y., Takeuchi, I., Matsumoto, S., and Yoda, K.

  Systems, 2022a. URL https://openreview.net/                          Can ai predict animal movements? filling gaps in animal

  forum?id=nosngu5XwY9.                                                trajectories using inverse reinforcement learning. Eco-

                                                                       sphere, 9(10):e02447, 2018.

Ashwood, Z. C., Roy, N. A., Stone, I. R., Urai, A. E.,

  Churchland, A. K., Pouget, A., Pillow, J. W., and Lab-             Houthooft, R., Chen, X., Duan, Y., Schulman, J., De Turck,

  oratory, T. I. B. Mice alternate between discrete strate-            F., and Abbeel, P. Vime: Variational information max-

  gies during perceptual decision-making. Nature Neuro-                imizing exploration. Advances in neural information

  science, 25(2):201–212, Feb 2022b. ISSN 1546-1726.                   processing systems, 29, 2016.

  doi: 10.1038/s41593-021-01007-z. URL https://

  doi.org/10.1038/s41593-021-01007-z.                                Kennedy, A.      The what, how, and why of natu-

                                                                       ralistic behavior.       Current Opinion in Neuro-

Babes-Vroman, M., Marivate, V., Subramanian, K.,                       biology, 74:102549, 2022.            ISSN 0959-4388.

  and Littman, M. L. Apprenticeship learning about                     doi:       https://doi.org/10.1016/j.conb.2022.102549.

  multiple intentions. In International Conference on                  URL        https://www.sciencedirect.com/

  Machine Learning, 2011.       URL https://api.                       science/article/pii/S0959438822000435.

  semanticscholar.org/CorpusID:9737656.

                                                                     Linderman, S. W., Miller, A. C., Adams, R. P., Blei, D. M.,

Bakker, B. Reinforcement learning with lstm in non-                    Paninski, L., and Johnson, M. J. Recurrent switching lin-

  markovian tasks with longterm dependencies. Memory,                  ear dynamical systems. arXiv preprint arXiv:1610.08466,

  pp. 1–18, 2001.                                                      2016.



                                                                10


===== PDF PAGE 11 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



Markowitz, J. E., Gillis, W. F., Jay, M., Wood, J., Harris,          Weinreb, C., Pearl, J. E., Lin, S., Osman, M. A. M.,

 R. W., Cieszkowski, R., Scott, R., Brann, D., Koveal, D.,            Zhang, L., Annapragada, S., Conlin, E., Hoffmann, R.,

 Kula, T., Weinreb, C., Osman, M. A. M., Pinto, S. R.,                Makowska, S., Gillis, W. F., et al. Keypoint-moseq: pars-

 Uchida, N., Linderman, S. W., Sabatini, B. L., and Datta,            ing behavior by linking point tracking to pose dynamics.

 S. R. Spontaneous behaviour is structured by reinforce-              Nature Methods, 21(7):1329–1339, 2024.

 ment without explicit reward. Nature, 614(7946):108–

 117, January 2023.                                                  Wiltschko, A. B., Johnson, M. J., Iurilli, G., Peterson, R. E.,

                                                                      Katon, J. M., Pashkovski, S. L., Abraira, V. E., Adams,

Mazzucato, L. Neural mechanisms underlying the temporal               R. P., and Datta, S. R. Mapping sub-second structure in

 organization of naturalistic animal behavior. Elife, 11:             mouse behavior. Neuron, 88(6):1121–1135, 2015.

 e76577, 2022.

                                                                     Wu, F., Ke, J., and Wu, A. Inverse reinforcement learning

Ng, A. Y. and Russell, S. J. Algorithms for inverse rein-             with the average reward criterion. Advances in Neural

  forcement learning. In Proceedings of the Seventeenth               Information Processing Systems, 36, 2024.

 International Conference on Machine Learning, ICML

 ’00, pp. 663–670, San Francisco, CA, USA, 2000. Mor-                Wulfmeier, M., Bloesch, M., Vieillard, N., Ahuja, A., Born-

  gan Kaufmann Publishers Inc. ISBN 1558607072.                       schein, J., Huang, S., Sokolov, A., Barnes, M., Desjardins,

                                                                      G., Bewley, A., Bechtle, S. M. E., Springenberg, J. T.,

Nguyen, Q. P., Low, K. H., and Jaillet, P. Inverse reinforce-         Momchev, N., Bachem, O., Geist, M., and Riedmiller,

  ment learning with locally consistent reward functions.             M. Imitating language via scalable inverse reinforcement

  In Neural Information Processing Systems, 2015.                     learning. In The Thirty-eighth Annual Conference on Neu-

Parisotto, E. and Salakhutdinov, R. Neural map: Structured            ral Information Processing Systems, 2024. URL https:

  memory for deep reinforcement learning. arXiv preprint              //openreview.net/forum?id=5d2eScRiRC.

  arXiv:1702.08360, 2017.                                            Yamaguchi, S., Naoki, H., Ikeda, M., Tsukada, Y., Nakano,

Pinsler, R., Maag, M., Arenz, O., and Neumann, G. Inverse              S., Mori, I., and Ishii, S. Identification of animal behav-

  reinforcement learning of bird flocking behavior. In ICRA            ioral strategies by inverse reinforcement learning. PLoS

  Swarms Workshop, 2018.                                               computational biology, 14(5):e1006122, 2018.



Rosenberg, M., Zhang, T., Perona, P., and Meister, M. Mice           Zeng, S., Li, C., Garcia, A., and Hong, M. Maximum-

  in a labyrinth show rapid learning, sudden insight, and              likelihood inverse reinforcement learning with finite-time

  efficient exploration. eLife, 10:e66175, jul 2021. ISSN              guarantees. In Koyejo, S., Mohamed, S., Agarwal, A.,

  2050-084X. doi: 10.7554/eLife.66175. URL https:                      Belgrave, D., Cho, K., and Oh, A. (eds.), Advances in

  //doi.org/10.7554/eLife.66175.                                       Neural Information Processing Systems, volume 35, pp.

                                                                       10122–10135. Curran Associates, Inc., 2022.

Sezener, C. E., Uchibe, E., and Doya, K. Obtaining reward

  functions of rats using inverse reinforcement learning. In         Zhu, H., Crompe, B. D. L., Kalweit, G., Schneider, A.,

  Türkiye Autonomous Robots Conference, 2014.                         Kalweit, M., Diester, I., and Boedecker, J. Multi-

                                                                       intention inverse q-learning for interpretable behavior

Sharafeldin, A., Imam, N., and Choi, H. Active sensing with            representation. Transactions on Machine Learning Re-

  predictive coding and uncertainty minimization. Patterns,            search, 2024. ISSN 2835-8856. URL https://

  5(6), Jun 2024. ISSN 2666-3899. doi: 10.1016/j.patter.               openreview.net/forum?id=hrKHkmLUFk.

  2024.100983. URL https://doi.org/10.1016/

  j.patter.2024.100983.                                              Ziebart, B. D., Maas, A., Bagnell, J. A., and Dey, A. K.

                                                                       Maximum entropy inverse reinforcement learning. In

Stone, I. R. Latent Variable Models for Characterizing the

                                                                       Proceedings of the 23rd National Conference on Artificial

  Dynamic Structure Underlying Complex Behaviors. PhD

                                                                       Intelligence - Volume 3, AAAI’08, pp. 1433–1438. AAAI

  thesis, Princeton University, 2023.

                                                                       Press, 2008. ISBN 9781577353683.

Surana, A. and Srivastava, K. Bayesian nonparametric

                                                                     Ziebart, B. D., Bagnell, J. A., and Dey, A. K. Modeling in-

  inverse reinforcement learning for switched markov de-

                                                                       teraction via the principle of maximum causal entropy. In

  cision processes. In 2014 13th International Conference

                                                                       Proceedings of the 27th International Conference on In-

  on Machine Learning and Applications, pp. 47–54. IEEE,

                                                                       ternational Conference on Machine Learning, ICML’10,

  2014.

                                                                       pp. 1255–1262, Madison, WI, USA, 2010. Omnipress.

Sutton, R. S. Dyna, an integrated architecture for learning,           ISBN 9781605589077.

  planning, and reacting. ACM Sigart Bulletin, 2(4):160–

  163, 1991.



                                                                11


===== PDF PAGE 12 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



A. Appendix A

A.1. The SWIRL algorithm

Following the EM update scheme, we derive the auxiliary function for the n-th trajectory during the E-step, where

n = 1, 2, . . . , N :





                                                    X                                       n −1

                                                                                           TX

                  Gn (θ, θ̂) = log p(sn,1 ) +            p(zn,1 |ξn , θ̂) log p(zn,1 ) +           log P(sn,t+1 |sn,t , an,t )   (5)

                                                     z                                     t=1

                      Tn X

                      X

                  +              p(zn,t |ξn , θ̂) log πzn,t (an,t |sL

                                                                    n,t ; rz )                                                   (6)

                      t=1 zn,t

                       n −1

                      TX         X

                  +                       p(zn,t , zn,t+1 |ξn , θ̂) log Pz (zn,t+1 |zn,t , sn,t ).                               (7)

                      t=1 zn,t ,zn,t+1









Here are some remarks: (I) We incorporate state dependency into the hidden mode transition Pz , such that zt+1 depends

not only on the previous hidden mode zt but also on the current state st . This modification results in longer segments

of hidden modes with reduced fast-switching phenomena. (II) We can perform MaxEnt IRL based on the policy term

πzn,t (an,t |sL

              n,t ; rz ) in Eq. 6, as discussed in Sec. 3.4. (III) If we have estimated the current policy πzn based on the

current reward estimate rz , we can apply any inference method to estimate the posterior probabilities p(zn,t |ξn , θ̂) and

p(zn,t , zn,t+1 |ξn , θ̂). In this work, we use the standard forward-backward message-passing algorithm. (IV) It is important

to note that P(sn,t+1 |sn,t , an,t ) represents the environment transition and is not involved in the optimization process.

In the M-step, to maximize the auxiliary function G, we update all parameters in θ by performing gradient descent on G.

The inference procedure alternates between the E-step and M-step until convergence or a predetermined number of iterations.

The algorithm is summarized in Algorithm 1.





Algorithm 1 The SWIRL Algorithm

Data: Expert demonstrations D = {ξ1 , ξ2 , . . . , ξN }

Result: Posterior probabilities of hidden modes z, rewards rz for each mode, and other parameters in θ

Initialize parameters θ0

for k = 1, 2, . . . , K do

     E-step

                                                                                                    ∗

         For each hidden mode z and corresponding reward rzk , infer the optimal soft Q-function Qkz using a RL method.

          Compute the policy with the Boltzmann distribution:

                                                                                   ∗

                                                                          exp{Qkz (s, a)/α}

                                                      πz (a|s) = P                 k∗     ′

                                                                        a′ ∈A exp{Qz (s, a )/α}



       to obtain πzk (a|sL ; rzk ), ∀s ∈ S. α is a predefined temperature parameter.

      For each trajectory ξn , use forward-backward message passing to calculate p(zn,t |ξn , θk ) and p(zn,t , zn,t+1 |ξn , θk ).

      Use the posteriors, πzk (a|sL ; rzk ), and θk to compute the auxiliary function G (Eqs. 5-7).

   end

   M-step

      Update parameters θ using gradient descent on the auxiliary function G with learning rate ηk :



                                                            θk+1 ← θk − ηk ∇θ G(θ, θk ).



   end

end





                                                                       12


===== PDF PAGE 13 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



A.2. Detailed derivation of SWIRL objectives by EM algorithm

Here we need to learn θ ≜ (rz , Pz , p(s1 ), p(z1 )). Note that the total probability for a sequence {(st , at , zt )}t=1:T is

                                                                         T

                                                                         Y

            log p(z, s, a) = log p(z1 )p(s1 )πz1 (a1 |s1 ; rz )                P(st |st−1 , at−1 )Pz (zt |zt−1 , st−1 )πzt (at |sL

                                                                                                                                 t ; rz ).

                                                                         t=2



The expectation across all possible sequences is given by



                                                         N

                                                         X                        N

                                                                                  X

                            E[log p(z, s, a)] =                log p(sn,1 ) +           p(zn,1 |s1 , a1 ) log p(zn,1 )

                                                         n=1                      n=1

                                                         N X

                                                         X T

                                                     +             log P(sn,t |sn,t−1 , an,t−1 )

                                                         n=1 t=2

                                                           T

                                                         N X

                                                         X

                                                     +             p(zn,t , zn,t−1 |ξn ) log Pz (zn,t |zn,t−1 , sn,t−1 )

                                                         n=1 t=2

                                                           T

                                                         N X

                                                         X

                                                     +             p(zn,t |ξn ) log πzn,t (an,t |sL

                                                                                                  n,t ; rz ).

                                                         n=1 t=1

Now we use Expectation-Maximization to find θ. E step:

                X

     G(θ, θ̂) =    p(z|ξ1:N , θ̂) log p(z, ξ1:N , |θ̂)

                     z

                            N

                                                          !

                    X       Y

                =                  p(zn,1:T |ξn , θ̂n )

                     z      n=1

                      N                                              Tn                                       Tn−1

                      X                                               X                                         X

                              log p(sn,1 ) + log p(zn,1 ) +                 (log πzn,t (an,t |sL

                                                                                               n,t ; rz )) +          (log P(sn,t+1 |sn,t , an,t )

                      n=1                                             t=1                                       t=1

                                                             

                             + log Pz (zn,t+1 |zn,t , sn,t ))

                    N

                    X

                =         log p(sn,1 )

                    n=1

                    N X

                    X

                +             p(zn,1 = z|ξn , θ̂) log p(zn,1 )

                    n=1 z

                      Tn X

                    N X

                    X

                +                      p(zn,t = z|ξn , θ̂) log πzn,t (an,t |sL

                                                                             n,t ; rz )

                    n=1 t=1    z

                       n −1 X X

                    N TX

                    X

                +                             p(zn,t = z, zn,t+1 = z ′ |ξn , θ̂) log Pz (zn,t+1 |zn,t , sn,t )

                    n=1 t=1        z     z′

                       n −1

                    N TX

                    X

                +              log P(sn,t+1 |sn,t , an,t ).

                    n=1 t=1





M step:



                                                              θk+1 = arg max G(θ, θk ).

                                                                                θ



For notational simplicity, we only consider a specific trajectory n. To compute G(θ, θk ), we need to estimate

                                                                   p(zt |s1:T , a1:T , θ̂)



                                                                             13


===== PDF PAGE 14 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



and

                                                     p(zt = z, zt+1 = z ′ |s1:T , a1:T , θ̂).

Thus we can use message passing algorithm, where we define the forward-backward variables α and β. Forward variables

αt,z , for t = 1, . . . , T :



             α1,z = p(z1 = z|θ̂),

             αt,z = p(s1:t , a1:t , zt = z|θ̂)

                    X

                  =     p(s1:t−1 , a1:t−1 , zt−1 = z ′ |θ̂)Pz (zt = z|st−1 , zt−1 = z ′ )p(st |st−1 , at−1 )πzt (at |sL

                                                                                                                      t ; rz )

                        z′

                        X

                    =        αt−1,z′ Pz (zt = z|st−1 , zt−1 = z ′ )p(st |st−1 , at−1 )πzt (at |sL

                                                                                                t ; rz ).

                        z′





Backward variables βt,z , for t = 1, . . . , T :



                             βT,z = 1,

                              βt,z = p(st+1:T , at+1:T |st , at , zt = z, θ̂)

                                     X

                                                                                                ′

                                   =     βt+1,z′ p(st+1 |st , at )πz′ (at |sL

                                                                            t ; rz )Pz (zt+1 = z |zt = z, st+1 ),

                                       z′



                              β1,z = p(s1:T , a1:T |z1 = z, θ̂)

                                     X

                                                                                 ′

                                   =     β1,z′ p(s1 )πz′ (a1 |sL

                                                               1 ; rz )Pz (z1 = z |z0 = z, s1 ).

                                       z′





Therefore,

                                  p(zt = z|ξ, θ̂)

                                   = p(zt = z, ξ|θ̂)/p(ξ|θ̂)

                                   = p(s1:t , a1:t , zt = z|θ̂)p(st+1:T , at+1:T |st , at , zt = z, θ̂)/p(ξ|θ̂)

                                   = αt,z βt,z /p(ξ|θ̂).

Furthermore,



             p(zt−1 , st−1 , zt |ξ, θ̂) = p(zt−1 , st−1 , zt , ξ|θ̂)/p(ξ|θ̂)

               = p(s1:t−1 , a1:t−1 , zt−1 )p(zt |zt−1 , st−1 )p(st , at |st−1 , at−1 , zt )p(st+1:T , at+1:T |zt , st , at )/p(ξ|θ̂)

                   p(s1:t−1 , a1:t−1 , zt−1 )p(zt |zt−1 , st−1 )p(st |st−1 , at−1 )p(at |st , zt )p(st+1:T , at+1:T |zt , st , at )

               =

                                                                    p(ξ|θ̂)

                   αt−1,zt−1 Pz (zt |zt−1 , st−1 )Pz (st |st−1 , at−1 )πzt (at |sL

                                                                                 t ; rz )βt,zt

               =                                                                                  .

                                                     p(ξ|θ̂)



And finally,                                                     X             X

                                                     p(ξ|θ̂) =        αT,z =        α1,z β1,z .

                                                                  z             z









                                                                        14


===== PDF PAGE 15 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



B. Appendix B

B.1. Implementation details

We developed our SWIRL framework in JAX, leveraging its automatic differentiation and parallelization features to

efficiently handle the computational demands of our algorithm. During each M-step update, we performed gradient descent

to optimize the model parameters. We employed the adam optimizer from Optax (5x5 Gridworld & Spontaneous Behavior)

or the BFGS optimizer from jax.scipy (Labyrinth) for learning the reward function rz , using a learning rate of 5 × 10−3

and momentum coefficients of (0.9, 0.999) (adam) or a tolerance of 1 × 10−4 (BFGS). We backpropagated the gradient for

the reward function from the policy term in loss function through 100 Soft-Q iterations. For optimizing the hidden mode

transition Pz (zt+1 | zt , st ), we used the LBFGS optimizer from JAXopt with the tolerance set to 1 × 10−4 .



B.2. Empirical runtime

Our SWIRL implementation leverages the advantages of JAX, including just-in-time (JIT) compilation and vectorization, to

achieve high computational efficiency. For S-2 experiments across all three datasets (gridworld, labyrinth, and spontaneous

behavior), SWIRL converges within 15–30 minutes on a V100 GPU, which takes 50–100 EM iterations. For longer L, a S-4

experiment on labyrinth with 50 EM iterations take 2-3 hours to finish on a L40S GPU.



B.3. Evaluation metrics

                                                                                                   P

The test log-likelihood is computed from the forward variable α, where log p(s1:T , a1:T ) = log z αT,z . Detail of the

forward variable α computation is described in Appendix A.2. For test hidden mode segmentation accuracy, we use

the Viterbi algorithm to predict the hidden mode of each timepoint and compute the percentage of correct hidden mode

prediction compared to ground truth data. For reward correlation, we compute the Pearson correlation between learnt reward

and ground truth reward or dopamine fluctuation levels.



B.4. Environment setup

5x5 Gridworld: State space: Discrete(25); Action space: Discrete(5). The 5 actions are ‘up’, ‘left’, ‘down’, ‘right’, ‘stay’.

Labyrinth: State space: Discrete(127); Action space: Discrete(4). The labyrinth has a binary-tree structure and the 4

actions are ‘move in left’, ‘move in right’, ‘move out left’, ‘move out right’.

Spontaneous Behavior: State space: Discrete(9); Action space: Discrete(9). Each state is a MoSeq syllable that defines a

behavior motif. Each action represents a next state that the agent transfers into.



B.5. Discussion on discount factor γ and temperature α

We set the discount factor γ = 0.95, a standard choice in RL and IRL literature. For the mouse spontaneous behavior

dataset, we also tested a smaller γ = 0.7, as previous literature Markowitz et al. (2023) suggested this value as optimal

for the dataset. However, we observed that the results learned by SWIRL were highly similar for both discount factors,

indicating that the choice of γ had minimal impact on performance in this case.

We searched for the optimal temperature α in {0.01, 0.1, 0.5, 1}. For the labyrinth dataset, smaller values of α led to better

results for certain hidden modes. This observation aligns with the deterministic nature of behaviors in the labyrinth’s

tree-like structure. On the contrary, for the spontaneous behavior dataset, where animals exhibit more stochastic behavior

patterns, we found higher values of α were more appropriate.



B.6. Discussion on the number of hidden modes Z and history length L

In this section, we discuss the selection and impact of the number of hidden modes Z = |Z| and action-level history length

L.



B.6.1. Z IN LABYRINTH EXPERIMENT

We evaluated the test LL of SWIRL models on Z from 2 to 5 and found that the best model (S-2) plateaus beyond Z = 4

(Fig. 5A). However, Z = 4 result does not differ much from the Z = 3 result: Z = 4 result mainly segments the explore





                                                             15


===== PDF PAGE 16 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



              A                                              B

                                                                                           3 hidden modes

                                                                                                      time

                                                                   water         home       explore          water port visit     home visit

               Test LL



                                                                                           4 hidden modes

                                                                                                   time

                         2          3            4       5       water         home     explore1     explore2        water port visit   home visit

                                number of hidden modes

              C              water            1

                                                         home              1

                                                                                        explore1                 1

                                                                                                                           explore2             1









                                              0                            0                                     0                               0







Figure 5. Water-restricted labyrinth experiment with different number of hidden modes Z. (A) Held-out test LL for each model

across different number of hidden modes over 10 runs. The shaded area represents the total area that falls between one standard deviation

above and below the mean. (B) Segments of a trajectory from held-out test data, predicted by SWIRL (S-2) with Z = 3 and Z = 4. The

orange dot indicates when the mouse visits the water port, while the red cross denotes the mouse’s visit to state 0 (home) at that time. (C)

Inferred reward maps from SWIRL (S-2) with Z = 4: water, home, and two explore maps. To enhance visualization, the inferred reward

r(st , st−1 ) was averaged over st−1 to produce r(st ).







mode of Z = 3 into two explore modes with similar reward maps (Fig. 5BC). As a result, we still present Z = 3 as the

primary result for simplicity.



B.6.2. L IN LABYRINTH EXPERIMENT

With Z = 3, we evaluated the test LL of SWIRL models on L from 1 to 4 and found that the L = 4 (S-4) provides

the best test LL (Fig. 6A). L = 3 and L = 4 provide similar hidden segments and reward maps (when averaged over

(st−1 , ...st−L+1 ) to produce r(st )) as L = 2 (Fig. 6BC). In the main paper, we present L = 2 (S-2) as the primary result as

it has effectively demonstrated the benefits of incorporating non-Markovian action-level history dependency into SWIRL.

However, we note that the test LL results in Fig. 6A suggest the presence of longer action-level history dependency (L > 2)

in this labyrinth dataset. This observation aligns with the partially observable nature of this 127-node labyrinth: The mouse

may not know the whole environment, so it likely relies on a longer history of prior states to guide its decision-making.



B.6.3. Z AND L IN MOUSE SPONTANEOUS BEHAVIOR EXPERIMENT

In the mouse spontaneous behavior experiment, we find that L = 1 (S-1) is the optimal choice, as L = 1 (S-1) consistently

provides higher test log-likelihood (LL) compared to L = 2 (S-2) (Fig. 4B). Additionally, we select Z = 5 for the number

of hidden modes since the test LL plateaus at Z = 5 (Fig. 4B).



B.7. Robustness of SWIRL

To assess the robustness of SWIRL, we evaluated the performance of SWIRL (S-2) under increasing levels of random

perturbations in the simulated gridworld dataset.

Specifically, we introduced random permutations to a percentage of the states and actions in the training data, ranging from

0% to 50%. As expected, performance decreased as the level of permutation increased (Fig. 7). The model maintained high

accuracy with less than 10% permutation. Between 10% and 30%, SWIRL demonstrated stable performance, achieving

reasonable reward correlations and hidden mode segmentation accuracy despite the noise. Permutation beyond 30% led to

very noisy data and it became hard for the model to maintain high performance.

These results suggest that SWIRL can tolerate moderate levels of noise or incomplete data, making it suitable for real-world



                                                                         16


===== PDF PAGE 17 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



                 A                                                     B                             S-1



                                                                                                     S-2

             Test LL



                                                                                                     S-3



                                                                                                     S-4

                                                                                                     time

                                 S-1    S-2        S-3   S-4               water        home   explore    water port visit                 home visit



                             C            water                    1

                                                                              home                                           explore         1

                                                                                                 1









                                                                   0                             0                                           0







Figure 6. Water-restricted labyrinth experiment with different action-level history length L. (A) Boxplot showing held-out test

LL over 10 runs, with the x-axis representing the four different models from L = 1 to L = 4. Outlier selection method is described in

Appendix B.8. (B) Segments of a trajectory from held-out test data, predicted by the four SWIRL models. The orange dot indicates when

the mouse visits the water port, while the red cross denotes the mouse’s visit to state 0 (home) at that time. (C) Inferred reward maps

from SWIRL (S-4): water, home, and explore. To enhance visualization, the inferred reward r(st , st−1 , st−2 , st−3 ) was averaged over

(st−1 , st−2 , st−3 ) to produce r(st ).





animal behavior datasets where such challenges are common.

                                                                                                     Test segment accuracy

             R correlation









                                                         Test LL









                                   permutation %                              permutation %                                      permutation %





Figure 7. SWIRL (S-2) experiment on 5 × 5 gridworld dataset with ten random permutations. Box plots illustrating the Pearson

correlation between the true and recovered reward maps, test log-likelihood, and test segmentation accuracy. The x-axis represents the

percentage of states and actions permuted in the training data. Outlier selection method is described in Appendix B.8.





B.8. Outlier selection in box plot

All box plots in this paper are drawn by seaborn.boxplot() with its default outlier selection method. Specifically, the

upper quartile (Q3), lower quartile (Q1), and interquartile range (IQR) are calculated. Values greater than Q3+1.5IQR or

less than Q1-1.5IQR are considered as outliers.









                                                                                   17


===== PDF PAGE 18 =====
   Inverse Reinforcement Learning with Switching Rewards and History Dependency for Characterizing Animal Behaviors



C. Appendix C

C.1. Model-free SWIRL on a simulated gridworld environment



                                    true                       discovered

             home reward







                                                                                                 r        st          s t-1

                                                                                                      current         right



                                                                                                      current       above

                                    true                       discovered                             current          left



                                                                                                      current       below

             water reward









                                                                                                      current current









Figure 8. True and discovered reward maps in model-free SWIRL (S-2) simulation experiment. The color scale represents reward

values ranging from 0 to 1. The home reward is defined as r(st ), while the water reward depends on both the current and previous

locations, r(st , st−1 ). To present the water reward, each location is divided into five groups, as detailed in the table on the far right. For

example, the polygon in the first row represents the reward value when st is the current location and st−1 is the location to the right.

Light grey indicates an impossible transition where no reward exists.



To demonstrate that SWIRL also supports model-free IRL, we replaced the model-based soft-Q iteration IRL approach

used in main experiments with a model-free IRL method IQ-Learn (Garg et al., 2021). Garg et al. (2021) shows that we can

convert the MaxEnt IRL objective L(π, r) with a convex reward regularizer to an offline inverse Q-learning objective:



                             max J (Q) = E(s,a,s′ )∼ξ [ϕ(Q(s, a) − γV (s′ ))] − E(s,a,s′ )∼ξ [V (s) − γV (s′ )],

                                Q





with V (s) = log a exp Q(s, a). ϕ is the concave function from a convex conjugate. When using χ2 -divergence,

                   P

              2

ϕ(x) = x − x4 . The reward can be obtained as r(s, a) = Q(s, a) − γEs′ ∼P(·|s,a) [log a′ exp Q (s′ , a′ )]. By marginalizing

                                                                                     P

over actions, one can similarly obtain a state-only reward r(s).

Since optimizing the reward by maximizing log π corresponds to the Lagrangian dual of the standard MaxEnt IRL approach

(Zeng et al., 2022), we can maximize the IQ-Learn objective J(Q) instead of the log π term in SWIRL EM auxiliary

function (Eq. 3). Therefore, for a trajectory ξ, SWIRL can perform IRL with the following objective:

                                  T X

                                  X

                                           p(zt |ξ, θ̂) [ϕ(Qzt (sL                 L                L            L

                                                                                                                       

                            max                                  t , at ) − γVzt (st+1 ))] − [Vzt (st ) − γVzt (st+1 )] ,

                            Q

                                  t=1 zt





with Vzt (sL ) = log                        L

                            P

                                a exp Qzt (s , a).



We tested this IQ-Learn-based, model-free SWIRL (S-2) on simulated trajectories in the same 5x5 gridworld environment as

Sec. 4.1. The recovered reward maps achieved a Pearson correlation of 0.737 relative to the true reward maps. Although the

model-free SWIRL recovered reward maps (Fig. 8) appear noisier than those from the model-based approach in Sec. 4.1

(Fig. 2A), they still accurately capture the critical high-reward regions.





                                                                         18

