這篇教程分爲兩部分,第一部分用例子解釋基礎概念,第二部分構建線性迴歸模型。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/