Skip to content

Commit 9335cc3

Browse files
committed
Merge naive python solution (Brice)
2 parents 15b937d + 740b088 commit 9335cc3

File tree

1 file changed

+56
-0
lines changed
  • 01-Simple-Linear-Regression/python-naive

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python
2+
3+
import resource
4+
5+
6+
points = []
7+
8+
with open("../data/ex2x.dat", 'r') as fx:
9+
with open("../data/ex2y.dat", 'r') as fy:
10+
xs = [float(xi) for xi in fx.readlines()]
11+
ys = [float(yi) for yi in fy.readlines()]
12+
points = zip(xs,ys)
13+
14+
def RSS(points, fn):
15+
return sum([ (fn(x)-y)**2 for (x,y) in points])
16+
17+
def linear(a,c):
18+
def fn(x):
19+
return (a*x)+c
20+
return fn
21+
22+
step = 0.00001
23+
24+
a0 = 0.0
25+
c0 = 0.0
26+
27+
def solve(points,a,c):
28+
rss = RSS(points, linear(a,c))
29+
30+
candidates = [
31+
(a+step, c),
32+
(a-step,c),
33+
(a,c+step),
34+
(a,c-step),
35+
(a-step,c-step),
36+
(a+step,c-step),
37+
(a+step,c+step),
38+
(a-step,c+step)
39+
]
40+
41+
best = min([
42+
(RSS(points, linear(a,c)),a,c) for a,c in candidates])
43+
return best
44+
45+
rss = RSS(points, linear(a0,c0))
46+
best = solve(points,a0,c0)
47+
48+
while best[0] < rss:
49+
rss = RSS(points, linear(best[1], best[2]))
50+
best = solve(points, best[1], best[2])
51+
52+
rss,a,c = best
53+
54+
print(
55+
"y={}x + {}".format(a,c)
56+
)

0 commit comments

Comments
 (0)