from keras.datasets import boston_housing
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSprop
import numpy as np
(train_data,train_target),(test_data,test_target) = boston_housing.load_data()
#标准化数据
mean = train_data.mean(axis = 0)
std = train_data.std(axis = 0)
train_data = (train_data - mean)/std #标准化训练集
test_data = (test_data - mean)/std #标准化测试集
#更标准一点的操作
#应该是将train_data,test_data叠加在一起求mean,std
#构建神经网络
def build_model():
model = Sequential()
#input layer
model.add(Dense(64,input_shape= (13,),activation = "relu"))
#hidden layer
model.add(Dense(64,activation = "relu"))
#output layer
model.add(Dense(1))
#输出的数据是连续的,不需要激活函数
#编译模型:优化器,损失函数
model.compile(optimizer = RMSprop(),loss = "mse",metrics = ['mae'])
return model
#交叉验证
#4折,404刚好可以被4整除
k = 4
# 4 * num_val_samples = len(train_data)
num_val_samples = len(train_data) // k
#训练周期:100
num_epochs = 100
#储存每个验证集的分数
all_scores = []
#交叉验证的循环
for i in range(k):
val_data = train_data[i * num_val_samples : (i + 1) * num_val_samples]
val_targets = train_target[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 : ]],
axis = 0
#沿着横轴连接
)
partial_train_targets = np.concatenate(
[train_target[: i * num_val_samples],
train_target[(i + 1) * num_val_samples : ]],
axis = 0
#沿着横轴连接
)
#每经过一折,都要构建一次神经网络
model = build_model()
#输出数据太多(100 * 101 * 4),不让它输出,所以verbose = 0
model.fit(partial_train_data,partial_train_targets,epochs = num_epochs,batch_size = 1,verbose = 0)
val_mse,val_mae = model.evaluate(val_data,val_targets,verbose = 0)
all_scores.append(val_mae)
print ("第",i+1,"折,MSE:",val_mse,"MAE:",val_mae)
np.mean(all_scores)
model = build_model()
model.fit(train_data,train_target,epochs = 80,batch_size = 16,verbose = 0)
#导入测试数据
test_mse,test_mae = model.evaluate(test_data,test_target)
用Keras构建多层感知器进行波士顿房价预测
该程序应用到了交叉验证
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦