TensorFlow基本計算單元與基本操作

  • 2019 年 10 月 7 日
  • 筆記

在學習深度學習等知識之前,首先得了解著名的框架TensorFlow裡面的一些基礎知識,下面首先看一下這個框架的一些基本用法

import tensorflow as tf  a = 3  # Python中普通的變數創建方式    # Create a variable.  w = tf.Variable([[0.5, 1.0]]) # tensorflow創建變數方式  x = tf.Variable([[2.0], [1.0]])    y = tf.matmul(w, x) # 矩陣內積  變數的操作  print(y) # tensor  裡面沒有具體的值    # variables have to be explicitly initialized before you can run Ops  # 初始化全局變數 w,x,y  init_op = tf.global_variables_initializer()  # 計算圖  with tf.Session() as sess:      sess.run(init_op)      print(y.eval()) # 通過這種方式列印具體的值  

得到的結果是:

Tensor("MatMul_2:0", shape=(1, 1), dtype=float32)  [[2.]]

通過上面可以看出,只是簡單的一個矩陣的乘法,我們就寫了這麼多的程式碼,看起來比較麻煩,但是沒有辦法,要用這個框架就必須按照它的用法去用,但是在用這個框架來寫深度學習裡面的程式碼,那就不是很複雜了。上面的程式碼展示了TensorFlow框架的基本用法,導入庫、變數定義、初始化變數、Session操作、然後才能進行具體的操作

下面學習一下TensorFlow框架中一些函數的用法,可以和numpy庫中的一些函數對比著學習。

from numpy import int32  # float32 在TensorFlow最好使用這種格式    # 創建都是0的矩陣  tf.zeros([3, 4], int32)  # ==> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]    tensor = tf.constant([[1, 2, 3], [4, 5, 6]])  # 矩陣格式相似  tf.zeros_like(tensor)  # ==> [[0, 0, 0], [0, 0, 0]]    # 矩陣元素都為1  tf.ones([2, 3], int32)  # ==> [[1, 1, 1], [1, 1, 1]]  tf.ones_like(tensor)  # ==> [[1, 1, 1], [1, 1, 1]]    # Constant 1-D Tensor populated with value list.  # 創建一個常量,必須使用這種方式  tensor = tf.constant([1, 2, 3, 4, 5, 6, 7])  # => [1 2 3 4 5 6 7]    # Constant 2-D tensor populated with scalar value -1.  # 創建二維矩陣常量  tensor = tf.constant(-1.0, shape=[2, 3])  # => [[-1. -1. -1.]                                              #     [-1. -1. -1.]]    # 創建間隔矩陣  tf.linspace(10.0, 12.0, 3, name="linspace")  # => [ 10.0  11.0  12.0]    # 'start' is 3  # 'limit' is 18  # 'delta' is 3  # tf.range(start, limit, delta)  tf.range(3, 18, 3)# ==> [3, 6, 9, 12, 15]  

可以看出TensorFlow裡面一些函數和numpy裡面的用法差不多,下面看看TensorFlow中隨機數的一些用法。

# 高斯分布的均值矩陣  指定均值和方差  norm = tf.random_normal([2, 3], mean=-1, stddev=4)    # Shuffle the first dimension of a tensor  c = tf.constant([[1, 2], [3, 4], [5, 6]])    # shuffle操作  shuff = tf.random_shuffle(c)    # Each time we run these ops, different results are generated  # 要執行這些操作的方法。推薦使用上面With結構  sess = tf.Session()  print(sess.run(norm))  print(sess.run(shuff))  

運行得到的結果是

[[-2.4004993   5.356218    0.51297414]   [-4.353016    2.234075   -4.2948236 ]]  [[1 2]   [3 4]   [5 6]]

下面來看一個使用TensorFlow完成列印0到4之間的數字這樣的一個小栗子,在原生Python中很簡單,主要看看在TensorFlow中的用法。

# 列印0到4之間的的值  state = tf.Variable(0) # 初始化常量0  new_value = tf.add(state, tf.constant(1)) # 執行加1操作  update = tf.assign(state, new_value)  # 將new_value賦給state    # Session計算塊  with tf.Session() as sess:      sess.run(tf.global_variables_initializer())      print(sess.run(state))      for _ in range(3):          sess.run(update)          print(sess.run(state))  

得到的結果是

0  1  2  3

下面再來看看在創建變數時將numpy裡面的格式轉換為tensor格式,但是並不推薦使用這種方法

import numpy as np  a = np.zeros((3,3))    # 將numpy裡面的格式轉換為tensor格式,並不推薦使用這種方法  # 推薦使用上面創建變數的方法  ta = tf.convert_to_tensor(a)  with tf.Session() as sess:       print(sess.run(ta))  

得到的結果是

[[0. 0. 0.]   [0. 0. 0.]   [0. 0. 0.]]

下面再來看看TensorFlow中佔位符的用法

# 創建佔位符,用的時候再具體賦值。  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.]}))  

得到的結果是

[array([14.], dtype=float32)]

總結,這篇博文包含了TensorFlow框架中一些常見的用法,但是肯定很多細節沒有寫全,只是寫了一些大概的用法留作以後查看。