1. 导入boston房价数据集。
1
2
3
4
|
from
sklearn.datasets
import
load_boston
boston
=
load_boston()
boston.keys()
print
(boston.data)
|
2. 一元线性回归模型,建立一个变量与房价之间的预测模型,并图形化显示。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import
pandas as pd
#导包
pd.DataFrame(boston.data)
#预处理获取斜率
from
sklearn.linear_model
import
LinearRegression
LineR
=
LinearRegression()
LineR.fit(x.reshape(
-
1
,
1
),y)
w
=
LineR.coef_
#图形化显示
x
=
data[:,
5
]
y
=
boston.target
import
matplotlib.pyplot as plt
plt.scatter(x,y)
plt.plot(x,w
*
x
+
b,
'G'
)
plt.show()
|
3. 多元线性回归模型,建立13个变量与房价之间的预测模型,并检测模型好坏,并图形化显示检查结果。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
from
sklearn.linear_model
import
LinearRegression
lineR
=
LinearRegression()
lineR.fit(boston.data,y)
w
=
lineR.coef_
b
=
lineR.intercept_
import
matplotlib.pyplot as plt
x
=
boston.data[:,
12
].reshape(
-
1
,
1
)
y
=
boston.target
plt.figure(figsize
=
(
10
,
6
))
#指定显示图大小
plt.scatter(x,y)
from
sklearn.linear_model
import
LinearRegression
lineR
=
LinearRegression()
lineR.fit(x,y)
y_pred
=
lineR.predict(x)
plt.plot(x,y_pred,
'G'
)
print
(lineR.coef_,lineR.intercept_)
plt.show()
|
4. 一元多项式回归模型,建立一个变量与房价之间的预测模型,并图形化显示。
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
|
xx
=
data[:,
12
].reshape(
-
1
,
1
)
plt.scatter(xx,y)
plt.show()
lr12
=
LinearRegression()
lr12.fit(xx,y)
w
=
lr12.coef_
b
=
lr12.intercept_
plt.scatter(xx,y)
plt.plot(xx,w
*
xx
+
b,
'G'
)
plt.show()
from
sklearn.preprocessing
import
PolynomialFeatures
p
=
PolynomialFeatures()
p.fit(xx)
x_poly
=
p.transform(xx)
lrp
=
LinearRegression()
lrp.fit(x_poly,y)
lrp.coef_
lrp.intercept_
lrp
=
LinearRegression()
lrp.fit(x_poly,y)
y_poly
=
lrp.predict(x_poly)
plt.scatter(xx,y)
plt.plot(xx,w
*
xx
+
b,
'G'
)
plt.scatter(xx,y_poly)
plt.show()
lrp.coef_
|