Last active
January 17, 2020 07:53
-
-
Save byronknoll/3bafb846d2760ab6081a37ac700c0618 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <valarray> | |
#include <stdio.h> | |
#include <random> | |
#include <functional> | |
double MSE(const std::valarray<float>& target, | |
const std::valarray<float>& lossy) { | |
return ((target-lossy)*(target-lossy)).sum() / target.size(); | |
} | |
int main() { | |
int n = 100; | |
std::valarray<float> target(n), lossy(n); | |
std::mt19937::result_type seed = 0xDEADBEEF; | |
auto real_rand = std::bind(std::uniform_real_distribution<double>(0,1), | |
std::mt19937(seed)); | |
for (int i = 0; i < n; ++i) { | |
target[i] = real_rand(); | |
} | |
// method 1: use mean | |
lossy = target.sum() / n; | |
printf("method 1: %.8f\n", MSE(target, lossy)); | |
// method 2: search for random seed | |
double best = 1; | |
for (int i = 0; i < 10000; ++i) { | |
for (int j = 0; j < n; ++j) { | |
lossy[j] = real_rand(); | |
} | |
double mse = MSE(target, lossy); | |
if (mse < best) { | |
best = mse; | |
} | |
} | |
printf("method 2: %.8f\n", best); | |
// method 3: random seed + offset | |
best = 1; | |
for (int i = 0; i < 10000; ++i) { | |
for (int j = 0; j < n; ++j) { | |
lossy[j] = real_rand(); | |
} | |
lossy += (target.sum() / n) - (lossy.sum() / n); | |
for (int j = 0; j < n; ++j) { | |
if (lossy[j] < 0) lossy[j] = 0; | |
else if (lossy[j] > 1) lossy[j] = 1; | |
} | |
double mse = MSE(target, lossy); | |
if (mse < best) { | |
best = mse; | |
} | |
} | |
printf("method 3: %.8f\n", best); | |
// method 4: sample from Bates distribution | |
best = 1; | |
for (int i = 0; i < 1000; ++i) { | |
for (int j = 0; j < n; ++j) { | |
double val = 0; | |
for (int k = 0; k < n; ++k) { | |
val += real_rand(); | |
} | |
lossy[j] = val / n; | |
} | |
double mse = MSE(target, lossy); | |
if (mse < best) { | |
best = mse; | |
} | |
} | |
printf("method 4: %.8f\n", best); | |
// method 5: sample from normal distribution | |
best = 1; | |
std::default_random_engine generator; | |
std::normal_distribution<double> distribution(0.5, 0.01); | |
for (int i = 0; i < 10000; ++i) { | |
for (int j = 0; j < n; ++j) { | |
lossy[j] = distribution(generator); | |
} | |
double mse = MSE(target, lossy); | |
if (mse < best) { | |
best = mse; | |
} | |
} | |
printf("method 5: %.8f\n", best); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment