-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomputations.go
152 lines (124 loc) · 2.47 KB
/
computations.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package olsgo
import (
"math"
)
// output
type ols struct {
intercept float64
b1 float64
r float64
R2 float64
x string
y string
}
// sum over 1d slice
func Sum(x []float64) float64 {
var sum float64
for _, v := range x {
sum += v
}
return sum
}
// compute mean over 1d slice
func Mean(x []float64) float64 {
return Sum(x) / float64(len(x))
}
// Standardize 1d slize
func ZScore(x []float64) []float64 {
mu := Mean(x)
sigma := Std(x)
z := make([]float64, len(x))
for i, v := range x {
z[i] = (v - mu) / sigma
}
return z
}
// compute total sums of squares for 1d slice
func Tss(y []float64) float64 {
var t []float64
mu := Mean(y)
for _, v := range y {
d := v - mu
t = append(t, d*d)
}
sst := Sum(t)
return sst
}
// compute std over 1d slice
func Std(x []float64) float64 {
numer := Tss(x)
n := float64(len(x))
return math.Sqrt(numer / (n - 1))
}
// Compute Pearson's r for two 1d slices.
func PearsonR(x []float64, y []float64) float64 {
if len(x) != len(y) {
return 0 // or handle error appropriately
}
xmu := Mean(x)
ymu := Mean(y)
var numer, xdenom, ydenom float64
for i := range x {
numer += (x[i] - xmu) * (y[i] - ymu)
xdenom += (x[i] - xmu) * (x[i] - xmu)
ydenom += (y[i] - ymu) * (y[i] - ymu)
}
r := numer / math.Sqrt(xdenom*ydenom)
return r
}
func B1(x []float64, y []float64) float64 {
r := PearsonR(x, y)
sx := Std(x)
sy := Std(y)
b := r * (sy / sx)
return b
}
// Calculate b0
func Intercept(x []float64, y []float64) float64 {
b1 := B1(x, y)
xbar := Mean(x)
ybar := Mean(y)
i := ybar - (b1 * xbar)
return i
}
// Compute y-hat
func YHat(x []float64, y []float64) []float64 {
inter := Intercept(x, y)
b1 := B1(x, y)
yhat := make([]float64, len(x))
for i := range x {
yhat[i] = inter + b1*x[i]
}
return yhat
}
// compute sums of squares explained for 1d slice
func Sse(y []float64, yhat []float64) float64 {
var sse float64
for i := range y {
d := y[i] - yhat[i]
sse += d * d
}
return sse
}
// calculate R2 from raw data
func R2(x []float64, y []float64) float64 {
sst := Tss(y)
yhat := YHat(x, y)
sse := Sse(y, yhat)
r2 := sse / sst
return r2
}
// Compute ordinary-least-squares regression over x and y variable
func OLS(d map[string][]float64, x string, y string) ols {
xv := d[x]
yv := d[y]
reg := ols{
intercept: Intercept(xv, yv),
b1: B1(xv, yv),
r: PearsonR(xv, yv),
R2: R2(xv, yv),
x: x,
y: y,
}
return reg
}