TensorFlow官方文档笔记

本文档深入探讨TensorFlow,从底层API到tf.contrib.learn的高层使用。介绍了常量、占位符和Variable的用法,以及如何利用tf.train API进行线性回归模型的训练。详细阐述了计算图的概念,以及训练过程中的损失计算和优化。同时提到了TensorBoard的使用,用于可视化模型训练状态。此外,还讨论了如何构建输入函数和自定义输入管道,并以波士顿房价预测为例展示了如何使用tf.contrib.learn进行模型训练和评估。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Getting Started With TensorFlow

https://www.tensorflow.org/get_started/get_started
tf.contrib.learn是更高层的API,TensorFlow Core是底层API。
本文档讲底层。

node 只是一个节点,不直接计算。计算是在session里。
##The Computational Graph
###constant 常量
可以是数 list 等等

node1 = tf.constant([1, 2], tf.float32)

###placeholder
通过feed_dict传入

Variable

init = tf.global_variables_initializer()只是初始化Variables
可通过assign重新赋值

##tf.train API
线性回归,因为w和b是Variable,因此只要设定了优化器,使其最小化loss,就会自动执行BP反向传播(计算梯度,根据梯度更新w和b),重复若干epoch,每一次cpoch改变一次w和b,最终得到最优的w和b。

# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

tf.contrib.learn

###Basic usage
线性回归,因为直接使用了LinearRegressor

estimator = tf.contrib.learn.LinearRegressor(feature_columns=features)

所以只需要定义x和y,即可不需要定义w和b。
这个确实是比较高层的API。

TensorFlow Mechanics 101

https://www.tensorflow.org/get_started/mnist/mechanics

读数据

几行代码

建立图

这个主要是分析mnist.py的代码的。
###loss
loss函数每次读一个batch的像素点与标签值。算出一个batch的loss的均值(一个数)

def loss(logits, labels):
  """Calculates the loss from the logits and the labels.

  Args:
    logits: Logits tensor, float - [batch_size, NUM_CLASSES].
    labels: Labels tensor, int32 - [batch_size].

  Returns:
    loss: Loss tensor of type float.
  """
  labels = tf.to_int64(labels)
  cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
      labels=labels, logits=logits, name='xentropy')
  return tf.reduce_mean(cross_entropy, name='xentropy_mean')

training

training每次把这一个batch的数加进“loss”的变量里,每读一个batch,loss都会变。最后会得到全部数据的loss均值。

global_step = tf.Variable(0, name=‘global_step’, trainable=False)
train_op = optimizer.minimize(loss, global_step=global_step)
其中global_step是一个计数器,每次会加1

训练模型

fully_connected_feed.py
###chenck the status
train_op, loss是张量,loss_value是数组。

_, loss_value = sess.run([train_op, loss],
                             feed_dict=feed_dict)

tensorboard

要用summary之后,才能从tensorboard读出来。

##Evaluate the Model

#tf.contrib.learn Quickstart
https://www.tensorflow.org/get_started/tflearn
把模型封装好了,用的是DNNClassifier,训练就是fit一句话,测试也是evaluate和predict。

#Building Input Functions with tf.contrib.learn
https://www.tensorflow.org/get_started/input_fn
##Custom Input Pipelines with input_fn
如果是图像的话,可以通过numpy读为矩阵,再转为tensor,然后再从input_fn中返回。

使用tf.contrib.learn 的好处是,不是只能在sess.run里才能看到Debug变量的结果,而是直接每一行都能出结果,方便Debug。

通过

training_set = pd.read_csv("boston_train.csv", skipinitialspace=True,
                           skiprows=1, names=COLUMNS)

之后,
training_set变为400行,10列。
testing_set 变为100行,10列。
predicting_set变为6行,9列。(最后一列MEDV没有,因为是需要预测的)。可在pycharm下debug看pandas。

自己敲的代码,更方便看,如下(波士顿房价预测)

#encoding=utf-8
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):
    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)
    prediction_set = pd.read_csv("boston_predict.csv", skipinitialspace = True, skiprows = 1, names = COLUMNS)

    # 把FEATURES按条目转换为list, 用于建立regressor
    feature_cols = [tf.contrib.layers.real_valued_column(k) for k in FEATURES]
    regressor    = tf.contrib.learn.DNNRegressor(feature_columns = feature_cols, hidden_units = [10, 10], model_dir = "/tmp/bosten_model")

    regressor.fit(input_fn = lambda:input_fn(training_set), steps = 1)

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

    y = regressor.predict(input_fn = lambda:input_fn(prediction_set))
    predictions = list(itertools.islice(y, 6))
    print("predictions:{}".format(str(predictions)))

if __name__ == "__main__":
    tf.app.run()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值