深度学习3:波士顿房价预测(2)

转载:https://blog.csdn.net/qq_40195614/article/details/90270287

我们接着上一篇去讲。

代码实例分析

all_scores
np.mean(all_scores)
  • 1
  • 2

可以分别查看所谓的分数,其实就是上一节提到的平均绝对误差,输出的结果是2.6到3.2左右,换句话说就是预测与实际的差别在三千美元左右,看看房价也就几万美元,可以说这个差别是有些大的。
为了让结果更准确,我们再训练,这个时候把训练的轮次变成500.在这之前先要做的是清理内存。

from keras import backend as K

K.clear_session()

之后再训练:

num_epochs = 500
all_mae_histories = []
for i in range(k):
    print('processing fold #', i)
    # Prepare the validation data: data from partition # k
    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)

这部分的代码和上一节的相似性非常高,我就不着重去分析了。

average_mae_history = [
    np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]

现在计算出每一轮得分的平均值,为我们后面画图做准备

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()

这段代码就可以画出随着轮次的增加,得到的分数的变化,效果如下:

这里可以看到很直观的变化,但是可能y轴范围太大导致图像看得不是很清楚,推荐的方法很简单,就是去掉一部分前面的点,而且折线看得不太舒服,就可以用指数移动平均值的方法来优化图片。

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()

这就是实现方法了,图会更直观一些。但是不论怎么画图,我们都清楚地认识到这个方法也确实不太靠谱,因为随着轮次的增加,分数只会在3左右波动,可见轮次增加之后误差依然很大。
这次就分析到这里

原文地址:https://www.cnblogs.com/demo-lv/p/12687194.html