tf.ones_like和tf.zeros_like()

参考  tf.less_equal或tf.math.less_equal - 云+社区 - 腾讯云

一、tf.ones_like 

tf.ones_like(
    tensor,
    dtype=None,
    name=None,
    optimize=True
)

创建一个所有元素都设为1的张量。给定一个张量(张量),这个操作返回一个与所有元素都设为1的张量类型和形状相同的张量。还可以为返回的张量指定一个新类型(dtype)。

例:

tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.ones_like(tensor)  # [[1, 1, 1], [1, 1, 1]]

参数:

  • tensor:  一个张量。
  • dtype:  返回张量的类型。必须是float32、float64、int8、uint8、int16、uint16、int32、int64、complex64、complex128orbool '。
  • name:  操作的名称(可选)。
  • optimize:  如果为真,尝试静态确定“张量”的形状,并将其编码为常量。

返回值:

  • 一个所有元素都为1的张量。

例:

import tensorflow as tf
import numpy as np

# 生成一个tensor,内部数据随机产生
a = tf.convert_to_tensor(np.random.random([2, 4, 5]), dtype=tf.float32)

# ones_like
b = tf.ones_like(a, dtype=tf.float32, name='ones_like')

# zeros_like
c = tf.zeros_like(a, dtype=tf.float32, name='zeros_like')

print(b)

print(c)

with tf.Session() as sess:
    b_, c_ = sess.run([b, c])
    print("b's shape: ", b_.shape)
    print("c's shape: ", c_.shape)
    print(b_)
    print(c_)


Output:
--------------------------------------------------------
Tensor("ones_like:0", shape=(2, 4, 5), dtype=float32)
Tensor("zeros_like:0", shape=(2, 4, 5), dtype=float32)
b's shape:  (2, 4, 5)
c's shape:  (2, 4, 5)
[[[1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]
  [1. 1. 1. 1. 1.]]

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

 [[0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]
  [0. 0. 0. 0. 0.]]]
--------------------------------------------------------

二、tf.zeros_like()

创建一个所有元素都为零的张量。

tf.zeros_like(
    input,
    dtype=None,
    name=None
)

给定一个张量(张量),这个操作返回一个与所有元素为零的张量类型和形状相同的张量。还可以选择使用dtype为返回的张量指定一个新类型。

例:

tensor = tf.constant([[1, 2, 3], [4, 5, 6]])
tf.zeros_like(tensor)  # [[0, 0, 0], [0, 0, 0]] with dtype=int32

If dtype of input `tensor` is `float32`, then the output is also of `float32`
tensor = tf.constant([[1.0, 2.0, 3.0], [4, 5, 6]])
tf.zeros_like(tensor)  # [[0., 0., 0.], [0., 0., 0.]] with dtype=floa32

If you want to specify desired dtype of output `tensor`, then specify it in
the op tensor = tf.constant([[1.0, 2.0, 3.0], [4, 5, 6]])
tf.zeros_like(tensor,dtype=tf.int32)  # [[0, 0, 0], [0, 0, 0]] with
dtype=int32

参数:

  • input:一个张量。
  • dtype:返回张量的类型。必须是float16、float32、float64、int8、uint8、int16、uint16、int32、int64、complex64、complex128、bool或字符串。
  • name:操作的名称(可选)。

返回值:

  • 一个所有元素都为零的张量。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wanderer001

ROIAlign原理

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值