使用飛漿實現波士頓房價預測

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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章