日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

tessorflow基本语法

發布時間:2025/3/21 编程问答 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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] 36)但是當某一維度長度不一致時,讀取所有維度時則不能讀出長短不一致的維度 >>> 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 range

perm函數

(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操作的名稱

#產生服從正態分布的數組 # tf.random_normal()正態分布函數 tf.random_uniform()均勻分布函數 # -*- coding: utf-8 -*-) import tensorflow as tf #shape為(2,2),標準差為1,隨機種子為1 w1 = tf.Variable(tf.random_normal([2, 2], stddev=1, seed=1))with tf.Session() as sess:sess.run(tf.global_variables_initializer())#變量w1聲明之后并沒有被賦值,需要在Session中調用run(tf.global_variables_initializer())方法初始化之后才會被具體賦值。# sess.run(tf.initialize_all_variables()) #比較舊一點的初始化變量方法print(w1) #獲取w1的形狀和數據類型等屬性信息print(sess.run(w1)) # 獲取w1的值需要調用sess.run(w1)方法

疑問:結果:[[-0.8113182 1.4845988 ]
[ 0.06532937 -2.4427042 ]]的標準差等于1.6439
疑問解決:其實,在生成均值為0,方差為1的隨機數時,matlab要遵守一定的算法,這個算法保證在數據量非常大時,其均值為0,方差為1,但并不能保證數據量非常小時,計算其均值和方差也是0和1

MATLAB舉例:R = random('Normal',0,1,2,4): 生成期望為 0,標準差為 1 的(2 行 4 列)2× 4 個正態隨機數 R = random('Normal',0,1,2,4) >> std2(R)1.0619 R = random('Normal',0,1,2000,4000) >> std2(R) 0.9998 可見隨著數據量的增大,偏差值越趨于真實值。

標準差MATLAB公式:
(1)一維數組

(1)二維數組
std2(A)
補充:

import tensorflow as tfw1 = tf.random_normal((5,)) with tf.Session() as sess:sess.run(tf.global_variables_initializer())print(sess.run(w1))

運行結果:[-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:

  • shape的括號可以是小括號或者中括號。
  • shape為(5,),表示一行5列的一維向量空間;shape為(1,5),表示一行5列的二維向量空間
  • 向量維數:向量分量的個數。向量空間的維數(不能少于兩個):向量空間是由好多個向量組成的空間
  • 矩陣相乘、相減、初始化

    sess = tf.InteractiveSession()與 sess = tf.Session()
    區別:tf.InteractiveSession()是一種交互式的session方式,它讓自己成為了默認的session。用戶在不需要指明用哪個session運行的情況下,就可以運行起來。run()和eval()函數可以不指明session。它允許變量不需要使用session就可以產生結構。

    # 進入一個交互式 TensorFlow 會話. import tensorflow as tf sess = tf.InteractiveSession()x = tf.Variable([1.0, 2.0]) a = tf.constant([3.0, 3.0])# 使用初始化器 initializer op 的 run() 方法初始化 'x' x.initializer.run()# 增加一個減法 sub op, 從 'x' 減去 'a'. 運行減法 op, 輸出結果 sub = tf.subtract(x, a) print(sub.eval()) # ==> [-2. -1.] #矩陣相乘 import tensorflow as tf sess = tf.InteractiveSession() #建立兩個矩陣變量w1和w2 w1 = tf.Variable(tf.random_normal([2,3],mean=1.0, stddev=1.0)) w2 = tf.Variable(tf.random_normal([3,1],mean=1.0, stddev=1.0))#定義一個二維的常量矩陣,注意:這里不是一維數組 x = tf.constant([[0.7, 0.9]]) # print(sess.run(x))#初始化全局變量,這里由于只有w1和w2沒有被初始化(之前只是定義了w1和w2的tensor,并沒有被初始化),故這一步只會初始化w1和w2. tf.global_variables_initializer().run() #在完全構建好模型并加載之后才運行這個操作 #tf.initialize_all_variables().run() #這種寫法也可,官方推薦使用上面的寫法#計算矩陣相乘a=x*w1 a = tf.matmul(x ,w1) #矩陣相乘tf.matmul(a,b) #計算矩陣相乘y=a*w2 y = tf.matmul(a, w2) #輸出計算結果,是一個1行1列的二維矩陣 print(y.eval()) print(sess.run(y)) #結果與上行相同 import tensorflow as tf# 創建一個常量 op, 產生一個 1x2 矩陣. 這個 op 被作為一個節點 # 加到默認圖中 # 構造器的返回值代表該常量 op 的返回值. matrix1 = tf.constant([[3., 3.]]) # 創建另外一個常量 op, 產生一個 2x1 矩陣. matrix2 = tf.constant([[2.],[2.]]) # 創建一個矩陣乘法 matmul op , 把 'matrix1' 和 'matrix2' 作為輸入. # 返回值 'product' 代表矩陣乘法的結果. product = tf.matmul(matrix1, matrix2)# 啟動默認圖. sess = tf.Session() # 調用 sess 的 'run()' 方法來執行矩陣乘法 op, 傳入 'product' 作為該方法的參數. # 上面提到, 'product' 代表了矩陣乘法 op 的輸出, 傳入它是向方法表明, 我們希望取回 # 矩陣乘法 op 的輸出. # 整個執行過程是自動化的, 會話負責傳遞 op 所需的全部輸入. op 通常是并發執行的. # 函數調用 'run(product)' 觸發了圖中三個 op (兩個常量 op 和一個矩陣乘法 op) 的執行. # 返回值 'result' 是一個 numpy `ndarray` 對象. result = sess.run(product) print(result) # ==> [[ 12.]] # 任務完成, 關閉會話. sess.close() import tensorflow as tf with tf.Session() as sess:with tf.device("gpu:1"):matrix1 = tf.constant([[3., 3.]])matrix2 = tf.constant([[2.],[2.]])product = tf.matmul(matrix1, matrix2)print(sess.run(product))

    疑問:最后一個模塊有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中的值(索引值)相等。

    import tensorflow as tfA = [[0.8, 0.6, 0.3], [0.1, 0.6, 0.4]] B = [1, 1] out = tf.nn.in_top_k(A, B, 1) with tf.Session() as sess:sess.run(tf.initialize_all_variables())print(sess.run(out))

    輸出:
    [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

    由于版本的更新,可能會出現以下問題,下面給出解決方案:

  • 粘貼到terminal中可能出現以下錯誤

    解決方案:找到manager.py, 更改代碼

  • FutureWarning: Conversion of the second argument of issubdtype from float to…
    解決方案:timinal輸入pip install h5py==2.8.0rc1
  • sd-20190404yevy 拒絕了我們的連接請求
  • 總結

    以上是生活随笔為你收集整理的tessorflow基本语法的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。