# TensorFlow－5: 用 tf.contrib.learn 来构建输入函数

• 给一组波士顿房屋价格数据，要用神经网络回归模型来预测房屋价格的中位数
• 数据集可以从官网教程下载：
https://www.tensorflow.org/get_started/input_fn
• 它包括以下特征：
• 我们需要预测的是MEDV这个标签，以每一千美元为单位

• 导入 CSV 格式的数据集
• 建立神经网络回归模型
• 用训练数据集训练模型
• 评价模型的准确率
• 对新样本数据进行分类
"""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):
skiprows=1, names=COLUMNS)
skiprows=1, names=COLUMNS)

# Set of 6 examples for which to predict median house values
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()

def my_input_fn():

# ...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

feature_cols：是一个字典，key 就是特征列的名字，value 就是 tensor，包含了相应的数据

labels：返回包含标签数据的 tensor，即所想要预测的目标

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]]

#### 使用tf.contrib.learn构建输入函数

2017-08-16 12:02:46

#### 深度学习笔记——深度学习框架TensorFlow(十)[Creating Estimators in tf.contrib.learn]

2017-07-04 16:17:13

#### TensorFlow高级API(tf.contrib.learn)及可视化工具TensorBoard的使用

2018-01-08 21:32:00

#### TensorFlow学习笔记6----tf.contrib.learn Quickstart

2017-05-09 10:19:39

#### 关于C++输入函数的读取问题

2017-04-18 22:50:33

#### tensorflow中使用tf.contrib.learn时调整GPU配置

2018-05-11 11:20:07

#### 05：Tensorflow高级API的进阶--利用tf.contrib.learn建立输入函数

2017-03-16 18:44:13

#### tensorflow学习笔记十四：TF官方教程学习 tf.contrib.learn Quickstart

2017-03-16 14:55:51

#### 学习使用tf.contrib.learn框架开发机器学习程序

2016-12-30 15:47:16

#### TensorFlow学习笔记11----Building Input Functions with tf.contrib.learn

2017-06-06 20:31:41