-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmore_regression.py
More file actions
69 lines (52 loc) · 1.86 KB
/
more_regression.py
File metadata and controls
69 lines (52 loc) · 1.86 KB
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
#
#
# Regression and Classification programming exercises
#
#
#
# In this exercise we will be taking a small data set and computing a linear function
# that fits it, by hand.
#
# the data set
import numpy as np
sleep = [5, 6, 7, 8, 10]
scores = [65, 51, 75, 75, 86]
def compute_regression(sleep, scores):
# First, compute the average amount of each list
avg_sleep = np.mean(sleep)
avg_scores = np.mean(scores)
print avg_sleep, avg_scores
# Then normalize the lists by subtracting the mean value from each entry
normalized_sleep = np.array(sleep) - avg_sleep
normalized_scores = np.array(scores) - avg_scores
print normalized_sleep
print normalized_scores
# Compute the slope of the line by taking the sum over each student
# of the product of their normalized sleep times their normalized test score.
# Then divide this by the sum of squares of the normalized sleep times.
slope = np.sum(normalized_sleep * normalized_scores) / np.sum(np.square(normalized_sleep))
print slope
# Finally, We have a linear function of the form
# y - avg_y = slope * ( x - avg_x )
# Rewrite this function in the form
# y = m * x + b
# Then return the values m, b
return slope, avg_scores - (avg_sleep * slope)
#
# Polynomial Regression
#
# In this exercise we will examine more complex models of test grades as a function of
# sleep using numpy.polyfit to determine a good relationship and incorporating more data.
#
#
# at the end, store the coefficients of the polynomial you found in coeffs
#
def polyRegression():
sleep = [5,6,7,8,10,12,16]
scores = [65,51,75,75,86,80,0]
coeffs = np.polyfit(sleep, scores, 2)
return coeffs
if __name__ == "__main__":
m, b = compute_regression(sleep, scores)
print "Your linear model is y={}*x+{}".format(m, b)
print "Polynomial regression: ", polyRegression()