使用飞浆实现波士顿房价预测

import paddle.fluid as fluid
import paddle
import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib


def menu():
    print("*" * 100)
    print("1.数据处理")
    print("2.模型设计")
    print("3.训练配置")
    print("4.训练过程")
    print("5.保存并测试")
    print("*" * 100)


def draw_train_process(iters, train_costs):
    title = "training cost"
    plt.title(title, fontsize=24)
    plt.xlabel("iter", fontsize=14)
    plt.ylabel("cost", fontsize=14)
    plt.plot(iters, train_costs, color='red', label='training cost')
    plt.grid()
    # plt.show()
    matplotlib.use('Agg')
    plt.savefig('./1.png')


# 绘制真实值和预测值对比图
def draw_infer_result(groud_truths, infer_results):
    title = 'Boston'
    plt.title(title, fontsize=24)
    x = np.arange(1, 20)
    y = x
    plt.plot(x, y)
    plt.xlabel('ground truth', fontsize=14)
    plt.ylabel('infer result', fontsize=14)
    plt.scatter(groud_truths, infer_results, color='green', label='training cost')
    plt.grid()
    matplotlib.use('Agg')
    # plt.show()
    plt.savefig('./2.png')


if __name__ == '__main__':
    menu()
    # matplotlib.use('TkAgg')

    BUF_SIZE = 500
    BATCH_SIZE = 20

    # 1.数据读取.
    # 用于训练的数据提供器,每次从缓存中随机读取批次大小的数据
    train_reader = paddle.batch(
        paddle.reader.shuffle(paddle.dataset.uci_housing.train(),
                              buf_size=BUF_SIZE),
        batch_size=BATCH_SIZE)
    # 用于测试的数据提供器,每次从缓存中随机读取批次大小的数据
    test_reader = paddle.batch(
        paddle.reader.shuffle(paddle.dataset.uci_housing.test(),
                              buf_size=BUF_SIZE),
        batch_size=BATCH_SIZE)

    # 2.网络配置
    # 2.1网络搭建
    # 定义张量变量x,表示13维的特征值
    x = fluid.layers.data(name='x', shape=[13], dtype='float32')
    # 定义张量y,表示目标值
    y = fluid.layers.data(name='y', shape=[1], dtype='float32')
    # 定义一个简单的线性网络,连接输入和输出的全连接层
    # input:输入tensor;
    # size:该层输出单元的数目
    # act:激活函数
    y_predict = fluid.layers.fc(input=x, size=1, act=None)

    # 2.2 定义损失函数
    cost = fluid.layers.square_error_cost(input=y_predict, label=y)  # 求一个batch的损失值
    avg_cost = fluid.layers.mean(cost)  # 对损失值求平均值

    # 2.3 定义优化函数
    optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.001)
    opts = optimizer.minimize(avg_cost)
    test_program = fluid.default_main_program().clone(for_test=True)

    # 3.模型训练和模型评估
    # 3.1创建Executor
    use_cuda = False  # use_cuda为False,表示运算场所为CPU;use_cuda为True,表示运算场所为GPU
    place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace()
    exe = fluid.Executor(place)  # 创建一个Executor实例exe
    exe.run(fluid.default_startup_program())  # Executor的run()方法执行startup_program(),进行参数初始化

    # 3.2定义输入数据维度
    feeder = fluid.DataFeeder(place=place, feed_list=[x, y])  # feed_list:向模型输入的变量表或变量表名

    # 3.3定义绘制训练过程的损失值变化趋势的方法draw_train_process
    iter = 0
    iters = []
    train_costs = []

    # 3.4训练并保存模型
    EPOCH_NUM = 50
    model_save_dir = "./work/fit_a_line.inference.model"

    for pass_id in range(EPOCH_NUM):  # 训练EPOCH_NUM轮
        # 开始训练并输出最后一个batch的损失值
        train_cost = 0
        for batch_id, data in enumerate(train_reader()):  # 遍历train_reader迭代器
            train_cost = exe.run(program=fluid.default_main_program(),  # 运行主程序
                                 feed=feeder.feed(data),  # 喂入一个batch的训练数据,根据feed_list和data提供的信息,将输入数据转成一种特殊的数据结构
                                 fetch_list=[avg_cost])
            if batch_id % 40 == 0:
                print("Pass:%d, Cost:%0.5f" % (pass_id, train_cost[0][0]))  # 打印最后一个batch的损失值
            iter = iter + BATCH_SIZE
            iters.append(iter)
            train_costs.append(train_cost[0][0])

        # 开始测试并输出最后一个batch的损失值
        test_cost = 0
        for batch_id, data in enumerate(test_reader()):  # 遍历test_reader迭代器
            test_cost = exe.run(program=test_program,  # 运行测试cheng
                                feed=feeder.feed(data),  # 喂入一个batch的测试数据
                                fetch_list=[avg_cost])  # fetch均方误差
        print('Test:%d, Cost:%0.5f' % (pass_id, test_cost[0][0]))  # 打印最后一个batch的损失值

    # 保存模型
    # 如果保存路径不存在就创建
    if not os.path.exists(model_save_dir):
        os.makedirs(model_save_dir)
    print('save models to %s' % (model_save_dir))
    # 保存训练参数到指定路径中,构建一个专门用预测的program
    fluid.io.save_inference_model(model_save_dir,  # 保存推理model的路径
                                  ['x'],  # 推理(inference)需要 feed 的数据
                                  [y_predict],  # 保存推理(inference)结果的 Variables
                                  exe)  # exe 保存 inference model
    draw_train_process(iters, train_costs)
    # 4.模型预测
    # 4.1创建预测用的Executor
    infer_exe = fluid.Executor(place)  # 创建推测用的executor
    inference_scope = fluid.core.Scope()  # Scope指定作用域
    # 4.2可视化真实值与预测值方法定义
    infer_results = []
    groud_truths = []

    # 4.3开始预测
    with fluid.scope_guard(inference_scope):  # 修改全局/默认作用域(scope), 运行时中的所有变量都将分配给新的scope。
        # 从指定目录中加载 推理model(inference model)
        [inference_program,  # 推理的program
         feed_target_names,  # 需要在推理program中提供数据的变量名称
         fetch_targets] = fluid.io.load_inference_model(  # fetch_targets: 推断结果
            model_save_dir,  # model_save_dir:模型训练路径
            infer_exe)  # infer_exe: 预测用executor
        # 获取预测数据
        infer_reader = paddle.batch(paddle.dataset.uci_housing.test(),  # 获取uci_housing的测试数据
                                    batch_size=200)  # 从测试数据中读取一个大小为200的batch数据
        # 从test_reader中分割x
        test_data = next(infer_reader())
        test_x = np.array([data[0] for data in test_data]).astype("float32")
        test_y = np.array([data[1] for data in test_data]).astype("float32")
        results = infer_exe.run(inference_program,  # 预测模型
                                feed={feed_target_names[0]: np.array(test_x)},  # 喂入要预测的x值
                                fetch_list=fetch_targets)  # 得到推测结果

        print("infer results: (House Price)")
        for idx, val in enumerate(results[0]):
            print("%d: %.2f" % (idx, val))
            infer_results.append(val)
        print("ground truth:")
        for idx, val in enumerate(test_y):
            print("%d: %.2f" % (idx, val))
            groud_truths.append(val)
        draw_infer_result(groud_truths, infer_results)

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 MATLAB 实现波士顿房价预测可以分为以下步骤: 1. 导入数据。在 MATLAB 中,可以使用 `readtable` 函数读取数据,并将其转换为 `table` 数据类型。 2. 数据预处理。对于波士顿房价数据,可以对数据进行标准化处理,使各个特征的数据范围相同。可以使用 `mapminmax` 函数进行标准化处理。另外,还需要将数据分为训练集和测试集。 3. 构建 BP 神经网络模型。可以使用 `feedforwardnet` 函数构建 BP 神经网络模型,并设置隐藏层的神经元数目。然后,使用 `train` 函数对模型进行训练。 4. 模型评估。使用测试集对训练好的模型进行评估,可以计算出均方误差(MSE)和均方根误差(RMSE)等指标,评估模型的预测准确度。 5. 预测。使用训练好的 BP 神经网络模型对新的房价数据进行预测。 下面是 MATLAB 代码示例: ```matlab % 导入数据 data = readtable('boston.csv'); % 数据预处理 x = table2array(data(:, 1:end-1)); % 特征数据 y = table2array(data(:, end)); % 标签数据 [x, ps] = mapminmax(x'); % 标准化处理 y = y'; % 转换为行向量 [train_x,train_y,test_x,test_y] = dividerand(x,y,0.7,0.3); % 分为训练集和测试集 % 构建 BP 神经网络模型 hiddenLayerSize = 10; net = feedforwardnet(hiddenLayerSize); net = train(net, train_x, train_y); % 模型评估 pred_y = net(test_x); mse = mean((pred_y - test_y).^2); rmse = sqrt(mse); % 预测 new_x = [0.02731 0 7.07 0 0.469 6.421 78.9 4.9671 2 242 17.8 396.9 9.14]; % 新的房价数据 new_x = mapminmax.apply(new_x', ps); % 标准化处理 pred_y = net(new_x); ``` 需要注意的是,BP 神经网络模型的训练需要大量的数据和时间,并且需要调整隐藏层神经元数目等参数,以获得更好的预测效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值