autoppl  v0.8
A C++ template library for probabilistic programming
welford.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <type_traits>
3 #include <Eigen/Dense>
4 
5 namespace ppl {
6 namespace math {
7 
12 struct WelfordVar
13 {
14  WelfordVar(size_t n_params)
15  : m_{n_params, 2}
16  , mean_{m_.col(0)}
17  , m2n_{m_.col(1)}
18  { m_.setZero(); }
19 
20  /*
21  * Update sample mean and sample variance with new sample x.
22  */
23  template <class MatType>
24  void update(const MatType& x)
25  {
26  ++n_;
27  auto delta = x - mean_;
28  mean_ += (1./static_cast<double>(n_)) * delta;
29  m2n_ += (delta.array() * (x - mean_).array()).matrix();
30  }
31 
32  const auto& get_variance() const { return m2n_; }
33  size_t get_n_samples() const { return n_; }
34 
39  void reset()
40  {
41  m_.setZero();
42  n_ = 0;
43  }
44 
45 private:
46  Eigen::MatrixXd m_;
47 
48  using col_t = std::decay_t<decltype(m_.col(0))>;
49  col_t mean_;
50  col_t m2n_;
51 
52  size_t n_ = 0; // number of samples
53 };
54 
55 } // namespace math
56 } // namespace ppl
ppl::math::WelfordVar::get_variance
const auto & get_variance() const
Definition: welford.hpp:32
ppl::math::WelfordVar::reset
void reset()
Definition: welford.hpp:39
ppl::math::WelfordVar::WelfordVar
WelfordVar(size_t n_params)
Definition: welford.hpp:14
ppl::math::WelfordVar::update
void update(const MatType &x)
Definition: welford.hpp:24
ppl::math::WelfordVar
Definition: welford.hpp:13
ppl
Definition: bounded.hpp:11
ppl::math::WelfordVar::get_n_samples
size_t get_n_samples() const
Definition: welford.hpp:33