create custom reinforcement learning agents
to implement your own custom reinforcement learning algorithms, you can create a custom agent by creating a subclass of a custom agent class. you can then train and simulate this agent in matlab® and simulink® environments. for more information about creating classes in matlab, see .
create template class
to define your custom agent, first create a class that is a subclass of the
rl.agent.customagent
class. as an example, this topic describes the
custom lqr agent trained in . as a starting point for your
own agent, you can open and modify this custom agent class. to download the example files in
a local folder and open the main example live script, at the matlab command line, type the following code.
openexample('rl/traincustomlqragentexample')
close the traincustomlqragentexample.mlx
file and open the
lqrcustomagent.m
class file.
edit lqrcustomagent.m
after saving the class to your own working folder, you can remove the example files and the local folder in which they were downloaded.
the class defined in lqrcustomagent.m
has the following class
definition, which indicates the agent class name and the associated abstract agent.
classdef lqrcustomagent < rl.agent.customagent
to define your agent, you must specify the following:
agent properties
constructor function
a critic that estimates the discounted long-term reward (if required for learning)
an actor that selects an action based on the current observation (if required for learning)
required agent methods
optional agent methods
agent properties
in the properties
section of the class file, specify any parameters
necessary for creating and training the agent. these parameters can include:
discount factor for discounting future rewards
configuration parameters for exploration models, such as noise models or epsilon-greedy exploration
experience buffers for using replay memory
mini-batch sizes for sampling from the experience buffer
number of steps to look ahead during training
for more information on potential agent properties, see the option objects for the built-in reinforcement learning toolbox™ agents.
the rl.agent.customagent
class already includes properties for the
agent sample time (sampletime
) and the action and observation
specifications (actioninfo
and observationinfo
,
respectively).
the custom lqr agent defines the following agent properties.
properties % q q % r r % feedback gain k % discount factor gamma = 0.95 % critic critic % buffer for k kbuffer % number of updates for k kupdate = 1 % number for estimator update estimatenum = 10 end properties (access = private) counter = 1 ybuffer hbuffer end
constructor function
to create your custom agent, you must define a constructor function that:
defines the action and observation specifications. for more information about creating these specifications, see
rlnumericspec
andrlfinitesetspec
.creates actor and critic as required by your training algorithm. for more information, see .
configures agent properties.
calls the constructor of the base abstract class.
for example, the lqrcustomagent
constructor defines continuous action
and observation spaces and creates a critic. the createcritic
function is
an optional helper function that defines the critic.
function obj = lqrcustomagent(q,r,initialk) % check the number of input arguments narginchk(3,3); % call the abstract class constructor obj = obj@rl.agent.customagent(); % set the q and r matrices obj.q = q; obj.r = r; % define the observation and action spaces obj.observationinfo = rlnumericspec([size(q,1),1]); obj.actioninfo = rlnumericspec([size(r,1),1]); % create the critic obj.critic = createcritic(obj); % initialize the gain matrix obj.k = initialk; % initialize the experience buffers obj.ybuffer = zeros(obj.estimatenum,1); num = size(q,1) size(r,1); obj.hbuffer = zeros(obj.estimatenum,0.5*num*(num 1)); obj.kbuffer = cell(1,1000); obj.kbuffer{1} = obj.k; end
actor and critic
if your learning algorithm uses a critic to estimate the long-term reward, an actor for selecting an action, or both, you must add these as agent properties. you must then create these objects when you create your agent; that is, in the constructor function. for more information on creating actors and critics, see .
for example, the custom lqr agent uses a critic, stored in its critic
property, and no actor. the critic creation is implemented in the
createcritic
helper function, which is called from the
lqrcustomagent
constructor.
function critic = createcritic(obj) nq = size(obj.q,1); nr = size(obj.r,1); n = nq nr; w0 = 0.1*ones(0.5*(n 1)*n,1); critic = rlqvaluefunction({@(x,u) computequadraticbasis(x,u,n),w0},... getobservationinfo(obj),getactioninfo(obj)); critic.options.gradientthreshold = 1; end
in this case, the critic is an rlqvaluefunction
object. to create this object, you must specify the handle to a custom basis function, in
this case the computequadraticbasis
function. for more information, see
.
required functions
to create a custom reinforcement learning agent you must define the following
implementation functions. to call these functions in your own code, use the wrapper methods
from the abstract base class. for example, to call getactionimpl
, use
getaction
. the wrapper methods have the same input and output arguments
as the implementation methods.
function | description |
---|---|
getactionimpl | selects an action by evaluating the agent policy for a given observation |
getactionwithexplorationimpl | selects an action using the exploration model of the agent |
learnimpl | learns from the current experiences and returns an action with exploration |
within your implementation functions, to evaluate your actor and critic, you can use the , , and functions.
to evaluate an critic, you need only the observation input, and you can obtain the value of the current observation
v
using the following syntax.v = getvalue(critic,observation);
to evaluate an
rlqvaluefunction
critic you need both observation and action inputs, and you can obtain the value of the current state-actionq
using the following syntax.q = getvalue(critic,[observation,action]);
to evaluate an critic you need only the observation input, and you can obtain the value of the current observation
q
for all possible discrete actions using the following syntax.q = getvalue(critic,observation);
for a discrete action space
rlqvaluefunction
critic, obtain the maximum q state-action value functionq
for all possible discrete actions using the following syntax.[maxq,maxactionindex] = getmaxqvalue(critic,observation);
to evaluate an actor, obtain the action
a
using the following syntax.a = getaction(actor,observation);
for each of these cases, if your actor or critic network uses a recurrent neural network, the functions can also return the current values of the network state after obtaining the corresponding network output.
getactionimpl
function
the getactionimpl
function evaluates the policy of your agent and
selects an action. this function must have the following signature, where
obj
is the agent object, observation
is the
current observation, and action
is the selected action.
function action = getactionimpl(obj,observation)
for the custom lqr agent, you select an action by applying the u=-kx control law.
function action = getactionimpl(obj,observation) % given the current state of the system, return an action action = -obj.k*observation{:}; end
getactionwithexplorationimpl
function
the getactionwithexplorationimpl
function selects an action using
the exploration model of your agent. using this function you can implement algorithms such
as epsilon-greedy exploration. this function must have the following signature, where
obj
is the agent object, observation
is the
current observation, and action
is the selected action.
function action = getactionwithexplorationimpl(obj,observation)
for the custom lqr agent, the getactionwithexplorationimpl
function
adds random white noise to an action selected using the current agent policy.
function action = getactionwithexplorationimpl(obj,observation) % given the current observation, select an action action = getaction(obj,observation); % add random noise to the action num = size(obj.r,1); action = action 0.1*randn(num,1); end
learnimpl
function
the learnimpl
function defines how the agent learns from the
current experience. this function implements the custom learning algorithm of your agent
by updating the policy parameters and selecting an action with exploration. this function
must have the following signature, where obj
is the agent object,
exp
is the current agent experience, and action
is
the selected action.
function action = learnimpl(obj,exp)
the agent experience is the cell array exp =
{state,action,reward,nextstate,isdone}
.
state
is the current observation.action
is the current action.reward
is the current reward.nextstate
is the next observation.isdone
is a logical flag indicating that the training episode is complete.
for the custom lqr agent, the critic parameters are updated every n
steps.
function action = learnimpl(obj,exp) % parse the experience input x = exp{1}{1}; u = exp{2}{1}; dx = exp{4}{1}; y = (x'*obj.q*x u'*obj.r*u); num = size(obj.q,1) size(obj.r,1); % wait n steps before updating the critic parameters n = obj.estimatenum; h1 = computequadraticbasis(x,u,num); h2 = computequadraticbasis(dx,-obj.k*dx,num); h = h1 - obj.gamma* h2; if obj.counter<=n obj.ybuffer(obj.counter) = y; obj.hbuffer(obj.counter,:) = h; obj.counter = obj.counter 1; else % update the critic parameters based on the batch of % experiences h_buf = obj.hbuffer; y_buf = obj.ybuffer; theta = (h_buf'*h_buf)\h_buf'*y_buf; obj.critic = setlearnableparameters(obj.critic,{theta}); % derive a new gain matrix based on the new critic parameters obj.k = getnewk(obj); % reset the experience buffers obj.counter = 1; obj.ybuffer = zeros(n,1); obj.hbuffer = zeros(n,0.5*num*(num 1)); obj.kupdate = obj.kupdate 1; obj.kbuffer{obj.kupdate} = obj.k; end % find and return an action with exploration action = getactionwithexploration(obj,exp{4}); end
optional functions
optionally, you can define how your agent is reset at the start of training by
specifying a resetimpl
function with the following function signature,
where obj
is the agent object. using this function, you can set the agent
into a known or random condition before training.
function resetimpl(ob)
also, you can define any other helper functions in your custom agent class as required.
for example, the custom lqr agent defines a createcritic
function for
creating the critic and a getnewk
function that derives the feedback gain
matrix from the trained critic parameters.
create custom agent
after you define your custom agent class, create an instance of it in the matlab workspace. for example, to create the custom lqr agent, define the
q
, r
, and initialk
values and
call the constructor function.
q = [10,3,1;3,5,4;1,4,9]; r = 0.5*eye(3); k0 = place(a,b,[0.4,0.8,0.5]); agent = lqrcustomagent(q,r,k0);
after validating the environment object, you can use it to train a reinforcement learning agent. for an example that trains the custom lqr agent, see .