I am getting this error when running my code >>>>Dot indexing is not supported for variables of this type. Error in rl.util.expstruct2timeserstruct (line 7) observation
66 次查看(过去 30 天)
显示 更早的评论
The below code is the one I am running
Create Simulink Environment and Train Agent
This example shows how to convert the PI controller in the watertank Simulink® model to a reinforcement learning deep deterministic policy gradient (DDPG) agent. For an example that trains a DDPG agent in MATLAB®, see Train DDPG Agent to Balance Double Integrator Environment.
Water Tank Model
The original model for this example is the water tank model. The goal is to control the level of the water in the tank. For more information about the water tank model, see watertank Simulink Model.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1759494/image.png)
Modify the original model by making the following changes:
- Delete the PID Controller.
- Insert the RL Agent block.
- Connect the observation vector
, where h is the height of the water in the tank,
, and r is the reference height.
- Set up the reward
.
- Configure the termination signal such that the simulation stops if
or
.
The resulting model is rlwatertank.slx. For more information on this model and the changes, see Create Simulink Environment for Reinforcement Learning.
open_system("RLFinal_PhD_Model_DroopPQ1")
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1759524/image.png)
Create the Environment
Creating an environment model includes defining the following:
- Action and observation signals that the agent uses to interact with the environment. For more information, see rlNumericSpec and rlFiniteSetSpec.
- Reward signal that the agent uses to measure its success. For more information, see Define Reward Signals.
Define the observation specification obsInfo and action specification actInfo.
% Observation info
obsInfo = rlNumericSpec([3 1],...
LowerLimit=[-inf -inf 0 ]',...
UpperLimit=[ inf inf inf]');
% Name and description are optional and not used by the software
obsInfo.Name = "observations";
obsInfo.Description = "integrated error, error, and measured height";
% Action info
actInfo = rlNumericSpec([1 1]);
actInfo.Name = "flow";
Create the environment object.
env = rlSimulinkEnv("RLFinal_PhD_Model_DroopPQ1","RLFinal_PhD_Model_DroopPQ1/RL Agent1",...
obsInfo,actInfo);
Set a custom reset function that randomizes the reference values for the model.
env.ResetFcn = @(in)localResetFcn(in);
Specify the simulation time Tf and the agent sample time Ts in seconds.
Ts = 1.0;
Tf = 200;
Fix the random generator seed for reproducibility.
rng(0)
Create the Critic
DDPG agents use a parametrized Q-value function approximator to estimate the value of the policy. A Q-value function critic takes the current observation and an action as inputs and returns a single scalar as output (the estimated discounted cumulative long-term reward for which receives the action from the state corresponding to the current observation, and following the policy thereafter).
To model the parametrized Q-value function within the critic, use a neural network with two input layers (one for the observation channel, as specified by obsInfo, and the other for the action channel, as specified by actInfo) and one output layer (which returns the scalar value).
Define each network path as an array of layer objects. Assign names to the input and output layers of each path. These names allow you to connect the paths and then later explicitly associate the network input and output layers with the appropriate environment channel. Obtain the dimension of the observation and action spaces from the obsInfo and actInfo specifications.
% Observation path
obsPath = [
featureInputLayer(obsInfo.Dimension(1),Name="obsInLyr")
fullyConnectedLayer(50)
reluLayer
fullyConnectedLayer(25,Name="obsPathOutLyr")
];
% Action path
actPath = [
featureInputLayer(actInfo.Dimension(1),Name="actInLyr")
fullyConnectedLayer(25,Name="actPathOutLyr")
];
% Common path
commonPath = [
additionLayer(2,Name="add")
reluLayer
fullyConnectedLayer(1,Name="QValue")
];
% Create the network object and add the layers
criticNet = dlnetwork();
criticNet = addLayers(criticNet,obsPath);
criticNet = addLayers(criticNet,actPath);
criticNet = addLayers(criticNet,commonPath);
% Connect the layers
criticNet = connectLayers(criticNet, ...
"obsPathOutLyr","add/in1");
criticNet = connectLayers(criticNet, ...
"actPathOutLyr","add/in2");
View the critic network configuration.
figure
plot(criticNet)
Initialize the dlnetwork object and summarize its properties.
criticNet = initialize(criticNet);
summary(criticNet)
Create the critic approximator object using the specified deep neural network, the environment specification objects, and the names if the network inputs to be associated with the observation and action channels.
critic = rlQValueFunction(criticNet, ...
obsInfo,actInfo, ...
ObservationInputNames="obsInLyr", ...
ActionInputNames="actInLyr");
Check the critic with a random input observation and action.
getValue(critic, ...
{rand(obsInfo.Dimension)}, ...
{rand(actInfo.Dimension)})
Create the Actor
DDPG agents use a parametrized deterministic policy over continuous action spaces, which is learned by a continuous deterministic actor.
A continuous deterministic actor implements a parametrized deterministic policy for a continuous action space. This actor takes the current observation as input and returns as output an action that is a deterministic function of the observation.
To model the parametrized policy within the actor, use a neural network with one input layer (which receives the content of the environment observation channel, as specified by obsInfo) and one output layer (which returns the action to the environment action channel, as specified by actInfo).
Define the network as an array of layer objects.
actorNet = [
featureInputLayer(obsInfo.Dimension(1))
fullyConnectedLayer(3)
tanhLayer
fullyConnectedLayer(actInfo.Dimension(1))
];
Convert the network to a dlnetwork object and summarize its properties.
actorNet = dlnetwork(actorNet);
summary(actorNet)
Create the actor approximator object using the specified deep neural network, the environment specification objects, and the name if the network input to be associated with the observation channel.
actor = rlContinuousDeterministicActor(actorNet,obsInfo,actInfo);
Check the actor with a random input observation.
getAction(actor,{rand(obsInfo.Dimension)})
Create the DDPG Agent
Create the DDPG agent using the specified actor and critic approximator objects.
agent = rlDDPGAgent(actor,critic);
Specify options for the agent, the actor, and the critic using dot notation.
agent.SampleTime = Ts;
agent.AgentOptions.TargetSmoothFactor = 1e-3;
agent.AgentOptions.DiscountFactor = 1.0;
agent.AgentOptions.MiniBatchSize = 64;
agent.AgentOptions.ExperienceBufferLength = 1e6;
agent.AgentOptions.NoiseOptions.Variance = 0.3;
agent.AgentOptions.NoiseOptions.VarianceDecayRate = 1e-5;
agent.AgentOptions.CriticOptimizerOptions.LearnRate = 1e-03;
agent.AgentOptions.CriticOptimizerOptions.GradientThreshold = 1;
agent.AgentOptions.ActorOptimizerOptions.LearnRate = 1e-04;
agent.AgentOptions.ActorOptimizerOptions.GradientThreshold = 1;
Check the agent with a random input observation.
getAction(agent,{rand(obsInfo.Dimension)})
Train Agent
To train the agent, first specify the training options. For this example, use the following options:
- Run each training for at most 5000 episodes. Specify that each episode lasts for at most ceil(Tf/Ts) (that is 200) time steps.
- Display the training progress in the Episode Manager dialog box (set the Plots option) and disable the command line display (set the Verbose option to false).
- Stop training when the agent receives an average cumulative reward greater than 800 over 20 consecutive episodes. At this point, the agent can control the level of water in the tank.
trainOpts = rlTrainingOptions(...
MaxEpisodes=5000, ...
MaxStepsPerEpisode=ceil(Tf/Ts), ...
ScoreAveragingWindowLength=20, ...
Verbose=false, ...
Plots="training-progress",...
StopTrainingCriteria="AverageReward",...
StopTrainingValue=800);
Train the agent using the train function. Training is a computationally intensive process that takes several minutes to complete. To save time while running this example, load a pretrained agent by setting doTraining to false. To train the agent yourself, set doTraining to true.
doTraining = true;
if doTraining
% Train the agent.
trainingStats = train(agent,env,trainOpts);
else
% Load the pretrained agent for the example.
load("WaterTankDDPG.mat","agent")
end
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1759529/image.png)
Validate Trained Agent
Validate the learned agent against the model by simulation. Since the reset function randomizes the reference values, fix the random generator seed to ensure simulation reproducibility.
rng(1)
Simulate the agent within the environment, and return the experiences as output.
simOpts = rlSimulationOptions(MaxSteps=ceil(Tf/Ts),StopOnError="on");
experiences = sim(env,agent,simOpts);
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1759534/image.png)
Local Reset Function
function in = localResetFcn(in)
% Randomize reference signal
blk = sprintf("RLFinal_PhD_Model_DroopPQ1/Droop/Voutref");
h = 3*randn + 0.5;
while h <= 0 || h >= 400
h = 3*randn + 200;
end
in = setBlockParameter(in,blk,Value=num2str(h));
% Randomize initial height
h1 = 3*randn + 200;
while h1 <= 0 || h1 >= 1
h1 = 3*randn + 0.5;
end
blk = "RLFinal_PhD_Model_DroopPQ1/Gain";
in = setBlockParameter(in,blk,Gain=num2str(h1));
end
I am getting the following results without rewards at all
Zero rewards
When I stop the trainging I see this error::::
Dot indexing is not supported for variables of this type.
Error in rl.util.expstruct2timeserstruct (line 7)
observation = {experiences.Observation};
Error in rl.env.AbstractEnv/sim (line 138)
s = rl.util.expstruct2timeserstruct(exp,time,oinfo,ainfo);
16 个评论
Walter Roberson
2024-8-25,21:00
dbstop in rl.util.expstruct2timeserstruct.m 7
Then run the code. It will (presumably) stop just before executing line 7, and will show the debugging prompt
K>>
At that point you can explore the then-current variable experiences
回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Applications 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!