1. 程式人生 > >TensorFlow - 相關 API

TensorFlow - 相關 API

再計算 通道數 erro ali ural 現在 thead post false

來自:https://cloud.tencent.com/developer/labs/lab/10324

TensorFlow - 相關 API

TensorFlow 相關函數理解

任務時間:時間未知

tf.nn.conv2d

conv2d(
    input,
    filter,
    strides,
    padding,
    use_cudnn_on_gpu=True,
    data_format=‘NHWC‘,
    name=None
)

功能說明:

卷積的原理可參考 A guide to convolution arithmetic for deep learning

參數列表:

參數名必選類型說明
input tensor 是一個 4 維的 tensor,即 [ batch, in_height, in_width, in_channels ](若 input 是圖像,[ 訓練時一個 batch 的圖片數量, 圖片高度, 圖片寬度, 圖像通道數 ])
filter tensor 是一個 4 維的 tensor,即 [ filter_height, filter_width, in_channels, out_channels ](若 input 是圖像,[ 卷積核的高度,卷積核的寬度,圖像通道數,卷積核個數 ]),filter 的 in_channels 必須和 input 的 in_channels 相等
strides 列表 長度為 4 的 list,卷積時候在 input 上每一維的步長,一般 strides[0] = strides[3] = 1
padding string 只能為 " VALID "," SAME " 中之一,這個值決定了不同的卷積方式。VALID 丟棄方式;SAME:補全方式
use_cudnn_on_gpu bool 是否使用 cudnn 加速,默認為 true
data_format string 只能是 " NHWC ", " NCHW ",默認 " NHWC "
name string 運算名稱

技術分享圖片

示例代碼:

現在您可以在 /home/ubuntu

目錄下創建源文件 conv2d.py,內容可參考:

示例代碼:/home/ubuntu/conv2d.py
import tensorflow as tf

a = tf.constant([1,1,1,0,0,0,1,1,1,0,0,0,1,1,1,0,0,1,1,0,0,1,1,0,0],dtype=tf.float32,shape=[1,5,5,1])
b = tf.constant([1,0,1,0,1,0,1,0,1],dtype=tf.float32,shape=[3,3,1,1])
c = tf.nn.conv2d(a,b,strides=[1, 2, 2, 1],padding=‘VALID‘)
d = tf.nn.conv2d(a,b,strides=[1, 2, 2, 1],padding=‘SAME‘)
with tf.Session() as sess:
    print ("c shape:")
    print (c.shape)
    print ("c value:")
    print (sess.run(c))
    print ("d shape:")
    print (d.shape)
    print ("d value:")
    print (sess.run(d))

然後執行:

cd /home/ubuntu;
python conv2d.py

執行結果:

c shape:
(1, 3, 3, 1)
c value:
[[[[ 4.]
   [ 3.]
   [ 4.]]

  [[ 2.]
   [ 4.]
   [ 3.]]

  [[ 2.]
   [ 3.]
   [ 4.]]]]
d shape:
(1, 5, 5, 1)
d value:
[[[[ 2.]
   [ 2.]
   [ 3.]
   [ 1.]
   [ 1.]]

  [[ 1.]
   [ 4.]
   [ 3.]
   [ 4.]
   [ 1.]]

  [[ 1.]
   [ 2.]
   [ 4.]
   [ 3.]
   [ 3.]]

  [[ 1.]
   [ 2.]
   [ 3.]
   [ 4.]
   [ 1.]]

  [[ 0.]
   [ 2.]
   [ 2.]
   [ 1.]
   [ 1.]]]]

tf.nn.relu

relu(
    features,
    name=None
)

功能說明:

relu激活函數可以參考 CS231n: Convolutional Neural Networks for Visual Recognition

參數列表:

參數名必選類型說明
features tensor 是以下類型float32, float64, int32, int64, uint8, int16, int8, uint16, half
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 relu.py,內容可參考:

示例代碼:/home/ubuntu/relu.py
import tensorflow as tf

a = tf.constant([1,-2,0,4,-5,6])
b = tf.nn.relu(a)
with tf.Session() as sess:
    print (sess.run(b))

然後執行:

cd /home/ubuntu;
python relu.py

執行結果:

[1 0 0 4 0 6]

tf.nn.max_pool

max_pool(
    value,
    ksize,
    strides,
    padding,
    data_format=‘NHWC‘,
    name=None
)

功能說明:

池化的原理可參考 CS231n: Convolutional Neural Networks for Visual Recognition

參數列表:

參數名必選類型說明
value tensor 4 維的張量,即 [ batch, height, width, channels ],數據類型為 tf.float32
ksize 列表 池化窗口的大小,長度為 4 的 list,一般是 [1, height, width, 1],因為不在 batch 和 channels 上做池化,所以第一個和最後一個維度為 1
strides 列表 池化窗口在每一個維度上的步長,一般 strides[0] = strides[3] = 1
padding string 只能為 " VALID "," SAME " 中之一,這個值決定了不同的池化方式。VALID 丟棄方式;SAME:補全方式
data_format string 只能是 " NHWC ", " NCHW ",默認" NHWC "
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 max_pool.py,內容可參考:

示例代碼:/home/ubuntu/max_pool.py
import tensorflow as tf

a = tf.constant([1,3,2,1,2,9,1,1,1,3,2,3,5,6,1,2],dtype=tf.float32,shape=[1,4,4,1])
b = tf.nn.max_pool(a,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding=‘VALID‘)
c = tf.nn.max_pool(a,ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1],padding=‘SAME‘)
with tf.Session() as sess:
    print ("b shape:")
    print (b.shape)
    print ("b value:")
    print (sess.run(b))
    print ("c shape:")
    print (c.shape)
    print ("c value:")
    print (sess.run(c))

然後執行:

cd /home/ubuntu;
python max_pool.py

執行結果:

b shape:
(1, 2, 2, 1)
b value:
[[[[ 9.]
   [ 2.]]

  [[ 6.]
   [ 3.]]]]
c shape:
(1, 2, 2, 1)
c value:
[[[[ 9.]
   [ 2.]]

  [[ 6.]
   [ 3.]]]]

tf.nn.dropout

dropout(
    x,
    keep_prob,
    noise_shape=None,
    seed=None,
    name=None
)

功能說明:

原理可參考 CS231n: Convolutional Neural Networks for Visual Recognition

參數列表:

參數名必選類型說明
x tensor 輸出元素是 x 中的元素以 keep_prob 概率除以 keep_prob,否則為 0
keep_prob scalar Tensor dropout 的概率,一般是占位符
noise_shape tensor 默認情況下,每個元素是否 dropout 是相互獨立。如果指定 noise_shape,若 noise_shape[i] == shape(x)[i],該維度的元素是否 dropout 是相互獨立,若 noise_shape[i] != shape(x)[i] 該維度元素是否 dropout 不相互獨立,要麽一起 dropout 要麽一起保留
seed 數值 如果指定該值,每次 dropout 結果相同
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 dropout.py,內容可參考:

示例代碼:/home/ubuntu/dropout.py
import tensorflow as tf

a = tf.constant([1,2,3,4,5,6],shape=[2,3],dtype=tf.float32)
b = tf.placeholder(tf.float32)
c = tf.nn.dropout(a,b,[2,1],1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print (sess.run(c,feed_dict={b:0.75}))

然後執行:

cd /home/ubuntu;
python dropout.py

執行結果:

[[ 0.          0.          0.        ]
 [ 5.33333349  6.66666651  8.        ]]

tf.nn.sigmoid_cross_entropy_with_logits

sigmoid_cross_entropy_with_logits(
    _sentinel=None,
    labels=None,
    logits=None,
    name=None
)

功能說明:

先對 logits 通過 sigmoid 計算,再計算交叉熵,交叉熵代價函數可以參考 CS231n: Convolutional Neural Networks for Visual Recognition

參數列表:

參數名必選類型說明
_sentinel None 沒有使用的參數
labels Tensor type, shape 與 logits相同
logits Tensor type 是 float32 或者 float64
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 sigmoid_cross_entropy_with_logits.py

示例代碼:/home/ubuntu/sigmoid_cross_entropy_with_logits.py
import tensorflow as tf
x = tf.constant([1,2,3,4,5,6,7],dtype=tf.float64)
y = tf.constant([1,1,1,0,0,1,0],dtype=tf.float64)
loss = tf.nn.sigmoid_cross_entropy_with_logits(labels = y,logits = x)
with tf.Session() as sess:
    print (sess.run(loss))

然後執行:

cd /home/ubuntu;
python sigmoid_cross_entropy_with_logits.py

執行結果:

[  3.13261688e-01   1.26928011e-01   4.85873516e-02   4.01814993e+00
   5.00671535e+00   2.47568514e-03   7.00091147e+00]

tf.truncated_normal

truncated_normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.float32,
    seed=None,
    name=None
)

功能說明:

產生截斷正態分布隨機數,取值範圍為 [ mean - 2 * stddev, mean + 2 * stddev ]

參數列表:

參數名必選類型說明
shape 1 維整形張量或 array 輸出張量的維度
mean 0 維張量或數值 均值
stddev 0 維張量或數值 標準差
dtype dtype 輸出類型
seed 數值 隨機種子,若 seed 賦值,每次產生相同隨機數
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 truncated_normal.py

示例代碼:/home/ubuntu/truncated_normal.py
import tensorflow as tf
initial = tf.truncated_normal(shape=[3,3], mean=0, stddev=1)
print(tf.Session().run(initial))

然後執行:

python /home/ubuntu/truncated_normal.py

執行結果:

將得到一個取值範圍 [ -2, 2 ] 的 3 * 3 矩陣,您也可以嘗試修改源代碼看看輸出結果有什麽變化?

tf.constant

constant(
    value,
    dtype=None,
    shape=None,
    name=‘Const‘,
    verify_shape=False
)

功能說明:

根據 value 的值生成一個 shape 維度的常量張量

參數列表:

參數名必選類型說明
value 常量數值或者 list 輸出張量的值
dtype dtype 輸出張量元素類型
shape 1 維整形張量或 array 輸出張量的維度
name string 張量名稱
verify_shape Boolean 檢測 shape 是否和 value 的 shape 一致,若為 Fasle,不一致時,會用最後一個元素將 shape 補全

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 constant.py,內容可參考:

示例代碼:/home/ubuntu/constant.py
#!/usr/bin/python

import tensorflow as tf
import numpy as np
a = tf.constant([1,2,3,4,5,6],shape=[2,3])
b = tf.constant(-1,shape=[3,2])
c = tf.matmul(a,b)

e = tf.constant(np.arange(1,13,dtype=np.int32),shape=[2,2,3])
f = tf.constant(np.arange(13,25,dtype=np.int32),shape=[2,3,2])
g = tf.matmul(e,f)
with tf.Session() as sess:
    print (sess.run(a))
    print ("##################################")
    print (sess.run(b))
    print ("##################################")
    print (sess.run(c))
    print ("##################################")
    print (sess.run(e))
    print ("##################################")
    print (sess.run(f))
    print ("##################################")
    print (sess.run(g))

然後執行:

python /home/ubuntu/constant.py

執行結果:

a: 2x3 維張量;
b: 3x2 維張量;
c: 2x2 維張量;
e: 2x2x3 維張量;
f: 2x3x2 維張量;
g: 2x2x2 維張量。

tf.placeholder

placeholder(
    dtype,
    shape=None,
    name=None
)

功能說明:

是一種占位符,在執行時候需要為其提供數據

參數列表:

參數名必選類型說明
dtype dtype 占位符數據類型
shape 1 維整形張量或 array 占位符維度
name string 占位符名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 placeholder.py,內容可參考:

示例代碼:/home/ubuntu/placeholder.py
#!/usr/bin/python

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32,[None,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}))

然後執行:

python /home/ubuntu/placeholder.py

執行結果:

輸出一個 3x3 的張量

tf.nn.bias_add

bias_add(
    value,
    bias,
    data_format=None,
    name=None
)

功能說明:

將偏差項 bias 加到 value 上面,可以看做是 tf.add 的一個特例,其中 bias 必須是一維的,並且維度和 value 的最後一維相同,數據類型必須和 value 相同。

參數列表:

參數名必選類型說明
value 張量 數據類型為 float, double, int64, int32, uint8, int16, int8, complex64, or complex128
bias 1 維張量 維度必須和 value 最後一維維度相等
data_format string 數據格式,支持 ‘ NHWC ‘ 和 ‘ NCHW ‘
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 bias_add.py,內容可參考:

示例代碼:/home/ubuntu/bias_add.py
#!/usr/bin/python

import tensorflow as tf
import numpy as np

a = tf.constant([[1.0, 2.0],[1.0, 2.0],[1.0, 2.0]])
b = tf.constant([2.0,1.0])
c = tf.constant([1.0])
sess = tf.Session()
print (sess.run(tf.nn.bias_add(a, b)))
#print (sess.run(tf.nn.bias_add(a,c))) error
print ("##################################")
print (sess.run(tf.add(a, b)))
print ("##################################")
print (sess.run(tf.add(a, c)))

然後執行:

python /home/ubuntu/bias_add.py

執行結果:

3 個 3x2 維張量。您也可以嘗試修改源代碼看看輸出結果有什麽變化?

tf.reduce_mean

reduce_mean(
    input_tensor,
    axis=None,
    keep_dims=False,
    name=None,
    reduction_indices=None
)

功能說明:

計算張量 input_tensor 平均值

參數列表:

參數名必選類型說明
input_tensor 張量 輸入待求平均值的張量
axis None、0、1 None:全局求平均值;0:求每一列平均值;1:求每一行平均值
keep_dims Boolean 保留原來的維度(例如不會從二維矩陣降為一維向量)
name string 運算名稱
reduction_indices None 和 axis 等價,被棄用

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 reduce_mean.py,內容可參考:

示例代碼:/home/ubuntu/reduce_mean.py
#!/usr/bin/python

import tensorflow as tf
import numpy as np

initial = [[1.,1.],[2.,2.]]
x = tf.Variable(initial,dtype=tf.float32)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(tf.reduce_mean(x)))
    print(sess.run(tf.reduce_mean(x,0))) #Column
    print(sess.run(tf.reduce_mean(x,1))) #row

然後執行:

python /home/ubuntu/reduce_mean.py

執行結果:

1.5
[ 1.5  1.5]
[ 1.  2.]

tf.squared_difference

squared_difference(
    x,
    y,
    name=None
)

功能說明:

計算張量 x、y 對應元素差平方

參數列表:

參數名必選類型說明
x 張量 是 half, float32, float64, int32, int64, complex64, complex128 其中一種類型
y 張量 是 half, float32, float64, int32, int64, complex64, complex128 其中一種類型
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 squared_difference.py,內容可參考:

示例代碼:/home/ubuntu/squared_difference.py
#!/usr/bin/python

import tensorflow as tf
import numpy as np

initial_x = [[1.,1.],[2.,2.]]
x = tf.Variable(initial_x,dtype=tf.float32)
initial_y = [[3.,3.],[4.,4.]]
y = tf.Variable(initial_y,dtype=tf.float32)
diff = tf.squared_difference(x,y)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(diff))

然後執行:

python /home/ubuntu/squared_difference.py

執行結果:

[[ 4.  4.]
 [ 4.  4.]]

tf.square

square(
    x,
    name=None
)

功能說明:

計算張量對應元素平方

參數列表:

參數名必選類型說明
x 張量 是 half, float32, float64, int32, int64, complex64, complex128 其中一種類型
name string 運算名稱

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 square.py,內容可參考:

示例代碼:/home/ubuntu/square.py
#!/usr/bin/python
import tensorflow as tf
import numpy as np

initial_x = [[1.,1.],[2.,2.]]
x = tf.Variable(initial_x,dtype=tf.float32)
x2 = tf.square(x)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(x2))

然後執行:

python /home/ubuntu/square.py

執行結果:

[[ 1.  1.]
 [ 4.  4.]]

TensorFlow 相關類理解

任務時間:時間未知

tf.Variable

__init__(
    initial_value=None,
    trainable=True,
    collections=None,
    validate_shape=True,
    caching_device=None,
    name=None,
    variable_def=None,
    dtype=None,
    expected_shape=None,
    import_scope=None
)

功能說明:

維護圖在執行過程中的狀態信息,例如神經網絡權重值的變化。

參數列表:

參數名類型說明
initial_value 張量 Variable 類的初始值,這個變量必須指定 shape 信息,否則後面 validate_shape 需設為 False
trainable Boolean 是否把變量添加到 collection GraphKeys.TRAINABLE_VARIABLES 中(collection 是一種全局存儲,不受變量名生存空間影響,一處保存,到處可取)
collections Graph collections 全局存儲,默認是 GraphKeys.GLOBAL_VARIABLES
validate_shape Boolean 是否允許被未知維度的 initial_value 初始化
caching_device string 指明哪個 device 用來緩存變量
name string 變量名
dtype dtype 如果被設置,初始化的值就會按照這個類型初始化
expected_shape TensorShape 要是設置了,那麽初始的值會是這種維度

示例代碼:

現在您可以在 /home/ubuntu 目錄下創建源文件 Variable.py,內容可參考:

示例代碼:/home/ubuntu/Variable.py
#!/usr/bin/python

import tensorflow as tf
initial = tf.truncated_normal(shape=[10,10],mean=0,stddev=1)
W=tf.Variable(initial)
list = [[1.,1.],[2.,2.]]
X = tf.Variable(list,dtype=tf.float32)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print ("##################(1)################")
    print (sess.run(W))
    print ("##################(2)################")
    print (sess.run(W[:2,:2]))
    op = W[:2,:2].assign(22.*tf.ones((2,2)))
    print ("###################(3)###############")
    print (sess.run(op))
    print ("###################(4)###############")
    print (W.eval(sess)) #computes and returns the value of this variable
    print ("####################(5)##############")
    print (W.eval())  #Usage with the default session
    print ("#####################(6)#############")
    print (W.dtype)
    print (sess.run(W.initial_value))
    print (sess.run(W.op))
    print (W.shape)
    print ("###################(7)###############")
    print (sess.run(X))

然後執行:

python /home/ubuntu/Variable.py

完成實驗

任務時間:時間未知

實驗內容已完成

您可進行更多關於機器學習教程:

  • 實驗列表 - 機器學習

關於 TensorFlow 的更多資料可參考 TensorFlow 官網

TensorFlow - 相關 API