adagrad_optimizer.cc 1.4 KB
Newer Older
1 2
#include <cmath>

3 4 5 6 7
#include "adagrad_optimizer.h"

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
8 9 10
void AdagradOptimizer::Update(const Tensor* gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
11
  Tensor& param = *parameter_;
D
dzhwinter 已提交
12
  Tensor& accum_g = *accum_gradient_;
13 14 15
  const Tensor& grad = *gradient;
  for (size_t i = 0; i < param.size(); ++i) {
    accum_g[i] += grad[i] * grad[i];
D
dzhwinter 已提交
16 17
    param[i] += learning_rate * grad[i] / std::sqrt(accum_g[i] + epsilon_) +
                learning_rate * decay_ * param[i];
18 19
  }
}
20
std::string AdagradOptimizer::SerializeState() {
D
dzhwinter 已提交
21 22
  AdagradOptimizerState state;
  state.set_num_sample_passed(num_sample_passed_);
23
  std::string lr_str = this->lr_policy_->SerializeState();
D
dongzhihong 已提交
24
  state.mutable_lr_state()->ParseFromString(lr_str);
D
dzhwinter 已提交
25 26 27

  TensorToProto(*parameter_, state.mutable_parameter());
  TensorToProto(*accum_gradient_, state.mutable_accum_gradient());
28
  return state.SerializeAsString();
D
dzhwinter 已提交
29 30 31 32 33
}

void AdagradOptimizer::DeserializeState(const std::string& str) {
  AdagradOptimizerState state;
  state.ParseFromString(str);
D
dongzhihong 已提交
34 35 36
  auto lr_state = state.lr_state();
  this->lr_policy_->DeserializeState(lr_state.SerializeAsString());

D
dzhwinter 已提交
37 38 39 40
  num_sample_passed_ = state.num_sample_passed();
  ProtoToTensor(state.parameter(), parameter_);
  ProtoToTensor(state.accum_gradient(), accum_gradient_);
}
41 42

}  // namespace optimizer
D
dzhwinter 已提交
43
}  // namespace paddle