# TensorFlow 核心

2018.10.08 23:27 2964浏览

## TensorFlow Core Walkthrough

• 通过 tf.Graph 建立计算图 (Building the computational graph (a tf.Graph).)
• 使用 tf.Session 运行计算图(Running the computational graph (using a tf.Session).)
import numpy as np
import tensorflow as tf


## Graph 与 Session

A computational graph is a series of TensorFlow operations arranged into a graph. The graph is composed of two types of objects.

• tf.Operation (or “ops”): The nodes of the graph. Operations describe calculations that consume and produce tensors.
• tf.Tensor: The edges in the graph. These represent the values that will flow through the graph. Most TensorFlow functions return tf.Tensors.

• tf.Operation (or “ops”): 图的节点（nodes）. 节点描述了如何 对 Tensor 的输入和输出进行计算；
• tf.Tensor: 图的边（edges）. 边代表了流经计算图的值。

a = tf.constant(3.0, dtype=tf.float32)
b = tf.constant(4.0)  # also tf.float32 implicitly
total = a + b
print(a)
print(b)
print(total)

Tensor("Const:0", shape=(), dtype=float32)
Tensor("Const_1:0", shape=(), dtype=float32)


• tf.Tensor 可以理解为一个符号，比如数学中的未知元 $x$ (仅仅是一个代表, 它可以是数组，字符串等)
• tf.Operation 可以理解为 $x$ 的方程，比如 $x^7 + 3x^5 + 1$ (只要你可以定义一个合理的运算规则, 若 $x$ 是字符串，该方程也可能成立)

## Datasets

• To get a runnable tf.Tensor from a Dataset you must first convert it to a tf.data.Iterator, and then call the Iterator’s tf.data.Iterator.get_next method.

• The simplest way to create an Iterator is with the tf.data.Dataset.make_one_shot_iterator method. For example, in the following code the next_item tensor will return a row from the my_data array on each run call:

my_data = [
[0, 1, ],
[2, 3, ],
[4, 5, ],
[6, 7, ],
]
slices = tf.data.Dataset.from_tensor_slices(my_data)
next_item = slices.make_one_shot_iterator().get_next()

next_item

<tf.Tensor 'IteratorGetNext:0' shape=(2,) dtype=int32>


while True:
try:
print(sess.run(next_item))
except tf.errors.OutOfRangeError:
break


r = tf.random_normal([10, 3])
dataset = tf.data.Dataset.from_tensor_slices(r)
iterator = dataset.make_initializable_iterator()
next_row = iterator.get_next()

sess.run(iterator.initializer)
while True:
try:
print(sess.run(next_row))
except tf.errors.OutOfRangeError:
break


## Layers

x = tf.constant([[1], [2], [3], [4]], dtype=tf.float32)
y_true = tf.constant([[0], [-1], [-2], [-3]], dtype=tf.float32)

linear_model = tf.layers.Dense(units=1)

y_pred = linear_model(x)
loss = tf.losses.mean_squared_error(labels=y_true, predictions=y_pred)

train = optimizer.minimize(loss)

init = tf.global_variables_initializer()

sess = tf.Session()
sess.run(init)
for i in range(100):
_, loss_value = sess.run((train, loss))
print(loss_value)

print(sess.run(y_pred))


4人点赞

• 4
• 评论
• 收藏
• 共同学习，写下你的评论

0/150