tensorflow之tf.nn.l2_normalize与l2_loss的计算

1.tf.nn.l2_normalize

 

tf.nn.l2_normalize(x, dim, epsilon=1e-12, name=None) 
上式: 
x为输入的向量; 
dim为l2范化的维数,dim取值为0或0或1; 
epsilon的范化的最小值边界;

 按照列计算:

import tensorflow as tf
input_data = tf.constant([[1.0,2,3],[4.0,5,6],[7.0,8,9]])

output = tf.nn.l2_normalize(input_data, dim = 0)
with tf.Session() as sess:
print sess.run(input_data)
print sess.run(output)
 

[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
[[0.12309149 0.20739034 0.26726127]
[0.49236596 0.51847583 0.53452253]
[0.86164045 0.82956135 0.80178374]]
 

 

[[1./norm(1), 2./norm(2) , 3./norm(3) ]
[4./norm(1) , 5./norm(2) , 6./norm(3) ]    =
[7./norm(1) , 8./norm(2) , 9./norm(3) ]]
[[0.12309149 0.20739034 0.26726127]
[0.49236596 0.51847583 0.53452253]
[0.86164045 0.82956135 0.80178374]]
 

按照行计算:

import tensorflow as tf
input_data = tf.constant([[1.0,2,3],[4.0,5,6],[7.0,8,9]])

output = tf.nn.l2_normalize(input_data, dim = 1)
with tf.Session() as sess:
print sess.run(input_data)
print sess.run(output)
 

 

[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
[[0.26726124 0.5345225 0.8017837 ]
[0.45584232 0.5698029 0.6837635 ]
[0.5025707 0.5743665 0.64616233]]

 

[[1./norm(1), 2./norm(1) , 3./norm(1) ]
[4./norm(2) , 5./norm(2) , 6./norm(2) ]    =
[7./norm(3) , 8..norm(3) , 9./norm(3) ]]
[[0.12309149 0.20739034 0.26726127]
[0.49236596 0.51847583 0.53452253]
[0.86164045 0.82956135 0.80178374]] 

2.tf.nn.l2_loss

tf.nn.l2_loss(t, name=None)

解释:这个函数的作用是利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半,具体如下:

output = sum(t ** 2) / 2

import tensorflow as tf

a=tf.constant([1,2,3],dtype=tf.float32)
b=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32)

with tf.Session() as sess:
    print('a:')
    print(sess.run(tf.nn.l2_loss(a)))
    print('b:')
    print(sess.run(tf.nn.l2_loss(b)))
    sess.close()
输出结果:
a:
7.0
b:
14.0

输入参数:

  • t: 一个Tensor。数据类型必须是一下之一:float32,float64,int64,int32,uint8,int16,int8,complex64,qint8,quint8,qint32。虽然一般情况下,数据维度是二维的。但是,数据维度可以取任意维度。
  • name: 为这个操作取个名字。

输出参数:

一个 Tensor ,数据类型和 t 相同,是一个标量。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值