Tensorflow深度学习之二十九:tf.ones_like()和tf.zeros_like()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/DaVinciL/article/details/82532976

一、简介
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.

For example:

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

翻译:
创建一个tensor,左右的元素都设置为1。
给定一个tensor(tensor 参数),该操作返回一个具有和给定tensor相同形状(shape)和相同数据类型(dtype),但是所有的元素都被设置为1的tensor。也可以为返回的tensor指定一个新的数据类型。

以上是tf.ones_like()函数的介绍,类似地也可以得到tf.zeros_like()函数的信息,只不过填充的数据是0,而不是1,这里就不做过多的叙述。

二、参数信息
tf.ones_like()和tf.zeros_like()的参数信息相同。如下:

参数
tensor A Tensor 一个tensor数据,也可以是一个numpy数组,该参数指定了返回tensor的shape和dtype。
dtype A type for the returned Tensor. Must be float32, float64, int8, uint8, int16, uint16, int32, int64, complex64, complex128 or bool. 一个可选参数,表明返回tensor的数据类型,必须为以下的几种之一:float32, float64, int8, uint8, int16, uint16, int32, int64, complex64, complex128 or bool
name A name for the operation (optional) 一个可选参数,表明返回的tensor的名称。
optimize if true, attempt to statically determine the shape of ‘tensor’ and encode it as a constant. 若果该参数设置为True,尝试去静态地决定tensor 的形状(shape)并将其编码为一个常量。默认为True。

三、代码

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_)

运行结果:

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.]]]

四:补充
   在numpy中,也有类似的np.ones_like()和np.zeros_like()函数,效果是一样的。

猜你喜欢

转载自blog.csdn.net/DaVinciL/article/details/82532976
今日推荐