首页 > 其他分享 >使用神经网络实现波士顿房价的预测

使用神经网络实现波士顿房价的预测

时间:2023-05-15 17:33:33浏览次数:42  
标签:plt keras 房价 神经网络 train mae test import 波士顿

主要目的:

1、从keras的数据集中加载波士顿房价数据,注意需要做数据的标准化。

2、构建一个神经网络模型,并使用划分好的训练集数据训练模型,使用划分好的测试集的数据验证模型,训练迭代100次(不需要K折验证)。

3、获取训练过程中的训练mae值、验证mae值,并使用matplotlib来绘制mae值变化曲线,要求模型验证的mae值达到4.0以下。

 

1、导入相关包

import tensorflow as tf

from tensorflow.python import keras

from keras.datasets import boston_housing

from keras import layers

from keras.models import Sequential

from keras.layers import Dense

import matplotlib.pyplot as plt

 

2、加载数据,并完成数据的标准化

#加载数据

(x_train, y_train), (x_test, y_test) = boston_housing.load_data()

 

3、数据预处理

# 数据标准化

x_mean = x_train.mean(axis=0)

x_std = x_train.std(axis=0)

x_train -= x_mean

x_train /= x_std

 

x_test -= x_mean

x_test /= x_std

 

4、构建深度学习模型

# 模型的定义

from keras.models import Sequential

from keras.layers import Dense

model = Sequential()

model.add(Dense(64,activation = 'relu',input_shape=(x_train.shape[1],)))

model.add(Dense(64,activation = 'relu'))

model.add(Dense(1))

model.compile(optimizer='rmsprop',loss='mse', metrics=['mae'])

 

5、训练模型

# 训练模型

history = model.fit(x_train, y_train, batch_size=8,validation_data=(x_test, y_test), epochs=100)

 

6、获取历史mae数据,绘制mae值变化折线图

       test_mae_score,test_mae_score=model.evaluate(x_test,y_test)

test_mae_score

 

# 绘制精度变化曲线

import matplotlib.pyplot as plt

plt.rcParams['font.sans-serif']=['SimHei']

plt.rcParams['axes.unicode_minus']=False

history_dict = history.history

print(history_dict.keys())

mae = history_dict['mae']

val_mae = history_dict['val_mae']

epochs = range(1,len(val_mae) + 1)

plt.plot(epochs,mae,color='red', label="训练mae")

plt.plot(epochs,val_mae,color='green',label="验证mae")

plt.legend(loc='center')

plt.show()

 结果分析

  使用神经网络实现波士顿房价的预测,主要是使用回归问题来进行操作,来完成对数据的预测,需要注意获取数据后要进行数据处理,例如数据格式的转换。在使用可视化时在尽量让图显得直观数据对比明显。在模型的训练时,需要注意改变batch_size的值,来减小test_mae_score。

标签:plt,keras,房价,神经网络,train,mae,test,import,波士顿
From: https://www.cnblogs.com/beichens/p/17402560.html

相关文章