Last active
May 24, 2017 17:41
-
-
Save sstelfox/38b1aefbbb145dc95be41c2bd79efcc1 to your computer and use it in GitHub Desktop.
Quick unoptimized model to perform certain stat operations
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
module Statistics | |
def self.sum(data) | |
data.inject(0.0) { |s, val| s + val } | |
end | |
def self.mean(data) | |
sum(data) / data.size | |
end | |
def self.median(data) | |
data.sort[data.size / 2] | |
end | |
def self.mode(data) | |
val_counts = data.group_by { |v| v }.map { |k, v| [k, v.count] }.sort_by { |k, v| v }.reverse | |
val_counts.select { |k, v| v == val_counts[0][1] }.map { |k, _| k } | |
end | |
def self.stddev(data) | |
Math.sqrt(variance(data).abs) | |
end | |
def self.variance(data) | |
mu = mean(data) | |
squared_diff = data.map { |val| (mu - val) ** 2 } | |
sum(squared_diff) / (data.size == 1 ? 1 : data.size - 1) | |
end | |
def self.dot_product(x, y) | |
(0...x.size).inject(0) { |s, i| s + (x[i] * y[i]) } | |
end | |
def self.linear_reg(x, y) | |
m = s_xy(x, y) / s_xx(x) | |
b = mean(y) - (m * mean(x)) | |
[ m, b ] | |
end | |
def self.s_xy(x, y) | |
dot_product(x, y) - sum(x) * sum(y) / x.size | |
end | |
def self.s_xx(x) | |
dot_product(x, x) - sum(x) ** 2 / x.size | |
end | |
def self.sse(x, y, m, b) | |
dot_product(y, y) - m * dot_product(x, y) - b * sum(y) | |
end | |
def self.sst(y) | |
dot_product(y, y) - sum(y) ** 2 / y.size | |
end | |
def self.r(x, y) | |
s_xy(x, y) / (Math.sqrt(s_xx(x)) * Math.sqrt(s_xx(y))) | |
end | |
def self.r_squared(x, y, m, b) | |
1 - sse(x, y, m, b) / sst(y) | |
end | |
end |
It's also worth noting that using N-1 (instead of N) is good for finding sample variance and standard deviation, but in the case data.size = 1 (which implies the data is not a sample), unbiased population variance and standard deviation (N) should be used instead to avoid undefined values.
Thanks man. Updated the gist to take both of those into account
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Small but important change to the variance calculation:
@@ -26,1 +26,1
- sum(data) / (data.size - 1)
+ sum(squared_diff) / (data.size - 1)
This helps to avoid infinite standard deviation in cases where the mean and variance exist in the real number domain.