当前位置:网站首页>波士顿房价预测
波士顿房价预测
2022-08-10 14:17:00 【ㄣ知冷煖*】
目录
前言
对于波士顿房价数据集的预测实战一、波士顿房价预测实战
1-1、数据集介绍&数据集导入&分割数据集
from keras.datasets import boston_housing
# 预测20世纪70年代中期波士顿郊区房屋价格的中位数
# 数据点比较少,只有506个,分为404个训练样本和102个测试样本
# 输入数据的每个特征都有不同的取值范围。
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
# 查看训练数据
输出:可以看到数据量较少,数据维度是13维的。
1-2、数据标准化
def normalize(train_data):
"""
数据标准化
"""
mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
return mean, std, train_data
mean, std, train_data = normalize(train_data)
# 注意:测试数据标准化的均值和标准差都必须是在训练数据上计算得到的。
test_data -= mean
test_data /= std
# 查看标准化后的数据
输出:
1-3、构建网络
import keras
def build_model():
"""
搭建网络
mse:损失函数采用均方误差,即mse。
mae:训练过程中采用的监控指标,mae,即平均绝对误差。
"""
model = keras.models.Sequential()
model.add(keras.layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
model.add(keras.layers.Dense(64, activation='relu'))
model.add(keras.layers.Dense(1))
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
return model
1-4、K折交叉验证&取出所有的训练损失、训练平均绝对误差、验证损失、验证平均绝对误差
# 因为在本例子中,数据较少,选择不同的训练集和验证集,验证分数会有较大的波动,这种情况下最好使用K折交叉验证,最后求K个验证分数的平均值。
import numpy as np
k=4
num_epochs = 500
all_loss = []
all_val_loss = []
all_mae = []
all_val_mae = []
num_val_samples = len(train_data) // k
for i in range(k):
print('-'*20+str(i)+' Start'+'-'*20)
val_data = train_data[i*num_val_samples:(i+1)*num_val_samples]
val_targets = train_targets[i*num_val_samples:(i+1)*num_val_samples]
partial_train_data = np.concatenate((train_data[:i*num_val_samples],train_data[(i+1)*num_val_samples:]))
partial_train_targets = np.concatenate((train_targets[:i*num_val_samples],train_targets[(i+1)*num_val_samples:]))
model = build_model()
# batch_size: 一次训练所选取的样本数。
history = model.fit(partial_train_data, partial_train_targets, epochs=num_epochs, batch_size=1, verbose=0,
validation_data=(val_data, val_targets))
all_loss.append(history.history['loss'])
all_val_loss.append(history.history['val_loss'])
all_mae.append(history.history['mae'])
all_val_mae.append(history.history['val_mae'])
print('-'*20+str(i)+' End'+'-'*20)
1-5、计算平均mae&绘制验证mae分数&绘制验证loss分数
# 回归问题常常使用的损失函数是均方误差
# 常用的回归指标是平均绝对误差,即MAE
# 如果可以用的数据很少,则可以使用K折交叉验证可靠的评估模型
# 如果可用的训练数据较少,则尽量使用较少的隐藏层(即只有一个或者两个隐藏层),这样可以避免过拟合。
# 如果数据被分为多个类别,那么中间层过小可能会导致信息瓶颈
# all_val_mae: (4,500)
average_mae_history = [np.mean([x[i] for x in all_val_mae]) for i in range(num_epochs)]
import plotly.express as px
import plotly.graph_objects as go
fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=list(range(1, len(average_mae_history)+1)), y=average_mae_history,
mode='lines',
name='average_mae_history'))
fig.show()
输出:
前10天数据拟合落差太大,无法对10天后的数据进行有效的观察。所以从第10天开始输出:
import plotly.express as px
import plotly.graph_objects as go
fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=list(range(10, len(average_mae_history)+1)), y=average_mae_history[10:],
mode='lines',
name='average_mae_history'))
fig.show()
输出:
绘制验证集loss:
average_mse_history = [np.mean([x[i] for x in all_val_loss]) for i in range(num_epochs)]
import plotly.express as px
import plotly.graph_objects as go
fig = go.Figure()
# Add traces
fig.add_trace(go.Scatter(x=list(range(10, len(average_mse_history)+1)), y=average_mse_history[10:],
mode='lines',
name='average_mse_history'))
fig.show()
输出:
1-6、找到最好的训练轮次&批次
# 根据1-5的探索可知,大概在40轮次到90轮次的损失是最低的,所以我们选择40-90轮次进行调参。
for i in range(40, 91):
for j in [16, 32, 64]:
model = build_model()
model.fit(train_data, train_targets, epochs=i, batch_size=j, verbose=0)
test_mse_score,test_mae_score = model.evaluate(test_data, test_targets)
print('轮次:{
}, 一次训练所取的样本数:{
}, mse: {
}, mae: {
}'.format(i, j, test_mse_score, test_mae_score))
# 这里的mae和loss每次训练都会有误差,所以大概选40-90轮次这个范围就ok,不用太纠结具体数值。
二、调参总结
调参总结:
1、训练轮次:房价预测是较为复杂的模型,先选择较大的轮次,这里设置为500,观察数据在验证集上的表现,训练是为了拟合一般数据,所以当模型在验证集上准确率下降时,那就不要再继续训练了。在验证集上大概在40轮次到90轮次的损失是最低的,所以选择这个范围内的训练轮次。
2、隐藏层数设置:同隐藏单元的设置规则,数据简单,则设置的层数较少,如果数据复杂,可以多加几层来观察数据的整体表现。
3、Trick:带有打乱数据的重复K折验证,如果可用的数据相对较少,而你又需要尽可能精确地评估模型,那么可以选择带有打乱数据的重复K折验证(当然这里的话这个Trick是不行的!这里是时间序列数据,是不可以被打乱的。)
4、尝试调节模型的其他方法:添加dropout、添加L1或者L2正则化、反复做特征工程(添加或者是删除没有信息量的特征)
总结
周二早上,昨天睡了很久很久,做了一个很长很长的梦。
边栏推荐
- leetcode 739. Daily Temperatures 每日温度(中等)
- malloc 函数详解
- 学习日记9
- PHP judges whether the file has content, and if there is no content, copy another file to write
- 1W word detailed thread local storage ThreadLocal
- 开源SPL消灭数以万计的数据库中间表
- Error: Rule can only have one resource source (provided resource and test + include + exclude)
- laravel 抛错给钉钉
- Matlab画分段函数「建议收藏」
- Lack of comparators, op amps come to the rescue!(Op amp is recorded as a comparator circuit)
猜你喜欢
池化技术有多牛?来,告诉你阿里的Druid为啥如此牛逼!
laravel 抛错给钉钉
2022年中国软饮料市场洞察
Existing in the rain of PFAS chemical poses a threat to the safety of drinking water
Using data intelligence, Amazon cloud technology helps companies build endogenous brand growth
AWS Security Fundamentals
正则表达式(包含各种括号,echo,正则三剑客以及各种正则工具)
王学岗—————————哔哩哔哩直播-手写哔哩哔哩硬编码录屏推流(硬编)(26节课)
发送post请求前台无法获取数据
2022年网络安全培训火了,缺口达95%,揭开网络安全岗位神秘面纱
随机推荐
win2012安装Oraclerac失败
Summary of tensorflow installation stepping on the pit
学习日记8
“国资云”和“国家云”能给市场带来怎样的变革?
PHP 判断文件是否有内容,没有内容则复制另一个文件写入
tensorflow安装踩坑总结
统信 UOS V20 专业版(1050update2)发布:文件共享、全局搜索等优化
Lithium battery technology
C#实现访问OPC UA服务器
Open source SPL wipes out tens of thousands of database intermediate tables
缺少比较器,运放来救场!(运放当做比较器电路记录)
The a-modal in the antd component is set to a fixed height, and the content is scrolled and displayed
快速了解大端模式和小端模式
Flask框架——基于Celery的后台任务
领域驱动实践总结(基本理论总结与分析V+架构分析与代码设计+具体应用设计分析)
【POI 2008, BLO】割点
发送post请求前台无法获取数据
数学建模学习视频及资料集(2022.08.10)
IT小白怎么系统的php学习
力扣解法汇总640-求解方程