【深度學(xué)習(xí)】PaddlePaddle計算機視覺項目:波士頓房價預(yù)測

波士頓房價預(yù)測模型琢唾,是經(jīng)典的線性回歸模型。記得吳恩達深度學(xué)習(xí)課程的第一課就是講波士頓房價預(yù)測模型桅滋,入門的項目慧耍。PaddlePaddle同樣有這個項目,可運行丐谋。記錄一下。

經(jīng)典的線性回歸模型主要用來預(yù)測一些存在著線性關(guān)系的數(shù)據(jù)集煌珊『爬回歸模型可以理解為:存在一個點集,用一條曲線去擬合它分布的過程定庵。如果擬合曲線是一條直線吏饿,則稱為線性回歸。如果是一條二次曲線蔬浙,則被稱為二次回歸猪落。線性回歸是回歸模型中最簡單的一種。 本教程使用PaddlePaddle建立起一個房價預(yù)測模型笨忌。

在線性回歸中:

(1)假設(shè)函數(shù)是指,用數(shù)學(xué)的方法描述自變量和因變量之間的關(guān)系俱病,它們之間可以是一個線性函數(shù)或非線性函數(shù)官疲。 在本次線性回顧模型中,我們的假設(shè)函數(shù)為 Y’= wX+b 亮隙,其中途凫,Y’表示模型的預(yù)測結(jié)果(預(yù)測房價),用來和真實的Y區(qū)分溢吻。模型要學(xué)習(xí)的參數(shù)即:w,b维费。

(2)損失函數(shù)是指,用數(shù)學(xué)的方法衡量假設(shè)函數(shù)預(yù)測結(jié)果與真實值之間的誤差。這個差距越小預(yù)測越準(zhǔn)確犀盟,而算法的任務(wù)就是使這個差距越來越小而晒。 建立模型后,我們需要給模型一個優(yōu)化目標(biāo)且蓬,使得學(xué)到的參數(shù)能夠讓預(yù)測值Y’盡可能地接近真實值Y欣硼。這個實值通常用來反映模型誤差的大小。不同問題場景下采用不同的損失函數(shù)恶阴。 對于線性模型來講诈胜,最常用的損失函數(shù)就是均方誤差(Mean Squared Error, MSE)冯事。

(3)優(yōu)化算法:神經(jīng)網(wǎng)絡(luò)的訓(xùn)練就是調(diào)整權(quán)重(參數(shù))使得損失函數(shù)值盡可能得小焦匈,在訓(xùn)練過程中,將損失函數(shù)值逐漸收斂昵仅,得到一組使得神經(jīng)網(wǎng)絡(luò)擬合真實模型的權(quán)重(參數(shù))缓熟。所以,優(yōu)化算法的最終目標(biāo)是找到損失函數(shù)的最小值摔笤。而這個尋找過程就是不斷地微調(diào)變量w和b的值够滑,一步一步地試出這個最小值。 常見的優(yōu)化算法有隨機梯度下降法(SGD)吕世、Adam算法等等彰触。

首先導(dǎo)入必要的包,分別是:

paddle.fluid--->PaddlePaddle深度學(xué)習(xí)框架

numpy---------->python基本庫命辖,用于科學(xué)計算

os------------------>python的模塊况毅,可使用該模塊對操作系統(tǒng)進行操作

matplotlib----->python繪圖庫,可方便繪制折線圖尔艇、散點圖等圖形

In[1]

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

Step1:準(zhǔn)備數(shù)據(jù)

(1)uci-housing數(shù)據(jù)集介紹

數(shù)據(jù)集共506行,每行14列尔许。前13列用來描述房屋的各種信息,最后一列為該類房屋價格中位數(shù)终娃。

PaddlePaddle提供了讀取uci_housing訓(xùn)練集和測試集的接口味廊,分別為paddle.dataset.uci_housing.train()和paddle.dataset.uci_housing.test()。

(2)train_reader和test_reader

paddle.reader.shuffle()表示每次緩存BUF_SIZE個數(shù)據(jù)項尝抖,并進行打亂

paddle.batch()表示每BATCH_SIZE組成一個batch

In[2]

BUF_SIZE=500
BATCH_SIZE=20

#用于訓(xùn)練的數(shù)據(jù)提供器毡们,每次從緩存中隨機讀取批次大小的數(shù)據(jù)
train_reader = paddle.batch(
    paddle.reader.shuffle(paddle.dataset.uci_housing.train(), 
                          buf_size=BUF_SIZE),                    
    batch_size=BATCH_SIZE)   
#用于測試的數(shù)據(jù)提供器,每次從緩存中隨機讀取批次大小的數(shù)據(jù)
test_reader = paddle.batch(
    paddle.reader.shuffle(paddle.dataset.uci_housing.test(),
                          buf_size=BUF_SIZE),
    batch_size=BATCH_SIZE)  


[=========================================         ]
[=============================================     ]
[==================================================]
/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/paddle/dataset/uci_housing.py:49: UserWarning: 
This call to matplotlib.use() has no effect because the backend has already
been chosen; matplotlib.use() must be called *before* pylab, matplotlib.pyplot,
or matplotlib.backends is imported for the first time.

The backend was *originally* set to 'module://ipykernel.pylab.backend_inline' by the following code:
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel_launcher.py", line 16, in <module>
    app.launch_new_instance()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/traitlets/config/application.py", line 658, in launch_instance
    app.start()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/kernelapp.py", line 505, in start
    self.io_loop.start()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/platform/asyncio.py", line 132, in start
    self.asyncio_loop.run_forever()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/asyncio/base_events.py", line 421, in run_forever
    self._run_once()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/asyncio/base_events.py", line 1425, in _run_once
    handle._run()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/asyncio/events.py", line 127, in _run
    self._callback(*self._args)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/ioloop.py", line 758, in _run_callback
    ret = callback()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/stack_context.py", line 300, in null_wrapper
    return fn(*args, **kwargs)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/gen.py", line 1233, in inner
    self.run()
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/gen.py", line 1147, in run
    yielded = self.gen.send(value)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 357, in process_one
    yield gen.maybe_future(dispatch(*args))
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/gen.py", line 326, in wrapper
    yielded = next(result)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 267, in dispatch_shell
    yield gen.maybe_future(handler(stream, idents, msg))
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/gen.py", line 326, in wrapper
    yielded = next(result)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/kernelbase.py", line 534, in execute_request
    user_expressions, allow_stdin,
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/tornado/gen.py", line 326, in wrapper
    yielded = next(result)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/ipkernel.py", line 294, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/zmqshell.py", line 536, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/IPython/core/interactiveshell.py", line 2821, in run_cell
    self.events.trigger('post_run_cell', result)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/IPython/core/events.py", line 88, in trigger
    func(*args, **kwargs)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/ipykernel/pylab/backend_inline.py", line 164, in configure_once
    activate_matplotlib(backend)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/IPython/core/pylabtools.py", line 314, in activate_matplotlib
    matplotlib.pyplot.switch_backend(backend)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/matplotlib/pyplot.py", line 231, in switch_backend
    matplotlib.use(newbackend, warn=False, force=True)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/matplotlib/__init__.py", line 1422, in use
    reload(sys.modules['matplotlib.backends'])
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/importlib/__init__.py", line 166, in reload
    _bootstrap._exec(spec, module)
  File "/opt/conda/envs/python35-paddle120-env/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 16, in <module>
    line for line in traceback.format_stack()

  matplotlib.use('Agg')

</pre>

(3)打印看下數(shù)據(jù)是什么樣的昧辽?PaddlePaddle接口提供的數(shù)據(jù)已經(jīng)經(jīng)過歸一化等處理

(array([-0.02964322, -0.11363636, 0.39417967, -0.06916996, 0.14260276, -0.10109875, 0.30715859, -0.13176829, -0.24127857, 0.05489093, 0.29196451, -0.2368098 , 0.12850267]), array([15.6])),

In[3]

用于打印衙熔,查看uci_housing數(shù)據(jù)
train_data=paddle.dataset.uci_housing.train();
sampledata=next(train_data())
print(sampledata)


<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, &quot;Liberation Mono&quot;, Menlo, Courier, monospace; font-size: 1em; margin: 0px; overflow: auto; background-color: transparent;">(array([-0.0405441 ,  0.06636364, -0.32356227, -0.06916996, -0.03435197,
        0.05563625, -0.03475696,  0.02682186, -0.37171335, -0.21419304,
       -0.33569506,  0.10143217, -0.21172912]), array([24.]))
</pre>

# **Step2:網(wǎng)絡(luò)配置**

**(1)網(wǎng)絡(luò)搭建**:對于線性回歸來講,它就是一個從輸入到輸出的簡單的全連接層搅荞。

對于波士頓房價數(shù)據(jù)集红氯,假設(shè)屬性和房價之間的關(guān)系可以被屬性間的線性組合描述框咙。

![image](https://upload-images.jianshu.io/upload_images/15504920-860d6c5547b09b92?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![image](https://upload-images.jianshu.io/upload_images/15504920-57fc0861eee93f56?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

In[4]

定義張量變量x,表示13維的特征值
x = fluid.layers.data(name='x', shape=[13], dtype='float32')
定義張量y,表示目標(biāo)值
y = fluid.layers.data(name='y', shape=[1], dtype='float32')
定義一個簡單的線性網(wǎng)絡(luò),連接輸入和輸出的全連接層
input:輸入tensor;
size:該層輸出單元的數(shù)目
act:激活函數(shù)
y_predict=fluid.layers.fc(input=x,size=1,act=None)


**(2)定義損失函數(shù)**

此處使用均方差損失函數(shù)痢甘。

square_error_cost(input,lable):接受輸入預(yù)測值和目標(biāo)值喇嘱,并返回方差估計,即為(y-y_predict)的平方

In[5]

cost = fluid.layers.square_error_cost(input=y_predict, label=y) #求一個batch的損失值
avg_cost = fluid.layers.mean(cost) #對損失值求平均值


**(3)定義優(yōu)化函數(shù)**

此處使用的是隨機梯度下降。

In[6]

optimizer = fluid.optimizer.SGDOptimizer(learning_rate=0.001)
opts = optimizer.minimize(avg_cost)


In[7]

test_program = fluid.default_main_program().clone(for_test=True)


在上述模型配置完畢后塞栅,得到兩個fluid.Program:fluid.default_startup_program() 與fluid.default_main_program() 配置完畢了者铜。

參數(shù)初始化操作會被寫入**fluid.default_startup_program()**

**fluid.default_main_program**()用于獲取默認(rèn)或全局main program(主程序)。該主程序用于訓(xùn)練和測試模型放椰。fluid.layers 中的所有l(wèi)ayer函數(shù)可以向 default_main_program 中添加算子和變量作烟。default_main_program 是fluid的許多編程接口(API)的Program參數(shù)的缺省值。例如,當(dāng)用戶program沒有傳入的時候砾医, Executor.run() 會默認(rèn)執(zhí)行 default_main_program 拿撩。

# **Step3.模型訓(xùn)練** and **Step4.模型評估**

**(1)創(chuàng)建Executor**

首先定義運算場所 fluid.CPUPlace()和 fluid.CUDAPlace(0)分別表示運算場所為CPU和GPU

Executor:接收傳入的program,通過run()方法運行program如蚜。

In[8]

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) #創(chuàng)建一個Executor實例exe
exe.run(fluid.default_startup_program()) #Executor的run()方法執(zhí)行startup_program(),進行參數(shù)初始化


<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, &quot;Liberation Mono&quot;, Menlo, Courier, monospace; font-size: 1em; margin: 0px; overflow: auto; background-color: transparent;">[]</pre>

定義輸入數(shù)據(jù)維度

DataFeeder負責(zé)將數(shù)據(jù)提供器(train_reader,test_reader)返回的數(shù)據(jù)轉(zhuǎn)成一種特殊的數(shù)據(jù)結(jié)構(gòu)压恒,使其可以輸入到Executor中。

feed_list設(shè)置向模型輸入的向變量表或者變量表名

In[9]

Step2 定義輸入數(shù)據(jù)維度

feeder = fluid.DataFeeder(place=place, feed_list=[x, y])#feed_list:向模型輸入的變量表或變量表名


**(3)定義繪制訓(xùn)練過程的損失值變化趨勢的方法draw_train_process**

In[10]

iter=0;
iters=[]
train_costs=[]

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


**(4)訓(xùn)練并保存模型**

Executor接收傳入的program,并根據(jù)feed map(輸入映射表)和fetch_list(結(jié)果獲取表) 向program中添加feed operators(數(shù)據(jù)輸入算子)和fetch operators(結(jié)果獲取算子)错邦。 feed map為該program提供輸入數(shù)據(jù)探赫。fetch_list提供program訓(xùn)練結(jié)束后用戶預(yù)期的變量。

注:enumerate() 函數(shù)用于將一個可遍歷的數(shù)據(jù)對象(如列表撬呢、元組或字符串)組合為一個索引序列期吓,同時列出數(shù)據(jù)和數(shù)據(jù)下標(biāo),

In[11]

EPOCH_NUM=50
model_save_dir = "/home/aistudio/work/fit_a_line.inference.model"

for pass_id in range(EPOCH_NUM): #訓(xùn)練EPOCH_NUM輪
# 開始訓(xùn)練并輸出最后一個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的訓(xùn)練數(shù)據(jù)倾芝,根據(jù)feed_list和data提供的信息,將輸入數(shù)據(jù)轉(zhuǎn)成一種特殊的數(shù)據(jù)結(jié)構(gòu)
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的測試數(shù)據(jù)
                        fetch_list=[avg_cost])                #fetch均方誤差
print('Test:%d, Cost:%0.5f' % (pass_id, test_cost[0][0]))     #打印最后一個batch的損失值

#保存模型
# 如果保存路徑不存在就創(chuàng)建

if not os.path.exists(model_save_dir):
os.makedirs(model_save_dir)
print ('save models to %s' % (model_save_dir))

保存訓(xùn)練參數(shù)到指定路徑中箭跳,構(gòu)建一個專門用預(yù)測的program
fluid.io.save_inference_model(model_save_dir, #保存推理model的路徑
['x'], #推理(inference)需要 feed 的數(shù)據(jù)
[y_predict], #保存推理(inference)結(jié)果的 Variables
exe) #exe 保存 inference model
draw_train_process(iters,train_costs)


<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, &quot;Liberation Mono&quot;, Menlo, Courier, monospace; font-size: 1em; margin: 0px; overflow: auto; background-color: transparent;">Pass:0, Cost:775.69037
Test:0, Cost:336.09720
Pass:1, Cost:631.15497
Test:1, Cost:70.60072
Pass:2, Cost:575.09827
Test:2, Cost:285.86896
Pass:3, Cost:595.56970
Test:3, Cost:227.26286
Pass:4, Cost:330.39081
Test:4, Cost:126.72552
Pass:5, Cost:386.42255
Test:5, Cost:119.62447
Pass:6, Cost:226.53174
Test:6, Cost:147.53394
Pass:7, Cost:370.09473
Test:7, Cost:91.69784
Pass:8, Cost:379.28619
Test:8, Cost:9.05422
Pass:9, Cost:510.79962
Test:9, Cost:28.97821
Pass:10, Cost:341.42810
Test:10, Cost:161.98212
Pass:11, Cost:232.81880
Test:11, Cost:1.24671
Pass:12, Cost:379.26666
Test:12, Cost:61.33340
Pass:13, Cost:245.12344
Test:13, Cost:184.92972
Pass:14, Cost:280.91974
Test:14, Cost:46.74941
Pass:15, Cost:297.70831
Test:15, Cost:39.04773
Pass:16, Cost:127.24528
Test:16, Cost:12.40762
Pass:17, Cost:84.47005
Test:17, Cost:31.83543
Pass:18, Cost:176.30728
Test:18, Cost:6.91334
Pass:19, Cost:64.81275
Test:19, Cost:26.38462
Pass:20, Cost:262.61273
Test:20, Cost:71.91628
Pass:21, Cost:136.62866
Test:21, Cost:46.76147
Pass:22, Cost:270.86783
Test:22, Cost:112.91938
Pass:23, Cost:131.29561
Test:23, Cost:39.15680
Pass:24, Cost:38.55107
Test:24, Cost:53.81767
Pass:25, Cost:154.57745
Test:25, Cost:17.59366
Pass:26, Cost:97.25758
Test:26, Cost:24.06485
Pass:27, Cost:52.72923
Test:27, Cost:13.88737
Pass:28, Cost:81.24602
Test:28, Cost:7.11193
Pass:29, Cost:102.37051
Test:29, Cost:61.35436
Pass:30, Cost:110.00648
Test:30, Cost:14.24446
Pass:31, Cost:134.07700
Test:31, Cost:23.70427
Pass:32, Cost:90.75577
Test:32, Cost:1.26567
Pass:33, Cost:39.38052
Test:33, Cost:82.46861
Pass:34, Cost:59.20267
Test:34, Cost:14.03627
Pass:35, Cost:104.19045
Test:35, Cost:31.30172
Pass:36, Cost:141.77986
Test:36, Cost:17.63796
Pass:37, Cost:23.15283
Test:37, Cost:2.80610
Pass:38, Cost:181.94595
Test:38, Cost:6.18225
Pass:39, Cost:79.11588
Test:39, Cost:7.55335
Pass:40, Cost:47.65699
Test:40, Cost:3.15243
Pass:41, Cost:75.34374
Test:41, Cost:7.44454
Pass:42, Cost:16.22910
Test:42, Cost:10.73070
Pass:43, Cost:77.80751
Test:43, Cost:1.21454
Pass:44, Cost:38.16778
Test:44, Cost:72.84727
Pass:45, Cost:128.39098
Test:45, Cost:62.30526
Pass:46, Cost:86.96892
Test:46, Cost:2.33209
Pass:47, Cost:69.26112
Test:47, Cost:7.32824
Pass:48, Cost:109.95087
Test:48, Cost:7.02785
Pass:49, Cost:51.08218
Test:49, Cost:2.19573
save models to /home/aistudio/work/fit_a_line.inference.model
</pre>

![image.png](https://upload-images.jianshu.io/upload_images/15504920-c4ba6b8c5a0ce9e8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

# **Step5.模型預(yù)測**

**(1)創(chuàng)建預(yù)測用的Executor**

In[12]

infer_exe = fluid.Executor(place) #創(chuàng)建推測用的executor
inference_scope = fluid.core.Scope() #Scope指定作用域


**(2)可視化真實值與預(yù)測值方法定義**

In[13]

infer_results=[]
groud_truths=[]

Step3 繪制真實值和預(yù)測值對比圖

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()
plt.show()


**(3)開始預(yù)測**

通過fluid.io.load_inference_model晨另,預(yù)測器會從params_dirname中讀取已經(jīng)訓(xùn)練好的模型,來對從未遇見過的數(shù)據(jù)進行預(yù)測谱姓。

In[14]

with fluid.scope_guard(inference_scope):#修改全局/默認(rèn)作用域(scope), 運行時中的所有變量都將分配給新的scope借尿。
#從指定目錄中加載 推理model(inference model)
[inference_program, #推理的program
feed_target_names, #需要在推理program中提供數(shù)據(jù)的變量名稱
fetch_targets] = fluid.io.load_inference_model(#fetch_targets: 推斷結(jié)果
model_save_dir, #model_save_dir:模型訓(xùn)練路徑
infer_exe) #infer_exe: 預(yù)測用executor
#獲取預(yù)測數(shù)據(jù)
infer_reader = paddle.batch(paddle.dataset.uci_housing.test(), #獲取uci_housing的測試數(shù)據(jù)
batch_size=200) #從測試數(shù)據(jù)中讀取一個大小為200的batch數(shù)據(jù)
#從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, #預(yù)測模型
feed={feed_target_names[0]: np.array(test_x)}, #喂入要預(yù)測的x值
fetch_list=fetch_targets) #得到推測結(jié)果

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)

<pre style="box-sizing: border-box; font-family: SFMono-Regular, Consolas, &quot;Liberation Mono&quot;, Menlo, Courier, monospace; font-size: 1em; margin: 0px; overflow: auto; background-color: transparent;">infer results: (House Price)
0: 15.40
1: 15.72
2: 15.19
3: 16.28
4: 15.47
5: 15.72
6: 15.20
7: 14.95
8: 13.37
9: 15.25
10: 13.19
11: 14.16
12: 14.61
13: 14.50
14: 14.47
15: 15.06
16: 16.22
17: 16.11
18: 16.34
19: 14.72
20: 15.23
21: 14.27
22: 15.66
23: 15.30
24: 15.21
25: 14.69
26: 15.57
27: 15.47
28: 16.20
29: 15.45
30: 15.33
31: 14.92
32: 14.86
33: 14.02
34: 13.88
35: 15.80
36: 15.91
37: 16.21
38: 16.34
39: 16.24
40: 15.12
41: 14.52
42: 16.03
43: 16.39
44: 16.33
45: 15.94
46: 14.99
47: 16.36
48: 16.49
49: 16.76
50: 14.92
51: 15.18
52: 14.75
53: 14.97
54: 16.23
55: 16.77
56: 16.18
57: 16.78
58: 16.92
59: 17.12
60: 17.35
61: 17.14
62: 15.13
63: 16.18
64: 16.90
65: 17.37
66: 17.04
67: 17.30
68: 17.37
69: 17.66
70: 16.25
71: 15.86
72: 16.71
73: 15.63
74: 16.52
75: 16.98
76: 17.86
77: 18.06
78: 18.20
79: 18.12
80: 17.70
81: 17.98
82: 17.19
83: 17.69
84: 17.41
85: 16.71
86: 16.12
87: 17.48
88: 18.07
89: 21.14
90: 21.28
91: 21.16
92: 20.19
93: 20.83
94: 21.02
95: 20.60
96: 20.73
97: 21.83
98: 21.59
99: 21.89
100: 21.80
101: 21.60
ground truth:
0: 8.50
1: 5.00
2: 11.90
3: 27.90
4: 17.20
5: 27.50
6: 15.00
7: 17.20
8: 17.90
9: 16.30
10: 7.00
11: 7.20
12: 7.50
13: 10.40
14: 8.80
15: 8.40
16: 16.70
17: 14.20
18: 20.80
19: 13.40
20: 11.70
21: 8.30
22: 10.20
23: 10.90
24: 11.00
25: 9.50
26: 14.50
27: 14.10
28: 16.10
29: 14.30
30: 11.70
31: 13.40
32: 9.60
33: 8.70
34: 8.40
35: 12.80
36: 10.50
37: 17.10
38: 18.40
39: 15.40
40: 10.80
41: 11.80
42: 14.90
43: 12.60
44: 14.10
45: 13.00
46: 13.40
47: 15.20
48: 16.10
49: 17.80
50: 14.90
51: 14.10
52: 12.70
53: 13.50
54: 14.90
55: 20.00
56: 16.40
57: 17.70
58: 19.50
59: 20.20
60: 21.40
61: 19.90
62: 19.00
63: 19.10
64: 19.10
65: 20.10
66: 19.90
67: 19.60
68: 23.20
69: 29.80
70: 13.80
71: 13.30
72: 16.70
73: 12.00
74: 14.60
75: 21.40
76: 23.00
77: 23.70
78: 25.00
79: 21.80
80: 20.60
81: 21.20
82: 19.10
83: 20.60
84: 15.20
85: 7.00
86: 8.10
87: 13.60
88: 20.10
89: 21.80
90: 24.50
91: 23.10
92: 19.70
93: 18.30
94: 21.20
95: 17.50
96: 16.80
97: 22.40
98: 20.60
99: 23.90
100: 22.00
101: 11.90
</pre>

![image.png](https://upload-images.jianshu.io/upload_images/15504920-3ad6a105d46ea281.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

In[ ]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市屉来,隨后出現(xiàn)的幾起案子路翻,更是在濱河造成了極大的恐慌,老刑警劉巖茄靠,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件茂契,死亡現(xiàn)場離奇詭異,居然都是意外死亡慨绳,警方通過查閱死者的電腦和手機掉冶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門真竖,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人厌小,你說我怎么就攤上這事恢共。” “怎么了璧亚?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵讨韭,是天一觀的道長。 經(jīng)常有香客問我癣蟋,道長透硝,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任梢薪,我火速辦了婚禮蹬铺,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘秉撇。我一直安慰自己甜攀,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布琐馆。 她就那樣靜靜地躺著规阀,像睡著了一般。 火紅的嫁衣襯著肌膚如雪瘦麸。 梳的紋絲不亂的頭發(fā)上谁撼,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音滋饲,去河邊找鬼厉碟。 笑死,一個胖子當(dāng)著我的面吹牛屠缭,可吹牛的內(nèi)容都是我干的箍鼓。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼呵曹,長吁一口氣:“原來是場噩夢啊……” “哼款咖!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起奄喂,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤铐殃,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后跨新,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體富腊,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年玻蝌,在試婚紗的時候發(fā)現(xiàn)自己被綠了蟹肘。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片词疼。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖帘腹,靈堂內(nèi)的尸體忽然破棺而出贰盗,到底是詐尸還是另有隱情,我是刑警寧澤阳欲,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布舵盈,位于F島的核電站,受9級特大地震影響球化,放射性物質(zhì)發(fā)生泄漏秽晚。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一筒愚、第九天 我趴在偏房一處隱蔽的房頂上張望赴蝇。 院中可真熱鬧,春花似錦巢掺、人聲如沸句伶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽考余。三九已至,卻和暖如春轧苫,著一層夾襖步出監(jiān)牢的瞬間楚堤,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工含懊, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留身冬,地道東北人。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓岔乔,卻偏偏與公主長得像吏恭,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子重罪,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,864評論 2 354