1. 程式人生 > >(tensorflow之十二)tensorflow與numpy函式的選擇(以reshape為例)

(tensorflow之十二)tensorflow與numpy函式的選擇(以reshape為例)

tensorflow與numpy均提供了強大的矩陣運算功能,很多矩陣的運算函式功能是重複的。

那什麼時候選擇用tensorflow,什麼時候選擇用numpy呢?

這個的選擇需正確的理解tensorflow與numpy計算過程的區別。

tensorflow的計算一般可分成兩個階段:

  • 第一階段,定義所有的計算過程,即計算流圖。在這個階段,所有的變數均無實際引數值,僅僅表示一個計算過程;
  • 第二階段,執行運算,建立會話(Session),此時才會對變數進行賦值;

而numpy的計算,會直接對具體的引數值進行運算。

因此,在tensoflow的第一階段,表示計算過程時,必段選用tensorflow的函式;而在第二階段,或者對已有具體引數值進行運算時,則需選擇numpy。

具體可參考示意如下(以reshape函式為例):

import tensorflow as tf
import numpy as np
#矩陣a已經具有實際引數值,需選用numpy的reshape函式
a = [[3.0,2.0,1.0],[3.0,4.0,5.0],[7.0,8.0,9.0]]
b = np.reshape(a,[9])
#矩陣c是張量,在執行sess.run()無實際引數值,需選用tensorflow的reshape函式
c = tf.get_variable('c',[3,3],tf.float32,initializer=tf.truncated_normal_initializer(stddev=0.1))
d = tf.reshape(c,[9])

with tf.Session() as sess:
    tf.initialize_all_variables().run()
    print('the a is')
    print(a)
    print('the b is')
    print(b)
    print('the c is')
    print(sess.run(c))
    print('the d is')
    print(sess.run(d))
    print('the e is')
	#在執行sess.run(c)時,sess.run(c)已經具有實際引數值,則需選用numpy的reshape函式
    e = np.reshape(sess.run(c),[9])
    print(e)
執行結果如下:
the a is
[[3.0, 2.0, 1.0], [3.0, 4.0, 5.0], [7.0, 8.0, 9.0]]
the b is
[ 3.  2.  1.  3.  4.  5.  7.  8.  9.]
the c is
[[ 0.02078418  0.08195087  0.05464306]
 [-0.05831626 -0.11729162  0.14623356]
 [ 0.0392873  -0.04524051 -0.09136122]]
the d is
[ 0.02078418  0.08195087  0.05464306 -0.05831626 -0.11729162  0.14623356
  0.0392873  -0.04524051 -0.09136122]
the e is
[ 0.02078418  0.08195087  0.05464306 -0.05831626 -0.11729162  0.14623356
  0.0392873  -0.04524051 -0.09136122]