My Project
gd.hpp
Go to the documentation of this file.
1 #pragma once
2 
3 #include "../common.hpp"
5 #include <Eigen/Eigen>
6 #include <chrono>
7 #include <iostream>
8 
9 namespace cpu_mlp {
10 
15 template <typename V, typename M> class GradientDescent : public FullBatchMinimizer<V, M> {
16  // Inherit protected members
18  using Base::_iters;
19  using Base::_max_iters;
20  using Base::_tol;
21 
22 public:
27  void setStepSize(double alpha) noexcept { step_size = alpha; }
28 
33  void useLineSearch(bool enable) noexcept { use_line_search = enable; }
34 
42  V solve(V x, VecFun<V, double> &f, GradFun<V> &Gradient) override {
43 
44  const bool timing = (this->recorder_ != nullptr);
45  if (this->recorder_) this->recorder_->reset();
46  auto start_time = std::chrono::steady_clock::now();
47 
48  V g = Gradient(x);
49  for (_iters = 0; _iters < _max_iters; ++_iters) {
50  if (g.norm() < _tol) break;
51 
52  double alpha = step_size;
53  if (use_line_search) alpha = this->line_search(x, -g, f, Gradient);
54 
55  x = x - alpha * g;
56  g = Gradient(x);
57 
58  if (this->recorder_) {
59  double loss = f(x);
60  double elapsed_ms = 0.0;
61  if (timing) {
62  auto now = std::chrono::steady_clock::now();
63  elapsed_ms = std::chrono::duration<double, std::milli>(now - start_time).count();
64  }
65  this->recorder_->record(_iters, loss, g.norm(), elapsed_ms);
66  }
67  }
68  return x;
69  }
70 
71 private:
72  double step_size = 1e-2;
73  bool use_line_search = true;
74 };
75 
76 } // namespace cpu_mlp
void reset()
Reset recorded size without releasing memory.
Definition: iteration_recorder.hpp:31
void record(int idx, double loss, double grad_norm, double time_ms=0.0)
Record a loss/grad/time entry at iteration index.
Definition: iteration_recorder.hpp:40
Base class for Full Batch Minimizers.
Definition: full_batch_minimizer.hpp:23
double _tol
Definition: full_batch_minimizer.hpp:109
double line_search(V x, V p, VecFun< V, double > &f, GradFun< V > &Gradient)
Backtracking Line Search satisfying Wolfe Conditions.
Definition: full_batch_minimizer.hpp:126
unsigned int _iters
Definition: full_batch_minimizer.hpp:108
::IterationRecorder< CpuBackend > * recorder_
Optional recorder for diagnostics.
Definition: full_batch_minimizer.hpp:110
unsigned int _max_iters
Definition: full_batch_minimizer.hpp:107
Standard Gradient Descent with optional Line Search.
Definition: gd.hpp:15
V solve(V x, VecFun< V, double > &f, GradFun< V > &Gradient) override
Run Gradient Descent.
Definition: gd.hpp:42
void setStepSize(double alpha) noexcept
Sets the constant step size.
Definition: gd.hpp:27
void useLineSearch(bool enable) noexcept
Enables or disables Line Search.
Definition: gd.hpp:33
std::function< T(T)> GradFun
Gradient function type alias (T -> T).
Definition: common.hpp:32
std::function< W(T)> VecFun
Objective function type alias (T -> W).
Definition: common.hpp:35
Definition: layer.hpp:13