bitsim
Model, simulate, estimate and control robots in C++
Loading...
Searching...
No Matches
double_q_learning.h
Go to the documentation of this file.
1#ifndef DOUBLE_Q_LEARNING_H
2#define DOUBLE_Q_LEARNING_H
3
7
12#include "bitrl/rl/rl_mixins.h"
16
17#include <chrono>
18#include <random>
19#include <string>
20#include <tuple>
21#include <vector>
22
23namespace bitrl
24{
26{
27
69
84template <envs::discrete_world_concept EnvTp, typename ActionSelector>
85class DoubleQLearning final : public TDAlgoBase<EnvTp>,
86 protected with_double_q_table_mixin<DynMat<real_t>>,
88{
89 public:
93 typedef ActionSelector action_selector_type;
95
99 DoubleQLearning(const DoubleQLearningConfig config, const ActionSelector &selector);
100
105
110
111 virtual void actions_before_episode_begins(env_type &, uint_t /*episode_idx*/) {}
112
116 virtual void actions_after_episode_ends(env_type &, uint_t episode_idx,
117 const EpisodeInfo & /*einfo*/)
118 {
119 action_selector_.adjust_on_episode(episode_idx);
120 }
121
125 virtual EpisodeInfo on_training_episode(env_type &, uint_t episode_idx);
126
130 void save(std::string filename) const;
131
132 const DynMat<real_t> &q_table_1() const noexcept { return this->table_mixin_type::q_table_1; }
133 const DynMat<real_t> &q_table_2() const noexcept { return this->table_mixin_type::q_table_2; }
134
135 private:
136 DoubleQLearningConfig config_;
137 action_selector_type action_selector_;
138
142 std::mt19937 generator_;
143
144 void update_q_table_(const action_type &action, const state_type &cstate,
145 const state_type &next_state, real_t reward, bool done);
146};
147
148template <envs::discrete_world_concept EnvTp, typename ActionSelector>
150 const ActionSelector &selector)
151 : TDAlgoBase<EnvTp>(), table_mixin_type(), config_(config), action_selector_(selector),
152 generator_(config.seed)
153{
154}
155
156template <envs::discrete_world_concept EnvTp, typename ActionSelector>
161
162template <envs::discrete_world_concept EnvTp, typename ActionSelector>
164{
165 if (config_.path != bitsim::consts::INVALID_STR)
166 {
167 save(config_.path);
168 }
169}
170
171template <envs::discrete_world_concept EnvTp, typename ActionSelector>
173 uint_t episode_idx)
174{
175 auto start = std::chrono::steady_clock::now();
176 EpisodeInfo info;
177
178 auto episode_score = 0.0;
179 auto state = env.reset().observation();
180
181 uint_t itr = 0;
182 for (; itr < config_.max_num_iterations_per_episode; ++itr)
183 {
184 auto action = action_selector_(this->table_mixin_type::q_table_1,
185 this->table_mixin_type::q_table_2, state);
186
187 auto time_step = env.step(action);
188 auto next_state = time_step.observation();
189 auto reward = time_step.reward();
190 auto done = time_step.done();
191
192 episode_score += reward;
193 update_q_table_(action, state, next_state, reward, done);
194 state = next_state;
195
196 if (done)
197 {
198 break;
199 }
200 }
201
202 auto end = std::chrono::steady_clock::now();
203 std::chrono::duration<real_t> elapsed_seconds = end - start;
204
205 info.episode_index = episode_idx;
206 info.episode_reward = episode_score;
207 info.episode_iterations = itr;
208 info.total_time = elapsed_seconds;
209 return info;
210}
211
212template <envs::discrete_world_concept EnvTp, typename ActionSelector>
213void DoubleQLearning<EnvTp, ActionSelector>::update_q_table_(const action_type &action,
214 const state_type &cstate,
215 const state_type &next_state,
216 real_t reward, bool done)
217{
218 auto &q_table_1 = this->table_mixin_type::q_table_1;
219 auto &q_table_2 = this->table_mixin_type::q_table_2;
220 const auto n_actions = static_cast<uint_t>(q_table_1.cols());
221
222 // a fair coin picks the table to update; the other one values the
223 // action that is best in it
224 std::bernoulli_distribution coin(0.5);
225 const bool update_first = coin(generator_);
226 auto &updated = update_first ? q_table_1 : q_table_2;
227 const auto &other = update_first ? q_table_2 : q_table_1;
228
229 // nothing follows a terminal state, so its value is 0
230 auto next_value = 0.0;
231 if (!done)
232 {
233 const auto best_action =
234 with_double_q_table_max_action_mixin::max_action(updated, next_state, n_actions);
235 next_value = other(next_state, best_action);
236 }
237
238 const auto target = reward + config_.gamma * next_value;
239 const auto current = updated(cstate, action);
240 updated(cstate, action) = current + config_.eta * (target - current);
241}
242
243template <envs::discrete_world_concept EnvTp, typename ActionSelector>
244void DoubleQLearning<EnvTp, ActionSelector>::save(std::string filename) const
245{
246 const auto &q_table_1 = this->table_mixin_type::q_table_1;
247 const auto &q_table_2 = this->table_mixin_type::q_table_2;
248
249 bitsim::utils::io::CSVWriter file_writer(filename, ',');
250 file_writer.open();
251
252 // one row per state and table: the state, which of the two tables, and
253 // the value of each action in it
254 std::vector<std::string> col_names(2 + q_table_1.cols());
255 col_names[0] = "state_index";
256 col_names[1] = "table";
257 for (uint_t i = 0; i < static_cast<uint_t>(q_table_1.cols()); ++i)
258 {
259 col_names[i + 2] = "action_" + std::to_string(i);
260 }
261 file_writer.write_column_names(col_names);
262
263 // a tuple with a DynVec in it would write the action values in one
264 // column, so every row is a vector of numbers
265 const auto n_actions = static_cast<uint_t>(q_table_1.cols());
266 std::vector<real_t> row(2 + n_actions);
267 for (uint_t s = 0; s < static_cast<uint_t>(q_table_1.rows()); ++s)
268 {
269 for (uint_t t = 1; t <= 2; ++t)
270 {
271 const auto &table = t == 1 ? q_table_1 : q_table_2;
272 row[0] = static_cast<real_t>(s);
273 row[1] = static_cast<real_t>(t);
274 for (uint_t a = 0; a < n_actions; ++a)
275 {
276 row[2 + a] = table(s, a);
277 }
278 file_writer.write_row(row);
279 }
280 }
281}
282
283} // namespace rl::algos::td
284} // namespace bitrl
285
286#endif // DOUBLE_Q_LEARNING_H
virtual void actions_before_training_begins(env_type &)
Sets both tables to zero.
Definition double_q_learning.h:157
with_double_q_table_mixin< DynMat< real_t > > table_mixin_type
Definition double_q_learning.h:94
TDAlgoBase< EnvTp >::action_type action_type
Definition double_q_learning.h:91
ActionSelector action_selector_type
Definition double_q_learning.h:93
TDAlgoBase< EnvTp >::env_type env_type
Definition double_q_learning.h:90
void save(std::string filename) const
Writes the two tables to a CSV file, one row per state and table.
Definition double_q_learning.h:244
virtual void actions_after_episode_ends(env_type &, uint_t episode_idx, const EpisodeInfo &)
Lets the action selector adjust itself, for example decay its epsilon.
Definition double_q_learning.h:116
const DynMat< real_t > & q_table_2() const noexcept
Definition double_q_learning.h:133
TDAlgoBase< EnvTp >::state_type state_type
Definition double_q_learning.h:92
DoubleQLearning(const DoubleQLearningConfig config, const ActionSelector &selector)
Constructor.
Definition double_q_learning.h:149
virtual void actions_after_training_ends(env_type &)
Saves the tables if the configuration gives a path.
Definition double_q_learning.h:163
virtual void actions_before_episode_begins(env_type &, uint_t)
Definition double_q_learning.h:111
const DynMat< real_t > & q_table_1() const noexcept
Definition double_q_learning.h:132
virtual EpisodeInfo on_training_episode(env_type &, uint_t episode_idx)
Plays one episode and updates the tables after every step.
Definition double_q_learning.h:172
env_type::action_type action_type
action_t
Definition td_algo_base.h:27
env_type::state_type state_type
state_t
Definition td_algo_base.h:32
EnvType env_type
env_t
Definition td_algo_base.h:22
The CSVWriter class. Handles writing into CSV file format.
Definition csv_file_writer.h:22
void write_row(const std::vector< T > &vals)
Write a row of the file.
Definition csv_file_writer.h:89
void write_column_names(const std::vector< std::string > &col_names, bool write_header=true)
Write the column names.
Definition csv_file_writer.cpp:16
virtual void open() override
Open the file for writing.
Definition file_writer_base.cpp:21
Definition double_q_learning.h:26
Various utilities used when working with RL problems.
Definition bitrl_log.h:25
const std::string INVALID_STR
Invalid string.
Definition bitsim_consts.h:21
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
Eigen::MatrixX< T > DynMat
Dynamically sized matrix to use around the library.
Definition bitsim_types.h:51
double real_t
real_t
Definition bitsim_types.h:20
The EpisodeInfo struct.
Definition episode_info.h:21
The configuration of DoubleQLearning.
Definition double_q_learning.h:32
real_t gamma
The discount factor.
Definition double_q_learning.h:47
uint_t n_episodes
Not used; the trainer decides how many episodes to run.
Definition double_q_learning.h:62
uint_t max_num_iterations_per_episode
The most steps an episode can take.
Definition double_q_learning.h:57
uint_t seed
The seed of the coin that picks which table a step updates.
Definition double_q_learning.h:67
std::string path
Where to save the two tables when training ends; nothing is saved if it is not set.
Definition double_q_learning.h:37
real_t tolerance
Not used; the trainer decides when training stops.
Definition double_q_learning.h:42
real_t eta
The learning rate.
Definition double_q_learning.h:52
static uint_t max_action(const TableTp &q1_table, const TableTp &q2_table, const StateTp &state, uint_t n_actions)
Returns the max action by averaging the state values from the two tables.
Definition rl_mixins.h:343
DynMat< value_type > q_table_1
q_table_1
Definition rl_mixins.h:169
DynMat< value_type > q_table_2
q_table_2
Definition rl_mixins.h:174
void initialize(const std::vector< index_type > &indices, action_type n_actions, real_t init_value)
initialize
Definition rl_mixins.h:154