一、要求
boston 房价数据是机器学习中著名的基础数据集,包含 506 条记录,每条记录包含房
屋的 13 条属性,房价信息属性 MEDV 在 boston.target 中,具体(翻译成中文) 可通过如下语句查看:
print(boston.DESCR)
各属性的中文解释如下:
- CRIM 城镇人均犯罪率
- ZN 占地面积超过 25,000 平方尺的住宅用地比例
- INDUS 城镇中非商业用地比例
- CHAS Charles River 虚拟变量(如果边界是河流则为 1;否则为 0)
- NOX 一氧化氮浓度
- RM 每栋住宅平均房间数
- AGE 1940 年前建成的自住房屋比例
- DIS 距五个波士顿就业中心的加权距离
- RAD 距离高速公路的便利指数- TAX 每 10,000 美元的全额房产税率
- PTRATIO 城镇中学生教师比例
- B 城镇中黑人比例
- LSTAT 人口中低收入阶层比例
- MEDV 自住房房价中位数
完成如下数据处理和分析任务:
(1)在一张画布上,画出每个变量与房价变化的散点图,并详细分析各个变量和房价
之间的关系。
(2)计算变量和房价的相关系数(相关系数的函数 df.corr())。
(3)建立所有变量和房价的线性回归模型,写出模型表达式,并分析模型的显著性。
(4)将系数检验结果不显著的变量去掉,重新建立线性模型。
(5)选择与房价的相关系数大于等于 0.5 的变量,作为模型的自变量,房价作为因变
量,建立线性回归模型,并将房价预测值和真实值绘制成折线图。
二、代码
from
sklearn
import
datasets
import
pandas
as
pd
import
matplotlib
.
pyplot
as
plt
#
from
scipy
.
misc
import
factorial 依赖scipy 而且为
1.2
.0
版本
#此文件依赖pillow
boston
=
pd
.
read_csv
(
'./dataset/boston_house.csv'
)
df
=
pd
.
DataFrame
(
boston
)
#
print
(
df
.
iloc
[
:
,
-
1
]
)
#相关系数大于
0.5
x_has
=
[
]
y_predict
=
[
]
plt
.
figure
(
1
)
#第一题
plt
.
rcParams
[
'font.sans-serif'
]
=
'SimHei'
plt
.
rcParams
[
'axes.unicode_minus'
]
=
False
for
i
in
range
(
13
)
:
plt
.
subplot
(
7
,
2
,
i
+
1
)
plt
.
scatter
(
df
.
iloc
[
:
,
i
]
,
df
.
iloc
[
:
,
-
1
]
,
marker
=
'o'
,
c
=
'g'
)
# x
,
y
,
,
green
#第二题
#
print
(
type
(
df
.
columns
[
1
]
)
)
dfi
=
df
[
[
df
.
columns
[
i
]
,
df
.
columns
[
-
1
]
]
]
print
(
'\n'
,
dfi
.
corr
(
)
,
dfi
.
corr
(
)
.
iloc
[
0
,
1
]
,
'\n'
)
#
print
(
dfi
.
corr
(
)
.
iloc
[
0
,
1
]
)
#第三题
import
numpy
as
np
from
sklearn
.
linear_model
import
LinearRegression
x_linear
=
df
.
iloc
[
:
,
i
]
.
values
.
reshape
(
-
1
,
1
)
#将DataFrame转为array格式,通过values 属性
y_linear
=
df
.
iloc
[
:
,
-
1
]
.
values
.
reshape
(
-
1
,
1
)
##
reshape
(
-
1
,
1
)
功能
#
print
(
x_linear
,
type
(
x_linear
)
)
lreg
=
LinearRegression
(
)
lreg
.
fit
(
x_linear
,
y_linear
)
message0
=
'一元线性回归方程为: '
+
'\ty'
+
'='
+
str
(
lreg
.
intercept_
[
0
]
)
+
' + '
+
str
(
lreg
.
coef_
[
0
]
[
0
]
)
+
'*x'
import
scipy
.
stats
as
stats
n
=
len
(
x_linear
)
y_prd
=
lreg
.
predict
(
x_linear
)
if
dfi
.
corr
(
)
.
iloc
[
0
,
1
]
>
0.5
:
x_has
.
append
(
i
)
y_predict
.
append
(
y_prd
)
Regression
=
sum
(
(
y_prd
-
np
.
mean
(
y_linear
)
)
**
2
)
# 回归
Residual
=
sum
(
(
y_linear
-
y_prd
)
**
2
)
# 残差
R_square
=
Regression
/
(
Regression
+
Residual
)
# 相关性系数
R
^
2
F
=
(
Regression
/
1
)
/
(
Residual
/
(
n
-
2
)
)
#
F
分布
#取a
=
0.05
if
stats
.
pearsonr
(
x_linear
,
y_linear
)
[
1
]
[
0
]
<
0.05
:
ms1_1
=
'显著'
else
:
ms1_1
=
'不显著'
message1
=
'显著性检测(p值检测):'
+
str
(
stats
.
pearsonr
(
x_linear
,
y_linear
)
[
1
]
[
0
]
)
+
ms1_1
print
(
message0
,
'\n'
,
message1
)
#第四题
print
(
x_has
,
y_predict
)
plt
.
show
(
)
#第五题
plt
.
figure
(
2
)
for
i
in
range
(
len
(
x_has
)
)
:
plt
.
plot
(
df
.
iloc
[
:
,
-
1
]
.
values
,
marker
=
'o'
,
c
=
'g'
)
plt
.
plot
(
y_predict
[
i
]
,
marker
=
'o'
,
c
=
'r'
)
plt
.
show
(
)