tensorflow笔记
生活随笔
收集整理的這篇文章主要介紹了
tensorflow笔记
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
**TensorFlow基礎:TensorFlow三個基礎核心概念:計算圖、Tensor、Session計算圖:
在TensorFlow中,計算圖是一個有向圖,用來描述計算節點以及計算節點之間的關系,所以在TensorFlow中我們存儲一個值或者數組的時候,存的其實是這個值或者數組的計算圖而不是其本身的數字。我們可以用寫一個簡單的例子來驗證一下:#GPU版本
import tensorflow as tf
g=tf.Graph()
with g.device("/gpu:0"):#c=lambda a,b:a+bd=tf.constant([10,9,8,7])e=tf.constant([1,2,3,4])f_1=d+fprint(f_1.graph)print(d.graph,e.graph)sess=tf.Session()print(sess.run(f_1))#CPU版
import tensorflow as tfa=tf.constant([1,2,3,4],name='a')
b=tf.constant([0,1,2,3],name='b')
c=a+b
print(a.graph,b.graph)
print(c.graph)sess=tf.Session()print(sess.run(c))關于計算圖的操作
1、新建計算圖:g=tf.Graph(),但是不同計算圖上的張量是不能共享的,這個是存在于變量
2、指定計算圖的使用的device:with g.device("/gpu:0"):
3、設置默認計算圖:with g.as_default:
4、在會話中可以指定使用的計算圖:with tf.Session(graph=g1):
對于以上操作用代碼說話,建議大家和我一起寫,這樣才會有比較大的體會和能夠記住,import tensorflow as tfg1=tf.Graph()
with g1.as_default():a=tf.constant([1,2,3],name="a")#用常量試試看b=tf.get_variable('b',initializer=tf.constant_initializer()(shape = [1]))#用變量試試看
g2=tf.Graph()
with g2.as_default():a=tf.constant([2,3],name="a")#用常量試試看b=tf.get_variable('b',initializer=tf.constant_initializer()(shape = [3]))#用常量試試看with tf.Session(graph=g2) as sess:with g1.device("/cpu:0"):tf.global_variables_initializer().run()c=a+1print("常量的情況下",sess.run(c))with tf.variable_scope("", reuse=True):print("變量情況下",sess.run(tf.get_variable("b")))
with tf.Session(graph=g2) as sess:with g2.device("/gpu:0"):tf.global_variables_initializer().run()c=a+1print("常量的情況下",sess.run(c))with tf.variable_scope("", reuse=True):print("變量情況下",sess.run(tf.get_variable("b")))張量:
張量(tensor)可以簡單理解為多維數組。其中零階張量表示標量(scalar),也就是一個數;一階張量為向量(vector),也就是一維數組;第n階張量可以理解為一個n維數組。但是張量在Tensorflow中的實現并不是直接采用數組的形式,它只是對Tensorflow中運算結果的引用。在張量中并沒有真正保存數字,它保存的是如何得到這些數字的計算過程。import tensorflow as tfa=tf.constant(2,name='a')
b=tf.constant([0,1,2,3],name='b')
c=a*b
print(a,b)
print(c)sess=tf.Session()print(sess.run(c))會話:
在TensorFlow中,計算圖的計算過程都是在會話下進行的,同一個會話內的數據是可以共享的,會話結束計算的中間量就會消失。在TensorFlow需要指定會話。import tensorflow as tfwith tf.Session as sess:print(sess.run(result))sess=tf.Session()
with sess.as_default():print(result.eval())sess = tf.InteractiveSession()#會自動成為默認會話TensorFlow 基礎API介紹
我們這個課程的是將TensorFlow的高階API,但是由于在我們的應用案例中不可能都是高階API,還會涉及到一些常用必須的基礎的API,我們在開始講高階API之前也先簡單講一下低階的基礎API.根據TensorFlow官網以及在日常的編程中的使用情況,我梳理了以下需要掌握的TensorFlow基礎API:tf.Graph():
tf.Graph.device():
tf.Graph.as_default():
tf.Session():
tf.Session.run():
tf.Session.as_default():
tf.InteractiveSession():
tf.constant():
tf.variable():
tf.get_variable():
tf.placeholder():
tf.agrmax
tf.train()
tf.nn()
前面我們在講解計算圖、張量、會話時有些基礎的API已經講解了,在這里我們就不重復講。我們這里重點講一下tf.train和tf.nn這兩個非常重要的API.**
總結
以上是生活随笔為你收集整理的tensorflow笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华夏保险到期取钱步骤
- 下一篇: 买房怎么贷款最划算 考虑好这几点就可以