TensorFlow-5: 用 tf.contrib.learn 來構建輸入函數(shù)

學習資料:
https://www.tensorflow.org/get_started/input_fn

對應的中文翻譯:
http://studyai.site/2017/03/06/%E3%80%90Tensorflow%20r1.0%20%E6%96%87%E6%A1%A3%E7%BF%BB%E8%AF%91%E3%80%91%E9%80%9A%E8%BF%87tf.contrib.learn%E6%9D%A5%E6%9E%84%E5%BB%BA%E8%BE%93%E5%85%A5%E5%87%BD%E6%95%B0/


今天學習用 tf.contrib.learn 來建立 input funciton, 并用 DNN 對 Boston Housing 數(shù)據(jù)集進行回歸預測。

問題:

  • 給一組波士頓房屋價格數(shù)據(jù),要用神經(jīng)網(wǎng)絡回歸模型來預測房屋價格的中位數(shù)
  • 數(shù)據(jù)集可以從官網(wǎng)教程下載:
    https://www.tensorflow.org/get_started/input_fn
  • 它包括以下特征:


  • 我們需要預測的是MEDV這個標簽,以每一千美元為單位

一共有 5 步:

  • 導入 CSV 格式的數(shù)據(jù)集
  • 建立神經(jīng)網(wǎng)絡回歸模型
  • 用訓練數(shù)據(jù)集訓練模型
  • 評價模型的準確率
  • 對新樣本數(shù)據(jù)進行分類

代碼:
地址:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/input_fn/boston.py

"""DNNRegressor with custom input_fn for Housing dataset."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import itertools

import pandas as pd
import tensorflow as tf

tf.logging.set_verbosity(tf.logging.INFO)

COLUMNS = ["crim", "zn", "indus", "nox", "rm", "age",
           "dis", "tax", "ptratio", "medv"]
FEATURES = ["crim", "zn", "indus", "nox", "rm",
            "age", "dis", "tax", "ptratio"]
LABEL = "medv"


def input_fn(data_set):
  feature_cols = {k: tf.constant(data_set[k].values) for k in FEATURES}
  labels = tf.constant(data_set[LABEL].values)
  return feature_cols, labels


def main(unused_argv):
  # Load datasets
  training_set = pd.read_csv("boston_train.csv", skipinitialspace=True,
                             skiprows=1, names=COLUMNS)
  test_set = pd.read_csv("boston_test.csv", skipinitialspace=True,
                         skiprows=1, names=COLUMNS)

  # Set of 6 examples for which to predict median house values
  prediction_set = pd.read_csv("boston_predict.csv", skipinitialspace=True,
                               skiprows=1, names=COLUMNS)

  # Feature cols
  feature_cols = [tf.contrib.layers.real_valued_column(k)
                  for k in FEATURES]

  # Build 2 layer fully connected DNN with 10, 10 units respectively.
  regressor = tf.contrib.learn.DNNRegressor(feature_columns=feature_cols,
                                            hidden_units=[10, 10],
                                            model_dir="/tmp/boston_model")

  # Fit
  regressor.fit(input_fn=lambda: input_fn(training_set), steps=5000)

  # Score accuracy
  ev = regressor.evaluate(input_fn=lambda: input_fn(test_set), steps=1)
  loss_score = ev["loss"]
  print("Loss: {0:f}".format(loss_score))

  # Print out predictions
  y = regressor.predict(input_fn=lambda: input_fn(prediction_set))
  # .predict() returns an iterator; convert to a list and print predictions
  predictions = list(itertools.islice(y, 6))
  print("Predictions: {}".format(str(predictions)))

if __name__ == "__main__":
  tf.app.run()

今天主要的知識點就是輸入函數(shù)

在上面的代碼中我們可以看到,輸入數(shù)據(jù)時用的是 pandas,可以直接讀取 CSV 文件
為了識別數(shù)據(jù)集中哪些是列,哪些是特征,哪些是預測標簽,需要把這三者定義出來

在定義神經(jīng)網(wǎng)絡回歸模型時,我們建立一個具有兩層隱藏層的神經(jīng)網(wǎng)絡,每一層具有 10 個神經(jīng)元節(jié)點,
接下來就是建立輸入函數(shù),它的作用就是把輸入數(shù)據(jù)傳遞給回歸模型,它可以接受 pandas 的 Dataframe 結構,并將特征和標簽列作為 Tensors 返回

在訓練時,只需要把訓練數(shù)據(jù)集傳遞給輸入函數(shù),用 fit 迭代5000步
評價模型時,也是將測試數(shù)據(jù)集傳遞給輸入函數(shù),再用 evaluate
預測時,同樣將預測數(shù)據(jù)集傳遞給輸入函數(shù)


關于 輸入函數(shù):

昨天學到讀取 CSV 文件的方法適用于不需要對原來的數(shù)據(jù)有什么操作的時候
但是當需要對數(shù)據(jù)進行特征工程時,我們就需要有一個輸入函數(shù)來把數(shù)據(jù)的預處理給封裝起來,再傳遞給模型

輸入函數(shù)的基本框架:

def my_input_fn():

    # Preprocess your data here...

    # ...then return 1) a mapping of feature columns to Tensors with
    # the corresponding feature data, and 2) a Tensor containing labels
    return feature_cols, labels

輸入函數(shù)必須返回下面兩種值:

feature_cols:是一個字典,key 就是特征列的名字,value 就是 tensor,包含了相應的數(shù)據(jù)

labels:返回包含標簽數(shù)據(jù)的 tensor,即所想要預測的目標

如果特征/標簽數(shù)據(jù)存在pandas數(shù)據(jù)幀中或numpy數(shù)組中,那么需要將其轉換為Tensor,然后從 input_fn 中返回。

對于稀疏數(shù)據(jù)
大多數(shù)值為0的數(shù)據(jù),應該填充一個 SparseTensor,

下面例子,就是定義了一個具有3行和5列的二維 SparseTensor。在 [0,1] 上的元素的值為 6,[2,4] 上的元素值為 0.5,其他值為 0:

sparse_tensor = tf.SparseTensor(indices=[[0,1], [2,4]],
                                values=[6, 0.5],
                                dense_shape=[3, 5])
[[0, 6, 0, 0, 0]
 [0, 0, 0, 0, 0]
 [0, 0, 0, 0, 0.5]]

推薦閱讀 歷史技術博文鏈接匯總
http://www.lxweimin.com/p/28f02bb59fe5
也許可以找到你想要的

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容