python深度学习——前4章简介

Keras 是一个Python 深度学习框架,可以方便地定 义和训练几乎所有类型的深度学习模型。Keras 是一个模型级(model-level)的库,它不处理张量操作、求微分等低层次的运算。相反,它依赖于一个专门的、高度优化的张量库来完成这些运算。
目前,Keras有三个后端实现:TensorFlow 后端、 Theano 后端和微软认知工具包(CNTK,Microsoft cognitive toolkit)后端。通过 TensorFlow(或 Theano、CNTK), Keras 可以在 CPU 和GPU 上无缝运行。在 CPU 上运行 时,TensorFlow 本身封装了一个低层次的张量运算库,叫作Eigen;在GPU 上运行时,TensorFlow 封装了一个高度优化的深度学习运算库,叫作 NVIDIA CUDA 深度神经网络库(cuDNN)。

房价预测实例
预测20 世纪70 年代中期波士顿郊区房屋价格的中位数,已知当时郊区的一些数 据点,比如犯罪率、当地房产税率等。本节用到的数据集与前面两个例子有一个有趣的区别。 它包含的数据点相对较少,只有506 个,分为404 个训练样本和102 个测试样本。输入数据的 每个特征(比如犯罪率)都有不同的取值范围。例如,有些特性是比例,取值范围为0~1;有 的取值范围为 1~12;还有的取值范围为 0~100,等等。

from keras import models
from keras import layers
from keras.datasets import boston_housing
import numpy as np
import matplotlib.pyplot as plt


def build_model():
    # Because we will need to instantiate the same model multiple times,(因为需要将同一个模型多次实例化,)
    # we use a function to construct it.(所以用一个函数来构建模型)
    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


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


if __name__=='__main__':

    (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
    print(train_data.shape, test_data.shape)  # (404, 13),(102, 13)
    # numpy实现标准化,对于输入数据的每个特征(输入数据矩阵中的列),减去特征平均值,再除以标准差,这样得到的特征平均值为 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

    # 由于数据点很少,验证集会非常小(比如大约100 个样本)。因此,验证分数可能会有很大波动,这取决于你所选择的验证集和训练集。
    # 也就是说,验证集的划分方式可能会造成验证分数上有很大的方差,这样就无法对模型进行可靠的评估。
    # 在这种情况下,最佳做法是使用 K 折交叉验证。这种方法将可用数据划分为 K 个分区(K 通常取 4 或 5),实例化 K 个相同的模型,将每个模型在 K-1 个分区上训练,并在剩下的一个分区上进行评估。
    # 模型的验证分数等于 K 个验证分数的平均值。
    k = 4
    num_val_samples = len(train_data) // k
    num_epochs = 100
    all_scores = []
    for i in range(k):
        print('processing fold #', i)
        # Prepare the validation data: data from partition # k(准备验证数据:第 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]

        # Prepare the training data: data from all other partitions(准备训练数据:其他所有分区的数据)
        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)

        # Build the Keras model (already compiled)(构建 Keras 模型(已编译))
        model = build_model()
        # Train the model (in silent mode, verbose=0)(训练模型(静默模式,)
        model.fit(partial_train_data, partial_train_targets,
                  epochs=num_epochs, batch_size=1, verbose=0)
        # Evaluate the model on the validation data(在验证数据上评估模型)
        val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0)
        all_scores.append(val_mae)


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

        # Prepare the training data: data from all other partitions(准备训练数据:其他所有分区的数据)
        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)

        # Build the Keras model (already compiled)(构建 Keras 模型(已编译))
        model = build_model()
        # Train the model (in silent mode, verbose=0)(训练模型(静默模式,verbose=0))
        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)
    # 计算每个轮次中所有折 MAE 的平均值
    average_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
    # 绘图观察
    plt.plot(range(1, len(average_mae_history) + 1), average_mae_history)
    plt.xlabel('Epochs')
    plt.ylabel('Validation MAE')
    plt.show()
    # 重新绘图观察
    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()

    # 模型调参(除了轮数,还可以调节隐藏层大小),观察在测试集上的性能
    # Get a fresh, compiled model.
    model = build_model()
    # Train it on the entirety of the data.
    model.fit(train_data, train_targets,
              epochs=80, batch_size=16, verbose=0)
    test_mse_score, test_mae_score = model.evaluate(test_data, test_targets)
    print(test_mse_score)




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值