参考 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:操作的名称(可选)。
返回值:
- 一个所有元素都为零的张量。