Email: helpdesk@telkomuniversity.ac.id

This Portal for internal use only!

  • My Download
  • Checkout
Application Package Repository Telkom University
All Categories

All Categories

  • Visual Paradigm
  • IBM
  • Adobe
  • Google
  • Matlab
  • Microsoft
    • Microsoft Apps
    • Analytics
    • AI + Machine Learning
    • Compute
    • Database
    • Developer Tools
    • Internet Of Things
    • Learning Services
    • Middleware System
    • Networking
    • Operating System
    • Productivity Tools
    • Security
    • VLS
      • Windows
      • Office
  • Opensource
  • Wordpress
    • Plugin WP
    • Themes WP
  • Others

Search

0 Wishlist

Cart

Categories
  • Microsoft
    • Microsoft Apps
    • Office
    • Operating System
    • VLS
    • Developer Tools
    • Productivity Tools
    • Database
    • AI + Machine Learning
    • Middleware System
    • Learning Services
    • Analytics
    • Networking
    • Compute
    • Security
    • Internet Of Things
  • Adobe
  • Matlab
  • Google
  • Visual Paradigm
  • WordPress
    • Plugin WP
    • Themes WP
  • Opensource
  • Others
More Categories Less Categories
  • Get Pack
    • Product Category
    • Simple Product
    • Grouped Product
    • Variable Product
    • External Product
  • My Account
    • Download
    • Cart
    • Checkout
    • Login
  • About Us
    • Contact
    • Forum
    • Frequently Questions
    • Privacy Policy
  • Forum
    • News
      • Category
      • News Tag

iconTicket Service Desk

  • My Download
  • Checkout
Application Package Repository Telkom University
All Categories

All Categories

  • Visual Paradigm
  • IBM
  • Adobe
  • Google
  • Matlab
  • Microsoft
    • Microsoft Apps
    • Analytics
    • AI + Machine Learning
    • Compute
    • Database
    • Developer Tools
    • Internet Of Things
    • Learning Services
    • Middleware System
    • Networking
    • Operating System
    • Productivity Tools
    • Security
    • VLS
      • Windows
      • Office
  • Opensource
  • Wordpress
    • Plugin WP
    • Themes WP
  • Others

Search

0 Wishlist

Cart

Menu
  • Home
    • Download Application Package Repository Telkom University
    • Application Package Repository Telkom University
    • Download Official License Telkom University
    • Download Installer Application Pack
    • Product Category
    • Simple Product
    • Grouped Product
    • Variable Product
    • External Product
  • All Pack
    • Microsoft
      • Operating System
      • Productivity Tools
      • Developer Tools
      • Database
      • AI + Machine Learning
      • Middleware System
      • Networking
      • Compute
      • Security
      • Analytics
      • Internet Of Things
      • Learning Services
    • Microsoft Apps
      • VLS
    • Adobe
    • Matlab
    • WordPress
      • Themes WP
      • Plugin WP
    • Google
    • Opensource
    • Others
  • My account
    • Download
    • Get Pack
    • Cart
    • Checkout
  • News
    • Category
    • News Tag
  • Forum
  • About Us
    • Privacy Policy
    • Frequently Questions
    • Contact
Home/Matlab/trying perform an image classification using RL but facing error, Any suggestion?

trying perform an image classification using RL but facing error, Any suggestion?

/ 2025-01-07
trying perform an image classification using RL but facing error, Any suggestion?
Matlab

clc;

%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);

% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);

% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);

%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;

% Feature extraction layer
featureLayer = ‘fc7’;

% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);

% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);

% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);

%% RL Environment Setup

% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);

ObservationInfo.Description = ‘Feature vector extracted from CNN’;

% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;

% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);

% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);

%% Define RL Agent

% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions

criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);

% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);

agent = rlDQNAgent(critic, agentOpts);

%% Train RL Agent

trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);

trainingStats = train(agent, env);

%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.

% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();

% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;

% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector

% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end

% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end

%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;

% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end

% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);

% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR

Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.

Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);

Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:});clc;

%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);

% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);

% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);

%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;

% Feature extraction layer
featureLayer = ‘fc7’;

% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);

% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);

% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);

%% RL Environment Setup

% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);

ObservationInfo.Description = ‘Feature vector extracted from CNN’;

% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;

% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);

% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);

%% Define RL Agent

% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions

criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);

% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);

agent = rlDQNAgent(critic, agentOpts);

%% Train RL Agent

trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);

trainingStats = train(agent, env);

%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.

% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();

% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;

% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector

% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end

% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end

%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;

% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end

% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);

% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR

Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.

Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);

Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:}); clc;

%% Load Dataset
imds = imageDatastore(‘D:2023thesiswaveletImagesSubsetImages’, …
‘IncludeSubfolders’, true, …
‘LabelSource’, ‘foldernames’);

% Ensure the dataset is balanced
DataSetInfo = countEachLabel(imds);

% Split Data into Training and Validation sets
[imdsTrain, imdsValidation] = splitEachLabel(imds, 0.80, ‘randomized’);

%% Load Pretrained Network
net = vgg16;
inputSize = net.Layers(1).InputSize;

% Feature extraction layer
featureLayer = ‘fc7’;

% Augment data to match input size of the network
augimdsTrain = augmentedImageDatastore(inputSize, imdsTrain);
augimdsValidation = augmentedImageDatastore(inputSize, imdsValidation);

% Extract Features using Pretrained CNN
trainFeatures = activations(net, augimdsTrain, featureLayer, ‘OutputAs’, ‘rows’);
validationFeatures = activations(net, augimdsValidation, featureLayer, ‘OutputAs’, ‘rows’);

% Extract labels
trainLabels = grp2idx(imdsTrain.Labels);
validationLabels = grp2idx(imdsValidation.Labels);

%% RL Environment Setup

% Define Observation and Action spaces
numFeatures = size(trainFeatures, 2); % Number of features (e.g., 4096 for ‘fc7’ layer)
ObservationInfo = rlNumericSpec([numFeatures, 1], …
‘LowerLimit’, -inf, ‘UpperLimit’, inf, …
‘Name’, ‘Features’);

ObservationInfo.Description = ‘Feature vector extracted from CNN’;

% Define Action space (each action corresponds to a class label)
ActionInfo = rlFiniteSetSpec(1:max(trainLabels)); % Class labels as actions
ActionInfo.Name = ‘Class Labels’;

% Define Step and Reset functions
stepFunction = @(Action, LoggedSignals) stepFunctionRL(Action, trainFeatures, trainLabels, LoggedSignals);
resetFunction = @() resetFunctionRL(trainFeatures);

% Create RL Environment
env = rlFunctionEnv(ObservationInfo, ActionInfo, stepFunction, resetFunction);

%% Define RL Agent

% Define critic network
statePath = [
featureInputLayer(numFeatures, ‘Normalization’, ‘none’, ‘Name’, ‘state’)
fullyConnectedLayer(128, ‘Name’, ‘fc1’)
reluLayer(‘Name’, ‘relu1’)
fullyConnectedLayer(64, ‘Name’, ‘fc2’)
reluLayer(‘Name’, ‘relu2’)
fullyConnectedLayer(numel(ActionInfo.Elements), ‘Name’, ‘fcOutput’)]; % Number of actions

criticNet = dlnetwork(layerGraph(statePath));
critic = rlQValueFunction(criticNet, ObservationInfo, ActionInfo, ‘ObservationInputNames’, ‘state’);

% Agent options
agentOpts = rlDQNAgentOptions( …
‘ExperienceBufferLength’, 1e5, …
‘DiscountFactor’, 0.99, …
‘MiniBatchSize’, 64, …
‘TargetSmoothFactor’, 1e-3, …
‘TargetUpdateFrequency’, 4);

agent = rlDQNAgent(critic, agentOpts);

%% Train RL Agent

trainOpts = rlTrainingOptions( …
‘MaxEpisodes’, 500, …
‘MaxStepsPerEpisode’, size(trainFeatures, 1), …
‘Verbose’, true, …
‘Plots’, ‘training-progress’, …
‘StopTrainingCriteria’, ‘EpisodeCount’, …
‘StopTrainingValue’, 500);

trainingStats = train(agent, env);

%% Reset Function
function [InitialObservation, LoggedSignals] = resetFunctionRL(Features)
% Reset function for the RL environment
% This function resets the environment to its initial state at the start
% of each new episode.

% Initialize the LoggedSignals structure (holds environment state)
LoggedSignals = struct();

% Set the initial observation index to the first data point
LoggedSignals.CurrentIndex = 1;

% Fetch the initial observation: the first feature vector
% Ensure that the observation is formatted as a column vector [numFeatures, 1]
InitialObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to column vector

% Check if the initial observation matches the expected size
if size(InitialObservation, 2) ~= 1
error(‘InitialObservation must be a column vector of size [numFeatures, 1]’);
end

% Optionally, initialize any other properties you want in LoggedSignals
% (e.g., additional state variables, environment-specific flags)
LoggedSignals.EpisodeStartTime = datetime(‘now’); % Track the start time for each episode
end

%% Step Function
function [NextObservation, Reward, IsDone, LoggedSignals] = stepFunctionRL(Action, Features, Labels, LoggedSignals)
% Step function for the RL environment
idx = LoggedSignals.CurrentIndex;

% Assign reward based on action correctness
correctLabel = Labels(idx); % Correct label for the current feature
if Action == correctLabel
Reward = 1; % Positive reward for correct classification
else
Reward = -1; % Negative reward for incorrect classification
end

% Update index and check if episode is done
LoggedSignals.CurrentIndex = idx + 1;
IsDone = LoggedSignals.CurrentIndex > size(Features, 1);

% Ensure the next observation is a column vector of size [numFeatures, 1]
if ~IsDone
NextObservation = Features(LoggedSignals.CurrentIndex, :)’; % Transpose to ensure column vector [numFeatures x 1]
else
NextObservation = Features(idx, :)’; % Dummy to avoid dimension mismatch
end
end
AND THIS IS THE ERROR

Error using rl.env.MATLABEnvironment/validateEnvironment (line 58)
Environment ‘ObservationInfo’ does not match observation output from reset function. Check the data type, dimensions, and range.

Error in rl.env.rlFunctionEnv (line 82)
validateEnvironment(this);

Error in rlFunctionEnv (line 45)
env = rl.env.rlFunctionEnv(varargin{:}); rl, image-classification MATLAB Answers — New Questions

​

Tags: matlab

Share this!

Related posts

test one two three four
2025-05-20

test one two three four

Is it possible to make this tiny loop faster?
2025-05-19

Is it possible to make this tiny loop faster?

Solar Wind Battery Hybrid Integration
2025-05-19

Solar Wind Battery Hybrid Integration

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Search

Categories

  • Matlab
  • Microsoft
  • News
  • Other
Application Package Repository Telkom University

Tags

matlab microsoft opensources
Application Package Download License

Application Package Download License

Adobe
Google for Education
IBM
Matlab
Microsoft
Wordpress
Visual Paradigm
Opensource

Sign Up For Newsletters

Be the First to Know. Sign up for newsletter today

Application Package Repository Telkom University

Portal Application Package Repository Telkom University, for internal use only, empower civitas academica in study and research.

Information

  • Telkom University
  • About Us
  • Contact
  • Forum Discussion
  • FAQ
  • Helpdesk Ticket

Contact Us

  • Ask: Any question please read FAQ
  • Mail: helpdesk@telkomuniversity.ac.id
  • Call: +62 823-1994-9941
  • WA: +62 823-1994-9943
  • Site: Gedung Panambulai. Jl. Telekomunikasi

Copyright © Telkom University. All Rights Reserved. ch

  • FAQ
  • Privacy Policy
  • Term

This Application Package for internal Telkom University only (students and employee). Chiers... Dismiss