keras boston_housing数据集学习
目的:预测20世纪70年代中期波士顿郊区房屋价格的中位数
特点:数据点较少,输入数据的每个特征都有不同的取值范围
1.指定gpu,设置显存自动增长
#指定gpu
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
#设置显存自动增长
import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)
2.加载波士顿房价数据
from tensorflow.python.keras.api._v1.keras.datasets import boston_housing
(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
3.对数据进行标准化处理
由于每个特征的特征取值范围不同,我们普遍采用对每个特征做标准化的方式
即对于输入数据的每个特征(输入数据矩阵中的列),减去特征平均值,再除以标准差,这样得到的特征平均值为0,标准差为1
mean = train_data.mean(axis=0)
train_data -= mean
std = train_data.std(axis=0)
train_data /= std
test_data -= mean
test_data /= std
用于测试数据标准化的均值和标准差都是在训练数据上计算得到的。在工作流程中,不能使用在测试数据上计算得到的任何结果,即使是像数据标准化这么简单的事情也不行
mean函数中的参数axis=0表示求每一列的平均,axis=1表示求每一行的平均
4.模型定义
from tensorflow.python.keras import models
from tensorflow.python.keras import layers
def build_model():
model = models.Sequential()
model.add(layers.Dense(64, activation='relu',input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(1))
model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
return model
网络的最后一层只有一个单元,没有激活,是一个线性层。这是标量回归(标量回归是预测单一连续值的回归)的典型设置。
损失函数采用的是mse 损失函数。这是回归问题常用的损失函数。
在训练过程中还监控一个新指标:平均绝对误差(MAE,mean absolute error)。它是预测值与目标值之差的绝对值。
5.k折验证,模型训练
import numpy as np
k = 4
num_val_samples = len(train_data)//k #获取每个分区训练样本的数量
num_epochs = 500 #循环的次数
all_mae_histories = []
for i in range(k): #从0到k-1
print('processing fold #', i)
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:]],
axis=0)
partial_train_targets = np.concatenate(
[train_targets[:i * num_val_samples],
train_targets[(i + 1) * num_val_samples:]],
axis=0)
#构建训练模型(已编译)
model = build_model()
#训练模型
history = model.fit(partial_train_data, partial_train_targets,
validation_data=(val_data,val_targets),epochs=num_epochs,
batch_size=1, verbose=0)
mae_history = history.history['val_mean_absolute_error']
all_mae_histories.append(mae_history)
print(all_mae_histories)
其中model.fit函数的返回值是一个History对象。其History.history属性是连续epoch训练损失和评估值,以及验证集损失和评估值的记录
append()函数用于在列表末尾添加新的对象
6.计算所有轮次中的 K 折验证分数平均值
average_mae_history = [
np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
7.绘制验证分数
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
plt.plot(range(1, len(average_mae_history) + 1), average_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show()
plt.savefig('Validation' + '_labeled.jpg')
8.绘制验证分数(删除前 10 个数据点)
因为纵轴的范围较大,且数据方差相对较大,所以难以看清这张图的规律
- 删除前 10 个数据点,因为它们的取值范围与曲线上的其他点不同
- 将每个数据点替换为前面数据点的指数移动平均值,以得到光滑的曲线
def smooth_curve(points, factor=0.9):
smoothed_points = []
for point in points:
if smoothed_points:
previous = smoothed_points[-1]
smoothed_points.append(previous * factor + point * (1 - factor))
else:
smoothed_points.append(point)
return smoothed_points
smooth_mae_history = smooth_curve(average_mae_history[10:])
plt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation MAE')
plt.show()
plt.savefig('Validation_EMA' + '_labeled.jpg')
指数移动平均值(EMA)是指数移动平均值,是一种趋向类指标,指数移动平均值是以指数式递减加权的移动平均。