MATLAB Reinforcement Learning Toolbox(6)テンプレートからカスタムMATLAB環境を作成します


テンプレート環境クラスを作成および変更することにより、カスタマイズされた強化学習環境を定義できます。カスタムテンプレート環境を使用して、

  1. より複雑な環境ダイナミクスを実現します。
  2. 環境にカスタムビジュアライゼーションを追加します。
  3. C ++、Java、Pythonなどの言語で定義されたサードパーティライブラリへのインターフェイスを作成します。

テンプレートクラスを作成する

カスタム環境を定義するには、最初にテンプレートクラスファイルを作成し、クラスの名前を指定します。この例では、クラスにMyEnvironmentという名前を付けます。

rlCreateEnvTemplate("MyEnvironment")

ソフトウェアはテンプレートファイルを作成して開きます。テンプレートクラスはrl.envのサブクラスです。テンプレートファイルの先頭にあるクラス定義に示されているMATLABEnvironment抽象クラス。この抽象クラスは、他のMATLAB強化学習環境オブジェクトで使用される抽象クラスと同じです。

classdef MyEnvironment <rl.env.MATLABEnvironment

デフォルトでは、テンプレートクラスは、「事前定義された制御システム環境のロード」で説明されている列事前定義環境と同様に、単純な列バランスモデルを実装します。

テンプレートクラスを動的に変更する環境を定義するには、以下を指定します。

  1. 環境属性
  2. 環境を必要とする方法
  3. 代替の環境方法

環境属性

テンプレートのプロパティセクションで、環境の作成とシミュレーションに必要なパラメータを指定します。これらのパラメータには次のものが含まれます。

  1. 物理定数-サンプル環境は、重力(重力)による加速度を定義します。
  2. 環境ジオメトリ-サンプル環境は、カートとポールの質量(CartMassとPoleMass)とポールの半分の長さ(HalfPoleLength)を定義します。
  3. 環境の制約-サンプル環境では、極角とカートの距離のしきい値(AngleThresholdとDisplacementThreshold)が定義されています。環境はこれらの値を使用して、トレーニングエピソードがいつ終了するかを検出します。
  4. 評価に必要な環境変数-サンプル環境の状態ベクトル(ステータス)と、エピソードが終了したことを示すフラグ(IsDone)を定義します。
  5. アクションまたは観測空間を定義する一定のサンプル環境は、アクション空間の最大力(MaxForce)を定義します。
  6. 報酬シグナルの計算に使用される定数-サンプル環境では、RewardForNotFalling定数とPenaltyForFalling定数を定義しています。
properties
    % Specify and initialize the necessary properties of the environment  
    % Acceleration due to gravity in m/s^2
    Gravity = 9.8
    
    % Mass of the cart
    CartMass = 1.0
    
    % Mass of the pole
    PoleMass = 0.1
    
    % Half the length of the pole
    HalfPoleLength = 0.5
    
    % Max force the input can apply
    MaxForce = 10
           
    % Sample time
    Ts = 0.02
    
    % Angle at which to fail the episode (radians)
    AngleThreshold = 12 * pi/180
        
    % Distance at which to fail the episode
    DisplacementThreshold = 2.4
        
    % Reward each time step the cart-pole is balanced
    RewardForNotFalling = 1
    
    % Penalty when the cart-pole fails to balance
    PenaltyForFalling = -10 
end
    
properties
    % Initialize system state [x,dx,theta,dtheta]'
    State = zeros(4,1)
end

properties(Access = protected)
    % Initialize internal flag to indicate episode termination
    IsDone = false        
end

必要な機能

強化学習環境では、以下の機能を定義する必要があります。関数getObservationInfo、getActionInfo、sim、validateEnvironmentは、基本抽象クラスで定義されています。環境を作成するには、コンストラクター、リセット、およびステップ関数を定義する必要があります。
ここに画像の説明を挿入します

サンプルコンストラクター

サンプルのカートポールコンストラクターは、次の方法で環境を作成します。

  1. 定義されたアクションと観察指標。これらの仕様の作成の詳細。

  2. 基本的な抽象クラスのコンストラクターを呼び出します。

function this = MyEnvironment()
    % Initialize observation settings
    ObservationInfo = rlNumericSpec([4 1]);
    ObservationInfo.Name = 'CartPole States';
    ObservationInfo.Description = 'x, dx, theta, dtheta';

    % Initialize action settings   
    ActionInfo = rlFiniteSetSpec([-1 1]);
    ActionInfo.Name = 'CartPole Action';

    % The following line implements built-in functions of the RL environment
    this = this@rl.env.MATLABEnvironment(ObservationInfo,ActionInfo);

    % Initialize property values and precompute necessary values
    updateActionInfo(this);
end

このサンプルコンストラクターには、入力パラメーターは含まれていません。ただし、カスタムコンストラクターに入力パラメーターを追加することはできます。

サンプリングリセット機能

サンプルリセット関数は、モデルの初期条件を設定し、観測値の初期値を返します。また、envUpdatedCallback関数を呼び出すことにより、環境が更新されたという通知を生成します。これは、環境の視覚化を更新するのに役立ちます。

% Reset environment to initial state and return initial observation
function InitialObservation = reset(this)
    % Theta (+- .05 rad)
    T0 = 2 * 0.05 * rand - 0.05;  
    % Thetadot
    Td0 = 0;
    % X 
    X0 = 0;
    % Xdot
    Xd0 = 0;

    InitialObservation = [X0;Xd0;T0;Td0];
    this.State = InitialObservation;

    % (Optional) Use notifyEnvUpdated to signal that the 
    % environment is updated (for example, to update the visualization)
    notifyEnvUpdated(this);
end

サンプリングステップ関数

サンプリングカースイング機能:

  1. 入力アクションを処理します。
  2. 環境ダイナミクス方程式を1回評価します。
  3. 更新された観測値を計算して返します。
  4. 報酬信号を計算して返します。
  5. エピソードが完了しているかどうかを確認し、IsDoneが信号を適切に返します。
  6. 環境が更新されたという通知を生成します。
function [Observation,Reward,IsDone,LoggedSignals] = step(this,Action)
    LoggedSignals = [];

    % Get action
    Force = getForce(this,Action);            

    % Unpack state vector
    XDot = this.State(2);
    Theta = this.State(3);
    ThetaDot = this.State(4);

    % Cache to avoid recomputation
    CosTheta = cos(Theta);
    SinTheta = sin(Theta);            
    SystemMass = this.CartMass + this.PoleMass;
    temp = (Force + this.PoleMass*this.HalfPoleLength*ThetaDot^2*SinTheta)...
        /SystemMass;

    % Apply motion equations            
    ThetaDotDot = (this.Gravity*SinTheta - CosTheta*temp)...
        / (this.HalfPoleLength*(4.0/3.0 - this.PoleMass*CosTheta*CosTheta/SystemMass));
    XDotDot  = temp - this.PoleMass*this.HalfPoleLength*ThetaDotDot*CosTheta/SystemMass;

    % Euler integration
    Observation = this.State + this.Ts.*[XDot;XDotDot;ThetaDot;ThetaDotDot];

    % Update system states
    this.State = Observation;

    % Check terminal condition
    X = Observation(1);
    Theta = Observation(3);
    IsDone = abs(X) > this.DisplacementThreshold || abs(Theta) > this.AngleThreshold;
    this.IsDone = IsDone;

    % Get reward
    Reward = getReward(this);

    % (Optional) Use notifyEnvUpdated to signal that the 
    % environment has been updated (for example, to update the visualization)
    notifyEnvUpdated(this);
end

オプション機能

必要に応じて、テンプレートクラスで他の関数を定義できます。たとえば、ステップまたはリセットによって呼び出されるヘルパー関数を作成できます。レバーテンプレートモデルは、各タイムステップの報酬を計算するgetReward関数を実装しています。

function Reward = getReward(this)
    if ~this.IsDone
        Reward = this.RewardForNotFalling;
    else
        Reward = this.PenaltyForFalling;
    end          
end

環境の視覚化

プロット機能を実装することにより、カスタム環境に視覚化効果を追加できます。プロット関数の場合:

  1. 独自に実装されたグラフィックスまたは視覚化ツールクラスのインスタンスを作成します。この例では、グラフを作成し、グラフのハンドルを環境オブジェクトに格納します。
  2. envUpdatedCallback関数を呼び出します。
function plot(this)
    % Initiate the visualization
    this.Figure = figure('Visible','on','HandleVisibility','off');
    ha = gca(this.Figure);
    ha.XLimMode = 'manual';
    ha.YLimMode = 'manual';
    ha.XLim = [-3 3];
    ha.YLim = [-1 2];
    hold(ha,'on');
    % Update the visualization
    envUpdatedCallback(this)
end

この例では、グラフィックスハンドルを環境オブジェクトの保護されたプロパティとして保存します。

function envUpdatedCallback(this)
    if ~isempty(this.Figure) && isvalid(this.Figure)
        % Set visualization figure as the current figure
        ha = gca(this.Figure);

        % Extract the cart position and pole angle
        x = this.State(1);
        theta = this.State(3);

        cartplot = findobj(ha,'Tag','cartplot');
        poleplot = findobj(ha,'Tag','poleplot');
        if isempty(cartplot) || ~isvalid(cartplot) ...
                || isempty(poleplot) || ~isvalid(poleplot)
            % Initialize the cart plot
            cartpoly = polyshape([-0.25 -0.25 0.25 0.25],[-0.125 0.125 0.125 -0.125]);
            cartpoly = translate(cartpoly,[x 0]);
            cartplot = plot(ha,cartpoly,'FaceColor',[0.8500 0.3250 0.0980]);
            cartplot.Tag = 'cartplot';

            % Initialize the pole plot
            L = this.HalfPoleLength*2;
            polepoly = polyshape([-0.1 -0.1 0.1 0.1],[0 L L 0]);
            polepoly = translate(polepoly,[x,0]);
            polepoly = rotate(polepoly,rad2deg(theta),[x,0]);
            poleplot = plot(ha,polepoly,'FaceColor',[0 0.4470 0.7410]);
            poleplot.Tag = 'poleplot';
        else
            cartpoly = cartplot.Shape;
            polepoly = poleplot.Shape;
        end

        % Compute the new cart and pole position
        [cartposx,~] = centroid(cartpoly);
        [poleposx,poleposy] = centroid(polepoly);
        dx = x - cartposx;
        dtheta = theta - atan2(cartposx-poleposx,poleposy-0.25/2);
        cartpoly = translate(cartpoly,[dx,0]);
        polepoly = translate(polepoly,[dx,0]);
        polepoly = rotate(polepoly,rad2deg(dtheta),[x,0.25/2]);

        % Update the cart and pole positions on the plot
        cartplot.Shape = cartpoly;
        poleplot.Shape = polepoly;

        % Refresh rendering in the figure window
        drawnow();
    end
end     

環境はenvUpdatedCallback関数を呼び出すため、環境が更新されると視覚化が更新されます。

カスタム環境を作成する

カスタム環境クラスを定義した後、MATLABワークスペースでそのインスタンスを作成します。コマンドラインで、次のように入力します。

env = MyEnvironment;

コンストラクターに入力パラメーターがある場合は、クラス名の後にそれらを指定します。たとえば、MyEnvironment(arg1、arg2)です。

環境が作成された後のベストプラクティスは、環境のダイナミクスを検証することです。これを行うには、validateEnvironment関数を使用してください。環境の実装に問題がある場合、この関数はコマンドウィンドウにエラーを表示します。

validateEnvironment(env)

環境オブジェクトを検証した後、それを使用して強化学習エージェントをトレーニングできます。

おすすめ

転載: blog.csdn.net/wangyifan123456zz/article/details/109477303