adam_optimizer.cc 1.1 KB
Newer Older
1
#include "adam_optimizer.h"
2
#include <cmath>
3 4 5 6

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
7
void AdamOptimizer::set_weight(Tensor *p) {
D
dzhwinter 已提交
8
  parameter_ = p;
9
  size_t size = p->size();
D
dzhwinter 已提交
10
  real *mptr = new real[size];
11
  momentums_ = new Tensor(mptr, size);
D
dzhwinter 已提交
12
  real *vptr = new real[size];
13
  velocitys_ = new Tensor(vptr, size);
14 15
}

D
dzhwinter 已提交
16 17 18 19 20
void AdamOptimizer::Update(const Tensor *gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
  double coef1 = 1.0 - std::pow(beta_1_, num_sample_passed_);
  double coef2 = 1.0 - std::pow(beta_2_, num_sample_passed_);
21
  learning_rate *= std::sqrt(coef2) / coef1;
22 23 24 25 26
  Tensor &param = *parameter_;
  const Tensor &grad = *gradient;
  Tensor &m = *momentums_;
  Tensor &v = *velocitys_;
  for (size_t i = 0; i < param.size(); ++i) {
D
dzhwinter 已提交
27 28
    m[i] = beta_1_ * m[i] + (1.0 - beta_1_) * grad[i];
    v[i] = beta_2_ * v[i] + (1.0 - beta_2_) * grad[i] * grad[i];
29
    param[i] -=
D
dzhwinter 已提交
30
        learning_rate * (m[i] / std::sqrt(v[i] + epsilon_) + decay_ * param[i]);
31 32 33 34
  }
}
}  // namespace optimizer
}  // namespace paddle