123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- #include "fields_of_experts.h"
- #include <cmath>
- #include <fstream>
- #include "pgm_image.h"
- namespace ceres::examples {
- FieldsOfExpertsCost::FieldsOfExpertsCost(const std::vector<double>& filter)
- : filter_(filter) {
- set_num_residuals(1);
- for (int64_t i = 0; i < filter_.size(); ++i) {
- mutable_parameter_block_sizes()->push_back(1);
- }
- }
- bool FieldsOfExpertsCost::Evaluate(double const* const* parameters,
- double* residuals,
- double** jacobians) const {
- const int64_t num_variables = filter_.size();
- residuals[0] = 0;
- for (int64_t i = 0; i < num_variables; ++i) {
- residuals[0] += filter_[i] * parameters[i][0];
- }
- if (jacobians != nullptr) {
- for (int64_t i = 0; i < num_variables; ++i) {
- if (jacobians[i] != nullptr) {
- jacobians[i][0] = filter_[i];
- }
- }
- }
- return true;
- }
- void FieldsOfExpertsLoss::Evaluate(double sq_norm, double rho[3]) const {
- const double c = 0.5;
- const double sum = 1.0 + sq_norm * c;
- const double inv = 1.0 / sum;
-
- rho[0] = alpha_ * log(sum);
- rho[1] = alpha_ * c * inv;
- rho[2] = -alpha_ * c * c * inv * inv;
- }
- FieldsOfExperts::FieldsOfExperts() : size_(0), num_filters_(0) {}
- bool FieldsOfExperts::LoadFromFile(const std::string& filename) {
- std::ifstream foe_file(filename.c_str());
- foe_file >> size_;
- foe_file >> num_filters_;
- if (size_ < 0 || num_filters_ < 0) {
- return false;
- }
- const int num_variables = NumVariables();
- x_delta_indices_.resize(num_variables);
- for (int i = 0; i < num_variables; ++i) {
- foe_file >> x_delta_indices_[i];
- }
- y_delta_indices_.resize(NumVariables());
- for (int i = 0; i < num_variables; ++i) {
- foe_file >> y_delta_indices_[i];
- }
- alpha_.resize(num_filters_);
- for (int i = 0; i < num_filters_; ++i) {
- foe_file >> alpha_[i];
- }
- filters_.resize(num_filters_);
- for (int i = 0; i < num_filters_; ++i) {
- filters_[i].resize(num_variables);
- for (int j = 0; j < num_variables; ++j) {
- foe_file >> filters_[i][j];
- }
- }
-
- if (!foe_file) {
- size_ = 0;
- return false;
- }
-
-
- double temp;
- foe_file >> temp;
- if (foe_file) {
- size_ = 0;
- return false;
- }
- return true;
- }
- ceres::CostFunction* FieldsOfExperts::NewCostFunction(int alpha_index) const {
- return new FieldsOfExpertsCost(filters_[alpha_index]);
- }
- ceres::LossFunction* FieldsOfExperts::NewLossFunction(int alpha_index) const {
- return new FieldsOfExpertsLoss(alpha_[alpha_index]);
- }
- }
|