2019-06-28
import tensorflow as tf 后,tf.什么什么。
都是tensorflow中需要理解的概念,不涉及神經(jīng)網(wǎng)絡(luò)相關(guān)概念的理解。
tf.Variable()
(對(duì)于《TensorFlow實(shí)戰(zhàn)(黃文堅(jiān))》P6,自己的理解)
- 這個(gè)一定是最常見的一個(gè)了,不就是“變量”嘛,可是它跟我們平常理解的變量有啥子區(qū)別?首先,tensorflow里流動(dòng)的是tensors,而正因?yàn)閠ensors是流動(dòng)著的,所以我們是抓不到它的。而variable卻是一種你抓或不抓它都在那的tensor,每次建一個(gè)variable,在計(jì)算圖中就多了一個(gè)節(jié)點(diǎn)。那為啥需要它不隨tensors逐流呢?因?yàn)殡S著每次迭代,不可能保留所有數(shù)據(jù),比如上一層算出來的feature maps,在下一層用完后就得扔掉;但是像是weights和biases這些參數(shù),只有保留下來,才能做梯度下降等,達(dá)到優(yōu)化參數(shù)的目的。
tf.Session()
(這邊主要參考《TensorFlow實(shí)戰(zhàn)(黃文堅(jiān))》P6)
- session是tensorflow中非?;镜母拍?,是用戶使用tensorflow時(shí)的交互式接口。用戶通過Session的extend方法添加新的節(jié)點(diǎn)和邊,如此創(chuàng)建計(jì)算圖,然后通過Session的run方法執(zhí)行計(jì)算圖。
tf.add_to_collection()
參考:tf.add_to_collection
TensorFlow學(xué)習(xí)--tf.add_to_collection與tf.get_collection使用
-
tf.add_to_collection('collection_name', tensor):
將tensor添加到列表collection_name中 -
tf.get_collection('collection_name'):
返回名稱為collection_name的列表的tensors -
tf.add_n(tf.get_collection('collection_name')):
返回名稱為collection_name的列表的tensors的加和
import tensorflow as tf
tf.add_to_collection('losses', tf.constant(2.2))
tf.add_to_collection('losses', tf.constant(3.))
with tf.Session() as sess:
print(sess.run(tf.get_collection('losses')))
print(sess.run(tf.add_n(tf.get_collection('losses'))
結(jié)果:
[2.2, 3.0]
5.2
注意:
使用tf.add_n對(duì)列表元素進(jìn)行相加時(shí),列表內(nèi)元素類型必須一致,否則會(huì)報(bào)錯(cuò)。
tf.add()、tf.nn.bias_add()、tf.add_n()
參考:Tensorflow——tf.nn.bias_add和tf.add、tf.add_n
-
tf.add(x, y):
x和y都必須是tensor,且類型必須一致。 -
tf.nn.bias_add(Wx, b):
是tf.add()的特例,其中b必須是一維的,個(gè)數(shù)與Wx的最后一維相同。
比如Wx的shape是[28, 28, 64],那么b是[64],符合神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)。 -
tf.add_n(a_list):
輸入是一個(gè)列表,實(shí)現(xiàn)列表中所有元素的相加,列表元素可以是tensor、矩陣等。
tf.reduce_mean()、tf.reduce_sum()、tf.reduce_max()
-
這幾位大兄弟都是一個(gè)概念,最終效果是降維了,所以叫reduce。
直接上這個(gè)看了忘忘了看的圖:要記住的是0是縱向、1是橫向。
with tf.name_scope('conv1') as scope:
- 將scope內(nèi)生成的Variable自動(dòng)命名為conv1/xxx,便于區(qū)分不同卷積層之間的組件
常用數(shù)據(jù)類型
tf.float32()tf.int32()
常用參數(shù)
shape=stddev=wl=padding=name=
常用函數(shù)
- 數(shù)據(jù):
tf.Variable()tf.Variable(tf.constant())-
tf.Variable(tf.truncated_normal()):截?cái)嗾龖B(tài)分布 tf.Variable(tf.random_nromal())tf.Variable(tf.ones())-
tf.reshape()tf.reshape().get_shape()
- 結(jié)構(gòu)構(gòu)建:
tf.add()tf.matmul()-
tf.nn.bias_add():專用于Wx+b tf.nn.conv2d()tf.nn.max_pool()tf.nn.relu()-
tf.nn.lrn():LRN -
tf.nn.dropout():去掉一定比率的神經(jīng)元
- 損失函數(shù):
-
tf.nn.l2_loss():L2范數(shù)損失 -
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(y_conv, y_GT):交叉熵?fù)p失 -
tf.reduce_mean(cross_entropy):沿某個(gè)軸的平均值,0縱1橫,最終效果是reduce降維了
- 優(yōu)化器:
-
tf.gradients(target, parameters):梯度下降 -
tf.train.AdamOptimizer(learning_rate).minimize(loss):Adam優(yōu)化
- 準(zhǔn)確率:
-
tf.nn.in_top_k():值最高的k類的值
- 運(yùn)行:
-
sess = tf.Session():定義一個(gè)session -
tf.global_variables_initailizer().run():初始化所有變量 -
sess.run():使tensors流動(dòng)起來
