您的位置:首页 > 其它

TensorFlow基本概念

2017-08-21 17:29 232 查看

核心概念

TensorFlow中的计算可以表示为一个有向图,或称计算图

每一个运算操作将作为一个节点,节点与节点之间的连接称为边

在计算图的边中流动(flow)的数据称为张量(tensor),故得名TensorFlow

基本操作

4个重要的类型

Variable 计算图谱中的变量

Tensor 一个多维矩阵,带有很多方法

Graph 一个计算图谱

Session 用来运行一个计算图谱

三个重要的函数

# Variable 变量
tf.Variable.__init__(
initial_value=None, @Tensor
trainable=True,
collections=None,
validate_shape=True,
caching_device=None,
name=None,
variable_def=None,
dtype=None)
# 注意:Variable是一个Class,Tensor也是一个Class

# Constant 常数
tf.constant(value, dtype=None, shape=None, name='Const')
return: a constant @Tensor

# Placeholder 暂时变量,将来会对它赋值
tf.placeholder(dtype, shape=None, name=None)
return: 一个还尚未存在的 @Tensor


A+B

代码

#!/usr/bin/python3.5

import tensorflow as tf

node1 = tf.constant(3.0, dtype=tf.float32)
node2 = tf.constant(4.0) # also tf.float32 implicitly
print(node1)
print(node2)

sess = tf.Session()
print(sess.run([node1, node2]))

node3 = tf.add(node1, node2)
print("node3: ", node3)
print("sess.run(node3): ",sess.run(node3))


运行结果

Tensor("Const:0", shape=(), dtype=float32)
Te
4000
nsor("Const_1:0", shape=(), dtype=float32)
[3.0, 4.0]
node3:  Tensor("Add:0", shape=(), dtype=float32)
sess.run(node3):  7.0


Placeholder

代码

#!/usr/bin/python3.5

import tensorflow as tf

a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

# Define some operations
add = tf.add(a, b)
mul = tf.multiply(a, b)

with tf.Session() as sess:
print(sess.run(add, feed_dict={a: 2, b: 3}))  # ==> 5
print(sess.run(mul, feed_dict={a: 2, b: 3}))  # ==> 6


运行结果

5
6


Graph

代码

#!/usr/bin/python3.5

import tensorflow as tf

a = tf.constant(5, name="input_a")
b = tf.constant(3, name="input_b")
c = tf.multiply(a, b, name="mul_c")
d = tf.add(a, b, name="add_d")
e = tf.add(c, d, name="add_e")

with tf.Session() as sess:
print(sess.run(e)) # output => 23
writer = tf.summary.FileWriter("./hello_graph", sess.graph)


运行结果

23


启动tensorboard来查看这个Graph

tensorboard --logdir="hello_graph"


打开网页http://ubuntu:6006 并切换到GRAPHS标签

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: