adagrad_optimizer.cc 1.3 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
  }
}
D
dzhwinter 已提交
20 21
const char* AdagradOptimizer::SerializeState(int* state_len) {
  AdagradOptimizerState state;
D
dzhwinter 已提交
22
  // TODO(zhihong) : add lr_policy serialization
D
dzhwinter 已提交
23 24 25 26
  state.set_num_sample_passed(num_sample_passed_);

  TensorToProto(*parameter_, state.mutable_parameter());
  TensorToProto(*accum_gradient_, state.mutable_accum_gradient());
D
dzhwinter 已提交
27 28 29
  auto str = state.SerializeAsString();
  *state_len = str.size();
  return str.c_str();
D
dzhwinter 已提交
30 31 32 33 34
}

void AdagradOptimizer::DeserializeState(const std::string& str) {
  AdagradOptimizerState state;
  state.ParseFromString(str);
D
dzhwinter 已提交
35
  // TODO(zhihong) : add lr_policy DeserializeState
D
dzhwinter 已提交
36 37 38 39
  num_sample_passed_ = state.num_sample_passed();
  ProtoToTensor(state.parameter(), parameter_);
  ProtoToTensor(state.accum_gradient(), accum_gradient_);
}
40 41

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