Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Combiner] Add a class for computing variance distributedly #235

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions core/combiner.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,82 @@
#include <set>
#include <utility>
#include <vector>
#include <cmath>

#include "boost/sort/spreadsort/spreadsort.hpp"

#include "base/log.hpp"

namespace husky {

class VarianceMeanNum {
public:
VarianceMeanNum() {
Copy link
Member

@kygx-legend kygx-legend Feb 6, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VarianceMeanNum() : variance_(.0), mean_(.0), num_(0) {}

variance = 0;
mean = 0;
num = 0;
}

VarianceMeanNum(double variance, double mean, int num) : variance(variance), mean(mean), num(num) {}

inline void set(double variance, double mean, int num) {
this->variance = variance;
this->mean = mean;
this->num = num;
}

// it works even when one side has num == 0
VarianceMeanNum& operator+=(const VarianceMeanNum& rhs) {
if (rhs.num == 0) {
return *this;
}

int num_ = num + rhs.num;
double delta = rhs.mean - mean;
double mean_ = (mean * num + rhs.mean * rhs.num) / num_;
variance = (variance * num + rhs.variance * rhs.num + delta * delta * num * rhs.num / num_) / num_;

mean = mean_;
num = num_;

return *this;
}

VarianceMeanNum operator+(const VarianceMeanNum& rhs) {
VarianceMeanNum res = *this;
res += rhs;
return res;
}

VarianceMeanNum& operator+=(double rhs) {
int num_ = num + 1;
double delta = rhs - mean;
double mean_ = (mean * num + rhs) / (num_);
variance = (variance * num + (rhs - mean) * (rhs - mean_)) / num_;

mean = mean_;
num = num_;

return *this;
}

VarianceMeanNum operator+(double rhs) {
VarianceMeanNum res = *this;
res += rhs;
return res;
}

inline double get_variance() const { return variance; }
inline double get_sd() const { return std::sqrt(variance); }
inline double get_mean() const { return mean; }
inline int get_num() const { return num; }

private:
double variance;
double mean;
int num;
};

struct HashCombinerBase {};

template <typename MsgT>
Expand Down