为了实现DQN强化学习控制,需要进行以下步骤:
- 搭建系统模型:
根据系统模型,可以定义状态、动作、奖励和环境。在这个案例中,我们使用的是基于电机控制的系统模型,其中状态是电机的角速度和位置,动作是电机的输入电压,奖励是位移与设定值之间的差别。
电机控制系统实现:
classdef MotorControlSystem < rl.env.MATLABEnvironment
%MATLABENVIRONMENT Template for defining custom environment in MATLAB.
% Environment properties
properties
% 系统参数
I = 0.25;
b = 0.1;
K = 0.01;
R = 1;
L = 0.5;
% 电机状态
Theta = 0.1;
Theta_dot = 0;
% 电机控制
InputVoltage = 0;
end
% 环境连续性设置
properties(Constant)
Ts = 0.01;
% 最大时间步数
MaxForceTimeSteps = 2500;
end
% Observation settings
properties
% 观测值宽度
ObservationDimension = 2;
end
% 用于计算奖励的变量
% 目标位置
TargetPosition = 0;
% 选择的惩罚因子
PunishFactor = 50;
% 继承MATLABEnvironment的函数
methods
% 验证环境和默认状态
function validateEnvironment(this)
% 验证自定义环境实现的有效性
end
% 输入初始状态
function init(this)
% 初始化环境
this.Theta = 0.1;
this.Theta_dot = 0;
this.InputVoltage = 0;
end
% 设置状态和动作
function setObservation(this,observation)
% 设置环境观测值
this.Theta = observation(1);
this.Theta_dot = observation(2);
end
function observation = getObservation(this)
% 得到当前环境观测值
observation = [this.Theta; this.Theta_dot];
end
function [reward,isdone] = getReward(this)
% 计算环境奖励
distance = abs(this.Theta - this.TargetPosition);
reward = exp(-distance^2/this.PunishFactor)+1;
if distance < 0.01
reward = reward + 10;
end
isdone = this.CurrentStep == this.MaxForceTimeSteps;
end
function [nextobs,reward,isdone] = step(this,action)
% 实现环境中一次决策的动作并返回环境的状态、奖励和停止标志。
this.InputVoltage = clamp(action,-12,12);
% 电机运行模型
[theta_dot_dot,theta_dot] = motor_model(this.InputVoltage,this.Theta_dot,this.Theta,this.I,this.b,this.K,this.R,this.L);
% 计算状态
this.Theta_dot = this.Theta_dot + this.Ts * theta_dot_dot;
this.Theta = this.Theta + this.Ts * this.Theta_dot;
nextobs = this.getObservation();
[reward,isdone] = this.getReward();
end
% 选择合适执行动作
function action = getActionInfo(this)
% 返回动作信息结构体
ActionInfo = rlNumericSpec([1 1],'LowerLimit',-12,'UpperLimit',12);
ActionInfo.Name = '电压输入';
action = ActionInfo;
end
end
end
% 电机运行模型定义
function [theta_dot_dot,theta_dot] = motor_model(u,theta_dot,theta,I,b,K,R,L)
c1 = -(R*I+b)/(K*I);
c2 = 1/(K*I);
theta_dot_dot = c1 * theta_dot + c2 * u;
theta_dot = theta_dot + theta_dot_dot * 0.01;
end
% 数值限制函数
function y = clamp(u,low,high)
y = u;
y(y>high) = high;
y(y<low) = low;
end
- 构建深度神经网络:
DQN算法使用深度神经网络来估计位移对电压的动作价值函数。这里我们使用的是深度全连接神经网络作为 DQN网络。
由于这是一个连续动作空间的任务,因此我们使用一个actor-critic架构并利用actor神经网络直接输出动作控制,critic神经网络输出动作价值函数。
电压控制策略实现:
classdef DQNMotorControl < rl.agent.AbstractCritic & rl.agent.AbstractActor
%DQNMOTORCONTROL
% 网络架构
properties
StatePath
ActionPath
CriticNetwork
ActorNetwork
TargetCriticNetwork
TargetActorNetwork
end
% 参数设置
properties
UseGPU
TargetSmoothFactor
DiscountFactor
ExperienceBufferLength
MiniBatchSize
NumStepsToLookAhead
LearnRate
GradThreshold
CriticGradientThreshold
ActorGradientThreshold
EntropyWeight
Epsilon
EpsilonDecay
EpsilonMin
UseDoubleDQN
UseFastUpdate
ClipActorGradients
ClipCriticGradients
SaveExperienceBufferWithAgent
ResetExperienceBufferBeforeTraining
end
% 深度学习环境
properties (SetAccess = protected)
% 深度学习环境
ObservationInfo
ActionInfo
% Actors返回动作值(在critic端使用)信息的time
% step。在连续操作空间中,时间步长必须小于1。
% 本例使用1
TimeStep
% Agent的错误计算
CriticError
end
% 训练参数
properties
% Soft update of targets
ExperienceBuffer
NumStepsTaken
StepsUntilTargetUpdate
CurrentEpisode
IsTrainingComplete
HasTrainingStarted
% 可选的导入下载的DQN模型
ImportAgent
% 数据保存命名
AgentName
% 保存连续现场参数
SaveExperienceBufferWithPath
end
methods
function this = DQNMotorControl(criticNetwork,actorNetwork,observationInfo,actionInfo)
%DQNMOTORCONTROL 构造函数
this.CriticNetwork = criticNetwork;
this.ActorNetwork = actorNetwork;
this.ObservationInfo = observationInfo;
this.ActionInfo = actionInfo;
this.StatePath = findPlaceholderByType(this.CriticNetwork,"observation","observation");
this.ActionPath = findPlaceholderByType(this.CriticNetwork,"action","action");
this.TargetCriticNetwork = copy(this.CriticNetwork);
this.TargetActorNetwork = copy(this.ActorNetwork);
this.StatePath = findPlaceholderByType(this.CriticNetwork,"observation","observation");
this.ActionPath = findPlaceholderByType(this.CriticNetwork,"action","action");
% Critic
this.CriticNetwork.Options.LearnRate = this.LearnRate;
this.CriticNetwork.Options.GradientThreshold = this.CriticGradientThreshold;
% Actor
this.ActorNetwork.Options.LearnRate = this.LearnRate;
this.ActorNetwork.Options.GradientThreshold = this.ActorGradientThreshold;
end
function set.Options.LearnRate(this,val)
this.LearnRate = val;
this.CriticNetwork.Options.LearnRate = val;
this.ActorNetwork.Options.LearnRate = val;
end
function set.Options.GradientThreshold(this,val)
this.CriticGradientThreshold = val;
this.ActorGradientThreshold = val;
this.CriticNetwork.Options.GradientThreshold = val;
this.ActorNetwork.Options.GradientThreshold = val;
end
% 训练
function [action,exp] = learn(this,exp)
imageSize = this.ObservationInfo.Dimension;
actionRep = [
imageInputLayer([imageSize 1],'Normalization','none','Name','observation')
fullyConnectedLayer(4050, 'Name', 'fc1')
reluLayer('Name', 'relu1')
fullyConnectedLayer(4050, 'Name', 'fc2')
reluLayer('Name', 'relu2')
fullyConnectedLayer(1, 'Name', 'fc3')
tanhLayer('Name', 'rtanh1')
scalingLayer('Name', 'Scaling', 'Scale', this.ActionInfo.UpperLimit, 'Center', 0)];
critic = rlQValueRepresentation(this.CriticNetwork,this.ObservationInfo,...
this.ActionInfo,'Observation',{'observation'},'Action',{'action'});
actor = rlDeterministicActorRepresentation(actionRep,this.ObservationInfo, ...
this.ActionInfo,'Observation',{'observation'},'Action',{'Scaling'},...
'OutputMode','normal');
critic.Options.LearnRate = this.LearnRate;
actor.Options.LearnRate = this.LearnRate;
critic.Options.GradientThreshold = this.CriticGradientThreshold;
actor.Options.GradientThreshold = this.ActorGradientThreshold;
agentOptions = rlDQNAgentOptions(...
'UseDoubleDQN', this.UseDoubleDQN, ...
'TargetSmoothFactor',0.1, ...
'DiscountFactor',this.DiscountFactor, ...
'MiniBatchSize',this.MiniBatchSize, ...
'ExperienceBufferLength',this.ExperienceBufferLength, ...
'LearnRate',this.LearnRate, ...
'GradientThreshold',this.GradThreshold, ...
'Epsilon',this.Epsilon, ...
'EpsilonDecay',this.EpsilonDecay, ...
'ExperienceBufferLength',1e6, ...
'UsePriorityReplay', false ,...
'EntropyWeight',this.EntropyWeight);
agent = rlDQNAgent(critic,agentOptions);
agent.Critic_ = critic;
agent.Actor_ = actor;
agent = setLearnableParameters(agent,[]);
% 训练
% 训练200个周期,每个周期使用20000步
maxepisodes = 10;
maxsteps = 20000;
maxrounds = 8;
totalsteps = maxepisodes * maxsteps * maxrounds;
% 状态展示
plot(env,'gif','actionFrequency',2);
% 训练代理程序
% 起点电压为0
InitialVoltage = 0;
for r = 1:maxrounds
ratings = [];
for i = 1:maxepisodes
observation = env.reset();
state = observation;
action = agent.getAction(state);
reward = 0;
fprintf("正在进行第: %d, %d 轮 回合: %d,电压: %g ,状态: %s %s\n",r,i,InitialVoltage,action,state{1},state{2});
% 环境初始设定
% env.Theta = -pi/2;
% env.Theta_dot = 0;
for j = 1:maxsteps
observation = env.step(action);