回归模型与房价预测

 1 from sklearn.datasets import load_boston
 2 import matplotlib.pyplot as plt
 3 from sklearn.linear_model import LinearRegression
 4 from sklearn.preprocessing import PolynomialFeatures
 5 
 6 def yiyuan(data,x,y):
 7     '''一元模型并画图'''
 8     plt.scatter(x, y)
 9     plt.plot(x, 9 * x - 30)
10     plt.show()
11 
12 def duoyuan(data,x,y):
13     LineR = LinearRegression()
14     LineR.fit(x.reshape(-1, 1), y)
15     lr = LinearRegression()
16     lr.fit(data, y)
17     lr.coef_  #斜率
18     w = lr.coef_
19     lr.intercept_#截距
20     b = lr.intercept_
21     y_pred = LineR.predict(x)
22     return y_pred
23 
24 
25 def duoxiangsi():
26     poly = PolynomialFeatures(degree=2)
27     x_poly = poly.fit_transform(x)
28     lp = LinearRegression()  # G构建模型
29     lp.fit(x_poly, y)
30     y_poly_pred = lp.predict(x_poly)
31 
32     plt.scatter(x, y)
33     plt.plot(x, y_poly_pred, 'r')
34     plt.show()
35 
36     lrp = LinearRegression()
37     lrp.fit(x_poly, y)
38     plt.scatter(x, y)
39     plt.scatter(x, y_pred)
40     plt.scatter(x, y_poly_pred)  # 多项回归
41     plt.show()
42 
43 
44 
45 
46 
47 
48 if __name__ == '__main__':
49     boston = load_boston()
50     boston.keys()
51     data = boston.data
52     x = data[:, 5]
53     y = boston.target
54     y_pred = yiyuan(boston,x,y)
55     duoxiangsi()

 

你可能感兴趣的:(回归模型与房价预测)