From d5ae0c694aac260df29116cfc41f84613287202d Mon Sep 17 00:00:00 2001 From: "Steinar H. Gunderson" Date: Mon, 17 Sep 2012 13:35:38 +0200 Subject: [PATCH] Initial checkin. --- Makefile | 9 +++++++ fit.sh | 5 ++++ opt.cc | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 95 insertions(+) create mode 100644 Makefile create mode 100755 fit.sh create mode 100644 opt.cc diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..1e14781 --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +CXX=g++ +CXXFLAGS=-O2 -ffast-math -g -Wno-write-strings $(shell pkg-config eigen3 --cflags) +LDFLAGS=-lceres_shared + +OBJS=opt.o + +opt: $(OBJS) + $(CXX) -o $@ $(OBJS) $(LDFLAGS) + diff --git a/fit.sh b/fit.sh new file mode 100755 index 0000000..f3062d3 --- /dev/null +++ b/fit.sh @@ -0,0 +1,5 @@ +#! /bin/sh +make +wget -q -O- http://www.google.com/intl/en_ALL/ipv6/statistics/data/adoption.js | grep '^ \[' | cut -d, -f5 | cut -d\] -f1 > nativeadoption.dat +./opt nativeadoption.dat + diff --git a/opt.cc b/opt.cc new file mode 100644 index 0000000..20e6a61 --- /dev/null +++ b/opt.cc @@ -0,0 +1,81 @@ +// Optimizes general sigmoid function 1/(1 + exp(-a(t-m))) over a set of points. + +#include +#include +#include "ceres/ceres.h" +#include "gflags/gflags.h" +#include "glog/logging.h" + +using namespace ceres; +using std::vector; + +struct Point { + float t; + float adoption_rate; +}; + +class DistanceFromSigmoidCostFunction { + public: + DistanceFromSigmoidCostFunction(Point p) : p_(p) {} + + template + bool operator() (const T * const a, const T * const m, T* e) const { + *e = T(p_.adoption_rate) - T(1.0) / (T(1.0) + ceres::exp(- *a * (T(p_.t) - *m))); + return true; + } + + private: + Point p_; +}; + +int main(int argc, char** argv) { + google::ParseCommandLineFlags(&argc, &argv, true); + google::InitGoogleLogging(argv[0]); + + Problem problem; + + FILE *fp = fopen(argv[1], "r"); + if (fp == NULL) { + perror(argv[1]); + exit(1); + } + + // The two parameters to be optimized. + double a = 1.0; + double m = 0.5; + + int line_num = 0; + while (!feof(fp)) { + char buf[256]; + if (fgets(buf, 256, fp) == NULL) { + break; + } + Point p; + p.t = line_num; + p.adoption_rate = atof(buf) * 0.01; + problem.AddResidualBlock( + new AutoDiffCostFunction( + new DistanceFromSigmoidCostFunction(p)), + NULL, + &a, &m); + ++line_num; + } + fclose(fp); + + a = 1.0 / line_num; + + // Run the solver! + Solver::Options options; + options.max_num_iterations = 1000000; + options.linear_solver_type = ceres::DENSE_QR; + options.minimizer_progress_to_stdout = true; + + Solver::Summary summary; + Solve(options, &problem, &summary); + + std::cout << summary.BriefReport() << "\n"; + std::cout << "a=" << a << std::endl; + std::cout << "m=" << m << std::endl; + + return 0; +} -- 2.39.2