tessorflow基本语法
文章目錄
- tessorflow基本語法
- 占位符、字典、數值運算
- shape函數
- perm函數
- tf.random_normal()函數
- 矩陣相乘、相減、初始化
- 變量
- Fetch
- Feed
- tf.strided_slice函數
- 一維數組
- 二維數組
- 三維數組
- tf.nn.in_top_k的用法
- 實現簡單可視化
tessorflow基本語法
占位符、字典、數值運算
import tensorflow as tf#定義‘符號’變量,也稱為占位符 a = tf.placeholder("float") b = tf.placeholder("float") y = tf.multiply(a, b) # 構造一個op節點,每一個運算操作opretion作為一個節點 sess = tf.Session() # 建立會話 # 運行會話,輸入數據,并計算節點,同時打印結果 print(sess.run(y, feed_dict={a: 3, b: 3})) # 任務完成, 關閉會話 sess.close()shape函數
shape函數是numpy.core.fromnumeric中的函數,它的功能是讀取矩陣的長度。shape的輸入參數可以是一個整數(表示維度),也可以是一個矩陣
(1)參數是一個數時,返回空: >>> import numpy as np >>> np.shape(0) () (2)參數是一個一維矩陣: >>> np.shape([1]) (1,) >>> np.shape([1,2]) (2,) (3)參數是一個二維矩陣: >>> np.shape([[1],[2]]) (2, 1) >>> np.shape([[1,1],[2,2],[3,3]]) (3, 2) (4)參數是一個三維矩陣: 1. >>> a=np.array([[[1, 2, 3],[4, 5, 6]],[[7, 8, 9],[10, 11, 12]]]) >>> a.shape (2, 2, 3) >>> a array([[[ 1, 2, 3],[ 4, 5, 6]],[[ 7, 8, 9],[10, 11, 12]]]) 2. >>> a=np.array([[[1, 2, 3],[4, 5, 6]],[[7, 8, 9],[10, 11, 12]],[[7, 8, 9],[10, 11, 12]]]) >>> a array([[[ 1, 2, 3],[ 4, 5, 6]],[[ 7, 8, 9],[10, 11, 12]],[[ 7, 8, 9],[10, 11, 12]]]) >>> a.shape (3, 2, 3) conclusion:三維數組中,第一位數字表示二維數組的個數,第二位數字表示二維數組的行數,第三位數字表示二維數組的列數 (5)直接用.shape可以快速讀取矩陣的形狀,使用shape[0]讀取矩陣行數,shape[1]讀取矩陣列數 >>> a=np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> a array([[1, 2, 3],[4, 5, 6],[7, 8, 9]]) >>> a.shape (3, 3) >>> a.shape[0] 3 >>> a.shape[1] 3 (6)但是當某一維度長度不一致時,讀取所有維度時則不能讀出長短不一致的維度 >>> a=np.array([[1,2,3],[4,5]]) >>> a array([[1, 2, 3], [4, 5]], dtype=object) >>> a.shape (2,) >>> a.shape[0] 2 >>> a.shape[1] Traceback (most recent call last):File "<pyshell#57>", line 1, in <module>a.shape[1] IndexError: tuple index out of rangeperm函數
(1)對于二維數組,perm=[0,1],0代表二維數組的行,1代表二維數組的列。perm[1,0]代表將數組的行和列進行交換,代表矩陣的轉置(2)對于三維數組,perm=[0,1,2],0代表三維數組的高(即為二維數組的個數),1代表二維數組的行,2代表二維數組的列。tf.transpose(x, perm=[1,0,2])代表將三位數組的高和行進行轉置
import tensorflow as tf import numpy as np# 設計一個3維數組 x = tf.placeholder('float') # 加法器 y = tf.add(x, x) # 隨機產生一個2*2 數組 rand_array1 = np.random.rand(2, 2) # 兩個中括號,二維 # print(rand_array1)rarray = [rand_array1] # 又加中括號,二維變三維 # print(rarray)with tf.Session() as sess: # 使用with代碼塊可以自動關閉sess對話print(sess.run(y, feed_dict={x: rarray}))sess = tf.Session() x = [[1, 2, 3], [4, 5, 6]] t1 = tf.transpose(x) # transpose(x)轉置 t2 = tf.transpose(x, perm=[1, 0]) # perm=[1, 0],將數組的行和列進行交換 x = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]] # x.shape=(2,2,3),表示兩個2*3的二維數組 t3 = tf.transpose(x, perm=[0, 2, 1]) # 表示將數組的行和列進行交換 print(sess.run(t1)) print() print(sess.run(t2)) # t1和t2結果一樣 print() print(sess.run(t3)) sess.close()可以將sess = tf.Session()和sess.close()去掉,將后續的代碼對齊到print(…),也可實現相同的效果。
tf.random_normal()函數
tf.random_rand(3,2)返回一個隨機值介于0~1之間的三行兩列的數組
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)正態(高斯)分布
shape形狀,必選
mean均值,默認為0
stddev標準差,默認為1
dtype數據類型,默認為tf.float32
seed隨機數種子,是一個整數,設置以后,每次生成的隨機數都一樣
name操作的名稱
疑問:結果:[[-0.8113182 1.4845988 ]
[ 0.06532937 -2.4427042 ]]的標準差等于1.6439
疑問解決:其實,在生成均值為0,方差為1的隨機數時,matlab要遵守一定的算法,這個算法保證在數據量非常大時,其均值為0,方差為1,但并不能保證數據量非常小時,計算其均值和方差也是0和1
標準差MATLAB公式:
(1)一維數組
(1)二維數組
std2(A)
補充:
運行結果:[-0.28473374 0.36357746 -0.04123257 -0.7963872 0.41197917]
w1 = tf.random_normal((5,))改成w1 = tf.random_normal((1,5))
運行結果:[[-0.17727162 -0.8383046 0.22584556 0.04784792 0.64250875]]
w1 = tf.random_normal((1,5))改成w1 = tf.random_normal([1,5])
運行結果:[[-0.8113182 1.4845988 0.06532937 -2.4427042 0.0992484 ]]
conclusion:
矩陣相乘、相減、初始化
sess = tf.InteractiveSession()與 sess = tf.Session()
區別:tf.InteractiveSession()是一種交互式的session方式,它讓自己成為了默認的session。用戶在不需要指明用哪個session運行的情況下,就可以運行起來。run()和eval()函數可以不指明session。它允許變量不需要使用session就可以產生結構。
疑問:最后一個模塊有bug
解決:"gpu:1"改為"cpu:0"可解決問題,因為我所運行的電腦沒有gpu,只有一個cpu,而python是從0開始計數的。
變量
# 創建一個變量, 初始化為標量 0. import tensorflow as tf state = tf.Variable(0, name="counter")# 創建一個 op, 其作用是使 state 增加 1one = tf.constant(2) new_value = tf.add(state, one) update = tf.assign(state, new_value)# 啟動圖后, 變量必須先經過`初始化` (init) op 初始化, # 首先必須增加一個`初始化` op 到圖中. init_op = tf.initialize_all_variables()# 啟動圖, 運行 op with tf.Session() as sess:# 運行 'init' opsess.run(init_op)# 打印 'state' 的初始值# print(sess.run(state))# 運行 op, 循環3次,更新 'state', 并打印 'state'for j in range(3):sess.run(update)print(sess.run(state))結果:
2
4
6
Fetch
需要獲取的多個 tensor 值,在 op 的一次運行中一起獲得(而不是逐個去獲取 tensor)
# 創建一個變量, 初始化為標量 0. import tensorflow as tf input1 = tf.constant(3.0) input2 = tf.constant(2.0) input3 = tf.constant(5.0) intermed = tf.add(input2, input3) mul = tf.multiply(input1, intermed)with tf.Session() as sess:result = sess.run([mul, intermed])print(result)Feed
feed 使用一個 tensor 值臨時替換一個操作的輸出結果. 你可以提供 feed 數據作為 run() 調用的參數. feed 只在調用它的方法內有效, 方法結束, feed 就會消失. 最常見的用例是將某些特殊的操作指定為 “feed” 操作, 標記的方法是使用 tf.placeholder() 為這些操作創建占位符.
# 創建一個變量, 初始化為標量 0. import tensorflow as tf input1 = tf.placeholder(tf.float32) input2 = tf.placeholder(tf.float32) output = tf.multiply(input1, input2)with tf.Session() as sess:print(sess.run([output], feed_dict={input1:[7.], input2:[2.]}))tf.strided_slice函數
一維數組
import tensorflow as tf data = [1,2,3,4,5,6,7,8] x = tf.strided_slice(data,[0],[4]) y = tf.strided_slice(data,[1],[5]) with tf.Session() as sess:print(sess.run(x))print(sess.run(y))結果
[1 2 3 4]
[2 3 4 5]
tf.strided_slice(data,[a],[b])函數的三個值為:原數據,起始位置a,終點位置b,即a<=x<b
二維數組
import tensorflow as tf data = [[1,2,3,4,5,6,7,8],[11,12,13,14,15,16,17,18]] x1 = tf.strided_slice(data,[0,0],[1,4]) x2 = tf.strided_slice(data,[0,1],[1,4]) x3 = tf.strided_slice(data,[1,0],[2,4]) x4 = tf.strided_slice(data,[1,0],[1,4]) x5 = tf.strided_slice(data,[1,1],[2,5]) with tf.Session() as sess:print(sess.run(x1))print(sess.run(x2))print(sess.run(x3))print(sess.run(x4))print(sess.run(x5))結果:
[[1 2 3 4]]
[[2 3 4]]
[[11 12 13 14]]
[]
[[12 13 14 15]]
tf.strided_slice(data,[a1,a2],[b1,b2])函數,
a1代表索引為a1的一維數組
a2代表索引為a1的一維數組中,索引為a2的數值
b1代表第b1行
b2代表第b1行中索引為b2的數值
三維數組
import tensorflow as tf data = [[[1, 1, 1], [2, 2, 2]],[[3, 3, 3], [4, 4, 4]],[[5, 5, 5], [6, 6, 6]]] x = tf.strided_slice(data,[2,0,0],[3,2,3]) with tf.Session() as sess:print(sess.run(x))結果:
[[[5 5 5]
[6 6 6]]]
以三維數組中索引為2的二維數組,索引為0的一維數組,索引為0的數字開始,以三維數組中第3個二維數組中,第2個一維數組中,索引為3的數字結束
tf.nn.in_top_k的用法
目的:用于計算預測的結果和實際結果的是否相等,返回一個bool類型的張量
tf.nn.in_top_k(prediction, target, K):
prediction就是表示你預測的結果,大小就是預測樣本的數量乘以輸出的維度,類型是tf.float32等。
target就是實際樣本類別的標簽,大小就是樣本數量的個數。
K表示每個樣本的預測結果的前K個最大的數的索引里面是否含有target中的值。一般都是取1。
K=1,表示每個樣本的預測結果的最大數的索引是否與target中的值(索引值)相等。
輸出:
[False True]
解釋:因為A張量里面的第一個元素的最大值的標簽是0,第二個元素的最大值的標簽是1.。但是實際的確是1和1.所以輸出就是False 和True。如果把K改成2,那么第一個元素的前面2個最大的元素的位置是0,1,第二個的就是1,2。實際結果是1和1。包含在里面,所以輸出結果就是True 和True.如果K的值大于張量A的列,那就表示輸出結果都是true
實現簡單可視化
import tensorflow as tfprint('version:', tf.__version__) foo = tf.Variable(3, name='foo') bar = tf.Variable(2, name='bar') result = tf.add(foo, bar, name='add') #初始化變量 init = tf.global_variables_initializer() #啟動圖 (graph) sess = tf.Session() sess.run(init) print('result:', sess.run(result)) train_writer = tf.summary.FileWriter('/tmp/tensorflow/add/logs/testTf/train',sess.graph) #結果存放路徑會發現這個log文件按指定位置存在:
copy此路徑:tensorboard --logdir=C:\tmp\tensorflow\add\logs\testTf\train
粘貼到terminal中:
復制http://susan-HP:6006 到谷歌瀏覽器,即可看到gragh
由于版本的更新,可能會出現以下問題,下面給出解決方案:
解決方案:找到manager.py, 更改代碼
解決方案:timinal輸入pip install h5py==2.8.0rc1
總結
以上是生活随笔為你收集整理的tessorflow基本语法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MATLAB之线性回归,逻辑回归,最小二
- 下一篇: tessorflow实战