0%

python数据分析与机器学习实战-19.线性回归

1
2
3
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
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
class LinearRegression():
def __init__(self):
self.w=None

def fit(self,X,y):
print(X.shape)
X=np.insert(X,0,1,axis=1)
print(X.shape)
X_=np.linalg.inv(X.T.dot(X))
self.w = X_.dot(X.T).dot(y)

def predict(self,X):
X=np.insert(X,0,1,axis=1)
y_pred = X.dot(self.w)
return y_pred

def mean_squared_error(y_true,y_pred):
mse = np.mean(np.power(y_true-y_pred,2))
return mse

def main():
diabetes = datasets.load_diabetes()
X = diabetes.data[:,np.newaxis,2]
print(X.shape)
x_train,x_test = X[:-20],X[-20:]
y_train,y_test = diabetes.target[:-20],diabetes.target[-20:]

clf = LinearRegression()
clf.fit(x_train,y_train)
y_pred = clf.predict(x_test)

plt.scatter(x_test[:,0],y_test,color='black')
plt.plot(x_test[:,0],y_pred,color='blue',linewidth=3)
plt.show()
main()
(442, 1)
(422, 1)
(422, 2)

png

# 线性回归