Created
March 3, 2017 05:16
-
-
Save vznvzn/d2522277600219ef88b78832925d18b2 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
require 'statsample' | |
def fit(l, y, lx) | |
a = {} | |
(lx + [y]).each { |x| a[x] = l.map { |b| b[x] }.to_vector() } | |
ds = a.to_dataset() | |
r = Statsample::Regression.multiple(ds, y) | |
$stderr.puts(r.summary) | |
return r.coeffs.merge({'c' => r.constant}) | |
end | |
def predict(z, l1) | |
l1.each \ | |
{ | |
|x| | |
t = z['c'] | |
(z.keys - ['c']).each { |k| t += z[k] * x[k] } | |
x['y_p'] = t | |
} | |
end | |
def out(fn, l) | |
f = File.open("#{fn}.txt", 'w') | |
f.puts(l[0].keys.join("\t")) | |
l.each { |x| f.puts(x.values.join("\t")) } | |
f.close | |
end | |
def read(fn) | |
l = File.open('data.txt').readlines | |
l1 = l.shift.split | |
return l.map \ | |
{ | |
|x| | |
Hash[[l1, x.split.map { |y| y.to_f }].transpose] | |
} | |
end | |
l2 = read('data.txt') | |
$stderr.puts("#{l2.size} pts") | |
# out('out', l2) | |
z = fit(l2, 'y', l2[0].keys - ['y']) | |
predict(z, l2) | |
out('out1', l2.sort_by { |x| x['y'] }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment