这篇教程分为两部分,第一部分用例子解释基础概念,第二部分构建线性回归模型。python
TensorFlow是一个数据流通过的图,数据表示为n维向量,图由数据和操做组成。linux
TensorFlow跟其余编程语言不一样之处在于不论你想建立什么都必须先建立一幅蓝图,默认初始化是不包含任何变量的。编程
sankit@sankit:~$ python Python 2.7.6 (default, Oct 26 2016, 20:30:19) [GCC 4.8.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import tensorflow as tf
数组
graph = tf.get_default_graph()
你能够获取图的所有操做:编程语言
graph.get_operations()
for op in graph.get_operations(): print(op.name)
你能够打印出它们的名字,固然在咱们没有添加操做以前,它仍是空的。工具
图用于定义操做,可是操做必须在会话中执行,它们之间是独立建立的,你能够把图想象为蓝图,把会话想象为建筑工地。this
图只定义了操做,但并无变量,更没有值,只有咱们在会话中运行图,这一切才有意义。spa
你能够像这样建立会话:code
sess=tf.Session() ... your code ... ... your code ... sess.close()
记得必定要关闭会话,或者你能够像这样使用:orm
with tf.Session() as sess: sess.run(f)
这样会话就自动关闭了,固然咱们也推荐你这样使用。
a=tf.constant(1.0) a <tf.Tensor'Const:0' shape=() dtype=float32> print(a) Tensor("Const:0", shape=(), dtype=float32)
它不能像Python同样打印或者访问,除非你在会话中使用:
with tf.Session() as sess: print(sess.run(a))
>>>b = tf.Variable(2.0,name="test_var") >>>b <tensorflow.python.ops.variables.Variable object at 0x7f37ebda1990>
with tf.Session() as sess: sess.run(init_op) print(sess.run(b))
这将输出2
如今咱们来打印图的操做:
graph = tf.get_default_graph() for op in graph.get_operations(): print(op.name)
输出:
Const
test_var/initial_value
test_var
test_var/Assign
test_var/read
init
就像你看到的,由于咱们使用了常量a,因此图中加入了Const.一样由于咱们定义了变量b,因此test_var开头的操做被加入到图中,你可使用名叫TensorBoard的工具来可视化一张图或者训练过程。
>>>a = tf.placeholder("float") >>>b = tf.placeholder("float") >>>y = tf.multiply(a, b) // Earlier this used to be tf.mul which has changed with Tensorflow 1.0 //Typically we load feed_dict from somewhere else, //may be reading from a training data folder. etc //For simplicity, we have put values in feed_dict here >>>feed_dict ={a:2,b:3} >>>with tf.Session() as sess: print(sess.run(y,feed_dict))
TensorFlow内建的的能力很是强大,为你提供了运行在GPU或者CPU集群的选择
reference:https://cv-tricks.com/artificial-intelligence/deep-learning/deep-learning-frameworks/tensorflow/tensorflow-tutorial/