adam_optimizer.cc 1023 字节
Newer Older
1 2 3 4 5
#include "adam_optimizer.h"

namespace paddle {
namespace optimizer {

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

D
dzhwinter 已提交
14
void AdamOptimizer::update(const Tensor &gradient) {
15
  num_sample_passed += 1;
16 17 18 19 20 21 22 23 24 25
  double learning_rate = lr_policy->get_learning_rate(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);
  learning_rate *= std::sqrt(coef2) / coef1;
  for (size_t i = 0; i < parameter_->size(); ++i) {
    momentums_[i] = beta_1 * momentums_[i] + (1.0 - beta_1) * gradient[i];
    velocitys_[i] =
        beta_2 * velocitys_[i] + (1.0 - beta_2) * gradient[i] * gradient[i];
    parameter_[i] -=
        learning_rate * (momentums_[i] / std::sqrt(velocitys_[i] + epsilon) +
26 27 28 29 30
                         decay * parameter_[i]);
  }
}
}  // namespace optimizer
}  // namespace paddle