python、numpy,keras,tensorflow等函数用法积累(持续更新)
目錄
?
Numpy:
np.random.choice()
Tensorflow:
tf.Session()
session的創建:
session的參數:
session的run方法
tf.truncated_normal(shape, mean, stddev)
tf.variable()圖變量
1.圖變量的初始化:
2. 兩種定義圖變量的方法
3.?scope劃分命名空間
4. 圖變量的種類
?
tf.placeholder? & feed_dict
?
tf.truncated_normal(shape, mean, stddev)
tf.reduce_sum()
Numpy:
np.random.choice()
numpy.random.choice(a, size=None, replace=True, p=None) :
從a(只要是ndarray都可以,但必須是一維的)中隨機抽取數字,并組成指定大小(size)的數組 ;
replace:True表示可以取相同數字,False表示不可以取相同數字
數組p:與數組a相對應,表示取數組a中每個元素的概率,默認為選取每個元素的概率相同。
Tensorflow:
tf.Session()
session是客戶端與整個TensorFlow系統交互的接口.
在tensorflow中數據流圖中的Op在得到執行之前,必須先創建Session對象,Session對象負責著圖中所有Op的執行。
session的創建:
# 創建本地 session with tf.Session() as sess:# ...# 創建遠程 session with tf.Session("grpc://example.org:2222"):# ...session的參數:
主要有三個參數:
1.target, 用來控制 session 使用的硬件設備, 如果使用空值,那么這個 session 就只會使用本地的設備,如果使用 grpc:// URL,那么就會使用這臺服務器控制的所有設備。
2.graph, 用來控制該 session 運行哪個計算圖,如果為空,那么該 session 就只會使用當前的默認 Graph,如果使用多個計算圖,就可以在這里指定。
3.config, 用來 指定一個?tf.ConfigProto?格式的 session 運行配置,比如說它里面包含的 allow_soft_placement 如果指定為 TRUE,那么 session 就會自動把不適合在 GPU 上運行的 OP 全部放到 CPU 上運行;cluster_def 是分布式運行時候需要指定的配置;gpu_options.allow_growth 設置會使得程序在開始時候逐步的增長 GPU 顯存使用量,而不是一開始就最大化的使用所有顯存。第一個和第三個配置是經常用到的。
session的run方法
tf.Session.run?是運行 OP 和獲取 tensor 的值的主要方式,可以一次性傳入多個 OP 和 tensor 給它,然后TensorFlow 會自動執行所有需要的 OP 來得到結果
?
tf.truncated_normal(shape, mean, stddev)
截斷的產生正態分布的隨機數,即隨機數與均值的差值若大于兩倍的標準差,則重新生成。
- shape,生成張量的維度
- mean,均值
- stddev,標準差
?
tf.variable()圖變量
1.圖變量的初始化:
In [1]: import tensorflow as tf In [2]: x = tf.Variable(3, name='x') In [3]: y = x * 5 In [4]: sess = tf.InteractiveSession() In [5]: sess.run(tf.global_variables_initializer()) In [6]: sess.run(y) Out[6]: 15在TensorFlow的世界里,變量的定義和初始化是分開的,所有關于圖變量的賦值和計算都要通過tf.Session的run來進行。想要將所有圖變量進行集體初始化時應該使用tf.global_variables_initializer。
2. 兩種定義圖變量的方法
(1)tf.Variable.init(initial_value, trainable=True, collections=None, validate_shape=True, name=None):
雖然有一堆參數,但只有第一個參數initial_value是必需的,用法如下(assign函數用于給圖變量賦值):
In [1]: import tensorflow as tf In [2]: v = tf.Variable(3, name='v') In [3]: v2 = v.assign(5) In [4]: sess = tf.InteractiveSession() In [5]: sess.run(v.initializer) In [6]: sess.run(v) Out[6]: 3 In [7]: sess.run(v2) Out[7]: 5(2)tf.get_variable:tf.get_variable必需參數(即第一個參數)并不是圖變量的初始值,而是圖變量的名稱。
In [1]: import tensorflow as tf In [2]: init = tf.constant_initializer([5]) In [3]: x = tf.get_variable('x', shape=[1], initializer=init) In [4]: sess = tf.InteractiveSession() In [5]: sess.run(x.initializer) In [6]: sess.run(x) Out[6]: array([ 5.], dtype=float32)用法要更豐富一點,當指定名稱的圖變量已經存在時表示獲取它,當指定名稱的圖變量不存在時表示定義它
3.?scope劃分命名空間
TensorFlow的命名空間分為兩種,tf.variable_scope和tf.name_scope。
區別如下:
當使用tf.get_variable定義變量時,如果出現同名的情況將會引起報錯:
In [1]: import tensorflow as tf In [2]: with tf.variable_scope('scope'):...: v1 = tf.get_variable('var', [1])...: v2 = tf.get_variable('var', [1]) ValueError: Variable scope/var already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:而對于tf.Variable來說,卻可以定義“同名”變量
In [1]: import tensorflow as tf In [2]: with tf.variable_scope('scope'):...: v1 = tf.Variable(1, name='var')...: v2 = tf.Variable(2, name='var')...: In [3]: v1.name, v2.name Out[3]: ('scope/var:0', 'scope/var_1:0')但是把這些圖變量的name屬性打印出來,就可以發現它們的名稱并不是一樣的。
如果想使用tf.get_variable來定義另一個同名圖變量,可以考慮加入新一層scope,比如:
In [1]: import tensorflow as tf In [2]: with tf.variable_scope('scope1'):...: v1 = tf.get_variable('var', shape=[1])...: with tf.variable_scope('scope2'):...: v2 = tf.get_variable('var', shape=[1])...: In [3]: v1.name, v2.name Out[3]: ('scope1/var:0', 'scope1/scope2/var:0')?
當tf.get_variable遇上tf.name_scope,它定義的變量的最終完整名稱將不受這個tf.name_scope的影響,如下:
In [1]: import tensorflow as tf In [2]: with tf.variable_scope('v_scope'):...: with tf.name_scope('n_scope'):...: x = tf.Variable([1], name='x')...: y = tf.get_variable('x', shape=[1], dtype=tf.int32)...: z = x + y...: In [3]: x.name, y.name, z.name Out[3]: ('v_scope/n_scope/x:0', 'v_scope/x:0', 'v_scope/n_scope/add:0')4. 圖變量的種類
TensorFlow的圖變量分為兩類:local_variables和global_variables。
如果我們想定義一個不需要長期保存的臨時圖變量,可以這樣定義它:
with tf.name_scope("increment"):zero64 = tf.constant(0, dtype=tf.int64)current = tf.Variable(zero64, name="incr", trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES])?
tf.placeholder? & feed_dict
TensorFlow 支持占位符placeholder。占位符并沒有初始值,它只會分配必要的內存。在會話中,占位符可以使用 feed_dict 饋送數據。
feed_dict是一個字典,在字典中需要給出每一個用到的占位符的取值。
在訓練神經網絡時需要每次提供一個批量的訓練樣本,如果每次迭代選取的數據要通過常量表示,那么TensorFlow 的計算圖會非常大。因為每增加一個常量,TensorFlow 都會在計算圖中增加一個結點。所以說擁有幾百萬次迭代的神經網絡會擁有極其龐大的計算圖,而占位符卻可以解決這一點,它只會擁有占位符這一個結點。
placeholder函數的定義為:
tf.placeholder(dtype, shape=None, name=None) 參數:dtype:數據類型。常用的是tf.int32,tf.float32,tf.float64,tf.string等數據類型。shape:數據形狀。默認是None,也就是一維值。也可以表示多維,比如要表示2行3列則應設為[2, 3]。形如[None, 3]表示列是3,行不定。name:名稱。 返回:Tensor類型例子:3個
import tensorflow as tfx = tf.placeholder(tf.string)with tf.Session() as sess:output = sess.run(x, feed_dict={x: 'Hello World'})print(output)運行結果:Hello World ------------------------------------------------ import tensorflow as tfx = tf.placeholder(tf.string) y = tf.placeholder(tf.int32) z = tf.placeholder(tf.float32)with tf.Session() as sess:output = sess.run(x, feed_dict = {x :'Hello World', y:123, z:45.67})print(output)output = sess.run(y, feed_dict = {x :'Hello World', y:123, z:45.67})print(output)output = sess.run(z, feed_dict = {x :'Hello World', y:123, z:45.67}) print(output)運行結果: Hello Word 123 45.66999816894531 ---------------------------------------------------- import tensorflow as tf import numpy as npx = tf.placeholder(tf.float32, shape=(3, 3)) y = tf.matmul(x, x) with tf.Session() as sess: rand_array = np.random.rand(3, 3) print(sess.run(y, feed_dict = {x: rand_array})) 運行結果: [[0.62475741 0.40487182 0.5968855 ][0.17491265 0.08546661 0.23616122][0.53931886 0.24997233 0.56168258]]?
tf.truncated_normal(shape, mean, stddev)
從一個正態分布片段中輸出隨機數值。shape表示生成張量的維度,mean是均值,stddev是標準差
這是一個截斷的產生正態分布的函數,均值和標準差自己設定。產生正態分布的值如果與均值的差值大于兩倍的標準差,那就重新生成。
例子:
import tensorflow as tf; import numpy as np; import matplotlib.pyplot as plt;c = tf.truncated_normal(shape=[10,10], mean=0, stddev=1)with tf.Session() as sess:print sess.run(c)結果:
[[ 1.95758033 -0.68666345 -1.83860338 ?0.78213859 -1.08119416 -1.44530308
? ?0.38035342 ?0.57904619 -0.57145643 -1.22899497]
?[-0.75853795 ?0.48202974 ?1.03464043 ?1.19210851 -0.15739718 ?0.8506189
? ?1.18259966 -0.99061841 -0.51968449 ?1.38996458]
?[ 1.05636907 -0.02668529 ?0.64182931 ?0.4110294 ?-0.4978295 ?-0.64912242
? ?1.27779591 -0.01533993 ?0.47417602 -1.28639436]
?[-1.65927458 -0.364887 ? -0.45535028 ?0.078814 ? -0.30295736 ?1.91779387
? -0.66928798 -0.14847915 ?0.91875714 ?0.61889237]
?[-0.01308221 -0.38468206 ?1.34700036 ?0.64531708 ?1.15899456 ?1.09932268
? ?1.22457981 -1.1610316 ? 0.59036094 -1.97302651]
?[-0.24886213 ?0.82857937 ?0.09046989 ?0.39251322 ?0.21155456 -0.27749416
? ?0.18883201 ?0.08812679 -0.32917103 ?0.20547724]
?[ 0.05388507 ?0.45474565 ?0.23398806 ?1.32670367 -0.01957406 ?0.52013856
? -1.13907862 -1.71957874 ?0.75772947 -1.01719368]
?[ 0.27155915 ?0.05900437 ?0.81448066 -0.37997526 -0.62020499 -0.88820189
? ?1.53407145 -0.01600445 -0.4236775 ?-1.68852305]
?[ 0.78942037 -1.32458341 -0.91667277 -0.00963761 ?0.76824385 -0.5405798
? -0.73307443 -1.19854116 -0.66179073 ?0.26329204]
?[ 0.59473759 -0.37507254 -1.21623695 -1.30528259 ?1.18013096 -1.32077384
? -0.59241474 -0.28063133 ?0.12341146 ?0.48480138]]
?
tf.reduce_sum()
reduce_sum(input_tensor,axis=None,keep_dims=False,name=None,reduction_indices=None )reduce_sum() 就是求和,由于求和的對象是tensor,所以是沿著tensor的某些維度求和。函數名中加了reduce是表示求和后會降維,當然可以通過設置參數來保證不降維,但是默認就是要降維的。
參數解釋:
1)input_tensor:輸入的張量。
2)axis:沿著哪個維度求和。
對于二維的input_tensor張量,0表示按列求和,1表示按行求和,[0, 1]表示先按列求和再按行求和。
3)keep_dims:默認值為Flase,表示默認要降維。若設為True,則不降維。
4)name:名字。
5)reduction_indices:默認值是None,即把input_tensor降到 0維,也就是一個數。
對于2維input_tensor,reduction_indices=0時,按列;reduction_indices=1時,按行。
注意,reduction_indices與axis不能同時設置。
?
?
?
參考資料:
鏈接:
https://www.jianshu.com/p/e4ff91317f7e
https://blog.csdn.net/UESTC_C2_403/article/details/72235565
https://www.jianshu.com/p/2d7db8b9cec9
?
總結
以上是生活随笔為你收集整理的python、numpy,keras,tensorflow等函数用法积累(持续更新)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dropout+Batch Normal
- 下一篇: Batch Normalization深