/
chp6_pml_part2.py
71 lines (50 loc) · 1.51 KB
/
chp6_pml_part2.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
63
64
65
66
67
68
69
70
71
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 04:14:16 2020
@author: lehrs
"""
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
import numpy as np
df = pd.read_csv('.\\PML\\polynomial.csv')
plt.scatter(df.x,df.y)
plt.show()
#plt.plot(df.x, df.y, 'b*')
model = LinearRegression()
x = df.x[0:6, np.newaxis] #---convert to 2D array---
y = df.y[0:6, np.newaxis] #---convert to 2D array---
# or...
# x = np.array(df.x).reshape(-1,1)
model.fit(x,y)
#---perform prediction---
y_pred = model.predict(x)
#---plot the training points---
plt.scatter(x, y, s=10, color='b')
#---plot the straight line---
plt.plot(x, y_pred, color='r')
plt.show()
#---calculate R-squared---
print('R-squared for training set: %.4f' % model.score(x,y))
print(model.intercept_)
print(model.coef_)
# end of page 137
# https://scikit-learn.org/stable/modules/classes.html
from sklearn.preprocessing import PolynomialFeatures
degree = 2
polynomial_features = PolynomialFeatures(degree = degree)
x_poly = polynomial_features.fit_transform(x)
print(x_poly)
print(x)
model = LinearRegression()
model.fit(x_poly, y)
y_poly_pred = model.predict(x_poly)
#---plot the points---
plt.scatter(x, y, s=10)
#---plot the regression line---
plt.plot(x, y_poly_pred)
plt.show()
print(model.intercept_)
print(model.coef_)
print('R-squared for training set: %.4f' % model.score(x_poly,y))
#http://polynomialregression.drque.net/math.html