tensorflow函数学习

标签(空格分隔): tensorflow 深度学习


一、一些函数

1 tf.nn.softmax

help(tf.nn.softmax)
logits = np.array([[1, 2, 7],
                   [3, 5, 2],
                   [6, 1, 3],
                   [8, 2, 0],
                   [3, 6, 1]], dtype=np.float32)
sess=tf.Session()
sess.run(tf.nn.softmax(logits=logits, dim=-1))

# -----输出:
softmax(logits, dim=-1, name=None)   Computes softmax activations.
    
    For each batch `i` and class `j` we have
    
        softmax = exp(logits) / reduce_sum(exp(logits), dim)
    
    Args:
      logits: A non-empty `Tensor`. Must be one of the following types: `half`,
        `float32`, `float64`.
      dim: The dimension softmax would be performed on. The default is -1 which
        indicates the last dimension.
      name: A name for the operation (optional).
    
    Returns:
      A `Tensor`. Has the same type as `logits`. Same shape as `logits`.
    Raises:
      InvalidArgumentError: if `logits` is empty or `dim` is beyond the last
        dimension of `logits`.
        
array([[  2.45611509e-03,   6.67641265e-03,   9.90867496e-01],
       [  1.14195190e-01,   8.43794703e-01,   4.20100652e-02],
       [  9.46499169e-01,   6.37746137e-03,   4.71234173e-02],
       [  9.97193694e-01,   2.47179624e-03,   3.34521203e-04],
       [  4.71234173e-02,   9.46499169e-01,   6.37746137e-03]], dtype=float32)

输入一个张量,默认对张量的最后一维进行softmax计算,以二维矩阵为例,针对第一行
math.exp(1)/(math.exp(1)+math.exp(2)+math.exp(7)) = 2.456e-03
math.exp(2)/(math.exp(1)+math.exp(2)+math.exp(7)) = 6.676e-03
math.exp(7)/(math.exp(1)+math.exp(2)+math.exp(7)) = 9.908e-01
可以看到,softmax返回一个概率向量,且和为1,类似于概率归一化。
softmax能够放大占比重较大的项

2 tf.nn.sigmoid

help(tf.nn.sigmoid)
logits = np.array([[1, 2, 7],
                   [3, 5, 2],
                   [6, 1, 3],
                   [8, 2, 0],
                   [3, 6, 1]], dtype=np.float32)
sess=tf.Session()
sess.run(tf.nn.sigmoid(logits))

# -----输出:
sigmoid(x, name=None)
    Computes sigmoid of `x` element-wise.
    
    Specifically, `y = 1 / (1 + exp(-x))`.
    
    Args:
      x: A Tensor with type `float32`, `float64`, `int32`, `complex64`, `int64`,
        or `qint32`.
      name: A name for the operation (optional).
    
    Returns:
      A Tensor with the same type as `x` if `x.dtype != qint32`
        otherwise the return type is `quint8`.
    
    @compatibility(numpy)
    Equivalent to np.scipy.special.expit
    @end_compatibility

array([[ 0.7310586 ,  0.88079703,  0.999089  ],
       [ 0.95257413,  0.99330717,  0.88079703],
       [ 0.99752742,  0.7310586 ,  0.95257413],
       [ 0.99966466,  0.88079703,  0.5       ],
       [ 0.95257413,  0.99752742,  0.7310586 ]], dtype=float32)

针对第一行,计算公式如下:
1/(1+math.exp(-1))=0.73
1/(1+math.exp(-2))=0.88
1/(1+math.exp(-7))=0.99

3 tf.clip_by_value(A, min,max)

输入一个张量A,把A中的每一个元素的值都压缩在min和max之间。小于min的让它等于min,大于max的元素的值等于max。常和对数函数一起使用,因为log(0)是nan,最好映射到非常小的值

import tensorflow as tf;  
import numpy as np;  
  
A = np.array([[1,1,2,4], [3,4,8,5]])  
  
with tf.Session() as sess:  
    print sess.run(tf.clip_by_value(A, 2, 5)) 

#---输出
[[2 2 2 4]
 [3 4 5 5]]

4 tf.one_hot(indices, depth, on_value=1, off_value=0)
将[2,1,0,0,1]转为其ont-hot编码矩阵

labels = np.array([[0, 0, 1],
                   [0, 1, 0],
                   [1, 0, 0],
                   [1, 0, 0],
                   [0, 1, 0]], dtype=np.float32)
classes = tf.argmax(labels, axis=1)                  #[2 1 0 0 1]
classes_one_hot=tf.one_hot(classes,3)           #与labels相同
print sess.run(classes)
print sess.run(classes_one_hot)

5 tf.reshape(data, shape)
更改数据的形状

initial = tf.truncated_normal([2,4], stddev=0.1)
reshaped=tf.reshape(initial,[-1,2])     #-1表示该维度由其他维度算出来的,这里可以推出是4
sess.run(initial)
sess.run(reshaped)
#---输出
array([[ 0.04542142,  0.05807167,  0.04512282, -0.00823399],
       [-0.04336055,  0.06470031,  0.17169526, -0.02920728]], dtype=float32)

array([[-0.13132362, -0.0573084 ],
       [ 0.14249204, -0.0505862 ],
       [ 0.01468951,  0.0189805 ],
       [-0.05596937, -0.04880321]], dtype=float32)

6 tf.stack()和tf.unstack()
tf.stack()这是一个矩阵拼接的函数,tf.unstack()则是一个矩阵分解的函数

a=tf.constant([1,2,3])
b=tf.constant([4,5,6])
c=tf.stack([a,b])
array([[1, 2, 3],
       [4, 5, 6]], dtype=int32)

d=tf.unstack(c,axis=0)
[array([1, 2, 3], dtype=int32), array([4, 5, 6], dtype=int32)]
e=tf.unstack(c,axis=1)       
[array([1, 4], dtype=int32), array([2, 5], dtype=int32), array([3, 6], dtype=int32)]

7 tf.truncated_normal与tf.random_normal
在tf.truncated_normal中如果x的取值在区间(μ-2σ,μ+2σ)之外则重新进行选择。这样保证了生成的值都在均值附近。

  1. add_to_collection、get_collection、add_n
    tf.add_to_collection:把变量放入一个集合,把很多变量变成一个列表
    tf.get_collection:从一个集合中取出全部变量,是一个列表
    tf.add_n:把一个列表的东西都依次加起来
with tf.name_scope("name1") as scope:
    a=tf.constant([11, 12],name="a")
    b = tf.constant([11, 13], name="b")
    tf.add_to_collection('losses', a)               #类似一个键值对,key='losses', value=[a]
    tf.add_to_collection('losses', b)               #key='losses',value=[a,b]

    xxx = tf.get_collection("losses",scope)          #[a, b]
    yyy = tf.get_collection("losses","name")         #[a, b]
    zzz = tf.get_collection("losses","name2")        #[]
    get_collection有两个参数,第一个是key,第二个scope(可选),使用正则匹配
  1. tf.group()
    创建一个操作,该操作可以对 TensorFlow 的多个操作进行组合执行,但没有输出。
a=tf.Variable(3)
add=tf.assign(a,a+1)               #a+1的op
add_2=tf.assign(a,a+2)             #a+2的op
sess.run(tf.group(add,add_2))      #执行a+1,a+2两个op,注意此时无返回
sess.run(a)                        #返回6,说明op都执行了
  1. tf.gather(data, indices)
    将data中由indices指定的元素取出
a                                   #二维示例                       
# array([[1, 2],          
        [3, 4],
        [5, 6]])
sess.run(tf.gather(a,[0,2]))     
# array([[1, 2],
        [5, 6]])

a                                   #一维示例
# array([1, 2, 4, 3])
sess.run(tf.gather(a,[0,2]))
# array([1, 4])
  1. tf.transpose()
>>> a                         #2×3
array([[1, 2],
       [3, 4],
       [5, 6]])
>>> sess.run(tf.transpose(a,[1,0]))     #第一阶和第0阶交换,3×2
array([[1, 3, 5],
       [2, 4, 6]])
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容