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

一、简介
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()的参数信息相同。如下:

参数
tensorA Tensor一个tensor数据,也可以是一个numpy数组,该参数指定了返回tensor的shape和dtype。
dtypeA 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
nameA name for the operation (optional)一个可选参数,表明返回的tensor的名称。
optimizeif 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()函数,效果是一样的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值