You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
58 lines
2.0 KiB
58 lines
2.0 KiB
7 years ago
|
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
|
||
7 years ago
|
|
||
7 years ago
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||
|
you may not use this file except in compliance with the License.
|
||
|
You may obtain a copy of the License at
|
||
7 years ago
|
|
||
7 years ago
|
http://www.apache.org/licenses/LICENSE-2.0
|
||
7 years ago
|
|
||
7 years ago
|
Unless required by applicable law or agreed to in writing, software
|
||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||
|
See the License for the specific language governing permissions and
|
||
|
limitations under the License. */
|
||
7 years ago
|
|
||
8 years ago
|
#include <cmath>
|
||
|
|
||
8 years ago
|
#include "adagrad_optimizer.h"
|
||
|
|
||
|
namespace paddle {
|
||
|
namespace optimizer {
|
||
|
|
||
8 years ago
|
void AdagradOptimizer::Update(const Tensor* gradient) {
|
||
|
num_sample_passed_ += 1;
|
||
|
double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
|
||
8 years ago
|
Tensor& param = *parameter_;
|
||
8 years ago
|
Tensor& accum_g = *accum_gradient_;
|
||
8 years ago
|
const Tensor& grad = *gradient;
|
||
|
for (size_t i = 0; i < param.size(); ++i) {
|
||
|
accum_g[i] += grad[i] * grad[i];
|
||
8 years ago
|
param[i] += learning_rate * grad[i] / std::sqrt(accum_g[i] + epsilon_) +
|
||
|
learning_rate * decay_ * param[i];
|
||
8 years ago
|
}
|
||
|
}
|
||
7 years ago
|
std::string AdagradOptimizer::SerializeState() {
|
||
8 years ago
|
AdagradOptimizerState state;
|
||
|
state.set_num_sample_passed(num_sample_passed_);
|
||
7 years ago
|
std::string lr_str = this->lr_policy_->SerializeState();
|
||
8 years ago
|
state.mutable_lr_state()->ParseFromString(lr_str);
|
||
8 years ago
|
|
||
|
TensorToProto(*parameter_, state.mutable_parameter());
|
||
|
TensorToProto(*accum_gradient_, state.mutable_accum_gradient());
|
||
7 years ago
|
return state.SerializeAsString();
|
||
8 years ago
|
}
|
||
|
|
||
|
void AdagradOptimizer::DeserializeState(const std::string& str) {
|
||
|
AdagradOptimizerState state;
|
||
|
state.ParseFromString(str);
|
||
8 years ago
|
auto lr_state = state.lr_state();
|
||
|
this->lr_policy_->DeserializeState(lr_state.SerializeAsString());
|
||
|
|
||
8 years ago
|
num_sample_passed_ = state.num_sample_passed();
|
||
|
ProtoToTensor(state.parameter(), parameter_);
|
||
|
ProtoToTensor(state.accum_gradient(), accum_gradient_);
|
||
|
}
|
||
8 years ago
|
|
||
|
} // namespace optimizer
|
||
8 years ago
|
} // namespace paddle
|