-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinear_regression.py
62 lines (48 loc) · 1.26 KB
/
linear_regression.py
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
## By BingLi224
##
## 13:31 THA 01/06/2018
##
## Linear Regression Example
##
## Click a point. When got > 1 point, auto calculate linear regression line.
from tkinter import *
from tkinter import ttk
points = []
def add_point ( event ) :
print ( str ( event.x ) + "\t" + str ( event.y ) )
cv.create_rectangle (
event.x - 1, event.y - 1,
event.x + 1, event.y + 1
)
points.append ( [ event.x, event. y ] )
if len ( points ) > 1 :
## get the width of the canvas
width = int ( cv.cget ( 'width' ) )
## count the sum
x_avg = 0
y_avg = 0
for p in points :
x_avg += p [ 0 ]
y_avg += p [ 1 ]
## get the averages
x_avg /= len ( points )
y_avg /= len ( points )
## calc the slope
slope = 0
slope_div = 0
for p in points :
slope += ( p [ 0 ] - x_avg ) * ( p [ 1 ] - y_avg )
slope_div += ( p [ 0 ] - x_avg ) ** 2
slope /= slope_div
## show the regression line
cv.delete ( 'regression' )
cv.create_line (
0, y_avg + slope * ( - x_avg ),
width, y_avg + slope * ( width - x_avg ),
tags = 'regression'
)
root = Tk ()
cv = Canvas ( root, width = 500, height = 500 )
cv.pack ( expand = 1, fill = 'both', side = 'top' )
cv.bind ( '<1>', add_point )
root.mainloop ( )