今天开始房价预测实战。
问题分析
原始数据是这样,波士顿各个区域的各种人文和地理参数,和对应的这个区域的房价,让我们找出这个参数的规律,从而依据这几个参数来预测这个地方的房价。
数据来源
from sklearn.datasets import load_boston
data = load_boston()
print(data.DESCR)
.. _boston_dataset:
Boston house prices dataset
---------------------------
**Data Set Characteristics:**
:Number of Instances: 506
:Number of Attributes: 13 numeric/categorical predictive. Median Value (attribute 14) is usually the target.
:Attribute Information (in order):
- CRIM per capita crime rate by town
- ZN proportion of residential land zoned for lots over 25,000 sq.ft.
- INDUS proportion of non-retail business acres per town
- CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise)
- NOX nitric oxides concentration (parts per 10 million)
- RM average number of rooms per dwelling
- AGE proportion of owner-occupied units built prior to 1940
- DIS weighted distances to five Boston employment centres
- RAD index of accessibility to radial highways
- TAX full-value property-tax rate per $10,000
- PTRATIO pupil-teacher ratio by town
- B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks by town
- LSTAT % lower status of the population
- MEDV Median value of owner-occupied homes in $1000's
:Missing Attribute Values: None
:Creator: Harrison, D. and Rubinfeld, D.L.
This is a copy of UCI ML housing dataset.
https://archive.ics.uci.edu/ml/machine-learning-databases/housing/
This dataset was taken from the StatLib library which is maintained at Carnegie Mellon University.
The Boston house-price data has been used in many machine learning papers that address regression
problems.
解释一下13个参数的意义
CRIM 犯罪率,应该对房价有影响
ZN 住宅区比例
INDUS 非零售商业面积
CHAS 取值0和1
NOX 一氧化氮浓度
RM 每处居所房间数
AGE 业主自住房比例
DIS 到波士5个顿雇员中心的距离
RAD 告诉公路半径
TAX 上交税率财产
PTRATIO 教师比例
B 黑人的比例
LSTAT 低出身人空
MEDV 房价的平均值单位是千美元
模型选择
这不是个分类问题,因为它输出的结果是连续的数字,而不是离散的类别。所以采用回归问题来解决。
然后我们把数据图表打印出来,看看应该采用线性回归还是使用更加复杂的回归算法。
Keras实现回归算法
搭建模型
第一层:Batchnormal 这个能让每一层在输入的时候都实现归一化,这个很厉害,反正很有用。我之前在想我们现在做的是回归算法,又不是分类,还需要做归一化吗?比较归一化是把数据变成0~1之间的成正太分布的数据。后来实验的结果是,Batchnormal效果非常好用。
同时第一层也是输入层,所以要定义参数input_shape=(13,)
model = Sequential()
model.add(BatchNormalization(input_shape=(13,)))
中间两成
model.add(Dense(32, activation="tanh", name="dense1"))
model.add(Dense(10, activation='relu'))
输出层,因为输出层是连续数字,所以并不需要使用激活函数
model.add(Dense(1, name="dense2"))
优化函数
我们使用的损失函数其实就是mse,算法平方平均值
keras/losses.py里定义是这样的:
def mean_squared_error(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
其实就是预测值和真实值差的平方和,但是这个平均平方差,
还有一个函数是平均绝对值差,能够反映出预测值和真实值之间的真实差值。
def mean_absolute_error(y_true, y_pred):
return K.mean(K.abs(y_pred - y_true), axis=-1)
优化函数选择的是 Adam
最终编译模型的方式就是:
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae'])
print(model.summary())
训练
开始训练,调用模型的fit函数
print('Train...')
num_epochs = 500
history = model.fit(x_train, y_train,
batch_size=32,
epochs=num_epochs)
打印训练过程中loss和mae的变化曲线
plt.plot(history.history['loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.show()
plot_0303_002.png
plt.plot(history.history['mean_absolute_error'])
plt.title('Model MAE')
plt.xlabel('Epochs')
plt.ylabel('MAE')
plt.show()
plot_0303_001.png
评估模型
使用测试集合来评估我们的模型对测试的测试效果,最终结果还是要看mae。
score = model.evaluate(x_test, y_test, batch_size=16)
print(score)
输出为:
[6.867778366687251, 1.9948508552476472]
打印预测值曲线
使用模型对所有的测试集进行预测,然后把预测结果打印出来,并和label进行直观比较。
p_pred = model.predict(x_test)
colors = ['b','g','r','orange']
plt.plot(np.arange(p_pred.shape[0]), y_test[:], c=colors[3], alpha=0.8)
plt.plot(np.arange(p_pred.shape[0]), p_pred[:], c=colors[0], alpha=0.8)
plot_0303_003.png
基本上模拟了原始数据的形状,这个回归的算法我们基本是满意的。











网友评论