TensorFlow中的tf.ones_like()和tf.zeros_like()函数详解
在基于tensorlayer的SRGAN代码中碰到了这两个函数,记录一下:
d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real, tf.ones_like(logits_real), name='d1')
d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake, tf.zeros_like(logits_fake), name='d2')
1.tf.ones_like()
a.官方注释
Creates a tensor with all elements set to 1.
Given a single tensor (tensor
), this operation returns a tensor of the same
type and shape as tensor
with all elements set to 1. Optionally, you can
specify a new type (dtype
) for the returned tensor.
翻译一下就是:
创建一个将所有元素设置为1的张量。
给定一个tensor(tensor
),该操作返回一个具有和给定tensor相同形状(shape
)和相同数据类型(dtype
),但是所有的元素都被设置为1的tensor。也可以为返回的tensor指定一个新的数据类型。
b.参数解释
def ones_like(tensor, dtype=None, name=None, optimize=True):
...
return ret
- tensor:张量.
- dtype:返回的 Tensor 类型.必须是:float32,float64,int8,int16,int32,int64,uint8,complex64,complex128或bool.
- name:操作的名称(可选).
- optimize:如果为 true,则尝试静态确定 “张量” 的形状并将其编码为常量.
- return:返回一个所有元素设置为1的tensor
c.例子
tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.ones_like(tensor) # [[1, 1, 1], [1, 1, 1]]
2.tf.zeros_like()
a.官方注释
Creates a tensor with all elements set to zero.
Given a single tensor (tensor
), this operation returns a tensor of the
same type and shape as tensor
with all elements set to zero. Optionally,
you can use dtype
to specify a new type for the returned tensor.
翻译一下就是:
创建一个将所有元素设置为0的张量。
给定一个tensor(tensor
),该操作返回一个具有和给定tensor相同形状(shape
)和相同数据类型(dtype
),但是所有的元素都被设置为0的tensor。也可以为返回的tensor指定一个新的数据类型。
b.参数解释
def zeros_like(tensor, dtype=None, name=None, optimize=True):
...
return gen_array_ops._zeros_like(tensor, name=name)
- tensor:张量.
- dtype:返回的张量的类型,必须是以下类型之一:float16,float32,float64,int8,uint8,int16,uint16,int32,int64,complex64,complex128,bool或string.
- name:操作的名称(可选).
- optimize:如果为 true,则尝试静态确定 “张量” 的形状并将其编码为常量.
- return:返回一个所有元素设置为零的tensor
c.例子
tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.zeros_like(tensor) # [[0, 0, 0], [0, 0, 0]]
参考
[1] Tensorflow深度学习之二十九:tf.ones_like()和tf.zeros_like()
[2] TensorFlow函数:tf.ones_like
[3] TensorFlow函数:tf.zeros_like
码字不易,如果您觉得有帮助,麻烦帮我点个赞~~