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

本文详细介绍了TensorFlow中tf.ones_like和tf.zeros_like函数的使用方法,包括函数的功能、参数信息及代码示例。这两个函数分别用于创建所有元素均为1或0的张量,与给定张量具有相同的形状和数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介
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()函数,效果是一样的。

代码检查 # 初始化模型优化器 generator = make_generator_model() discriminator = make_discriminator_model() cross_entropy = tf.keras.losses.BinaryCrossentropy() generator_optimizer = tf.keras.optimizers.Adam(1e-4) discriminator_optimizer = tf.keras.optimizers.Adam(1e-4) # 定义损失函数 def discriminator_loss(real_output, fake_output): real_loss = cross_entropy(tf.ones_like(real_output), real_output) fake_loss = cross_entropy(tf.zeros_like(fake_output), fake_output) return real_loss + fake_loss def generator_loss(fake_output): return cross_entropy(tf.ones_like(fake_output), fake_output) # 训练步骤 @tf.function def train_step(images): noise = tf.random.normal([BATCH_SIZE, NOISE_DIM]) with tf.GradientTape() as gen_tape, tf.GradientTape() as disc_tape: generated_images = generator(noise, training=True) real_output = discriminator(images, training=True) fake_output = discriminator(generated_images, training=True) gen_loss = generator_loss(fake_output) disc_loss = discriminator_loss(real_output, fake_output) gradients_of_generator = gen_tape.gradient(gen_loss, generator.trainable_variables) gradients_of_discriminator = disc_tape.gradient(disc_loss, discriminator.trainable_variables) generator_optimizer.apply_gradients(zip(gradients_of_generator, generator.trainable_variables)) discriminator_optimizer.apply_gradients(zip(gradients_of_discriminator, discriminator.trainable_variables)) return gen_loss, disc_loss # 训练循环 def train(dataset, epochs): for epoch in range(epochs): for image_batch in dataset: gen_loss, disc_loss = train_step(image_batch) # 每5个epoch输出一次生成结果 if (epoch + 1) % 5 == 0: generate_and_save_images(generator, epoch + 1, tf.random.normal([16, NOISE_DIM])) print(f'Epoch {epoch+1}, Gen Loss: {gen_loss}, Disc Loss: {disc_loss}') # 生成示例图像 def generate_and_save_images(model, epoch, test_input): predictions = model(test_input, training=False) fig = plt.figure(figsize=(4,4)) for i in range(predictions.shape[0]): plt.subplot(4, 4, i+1) plt.imshow(predictions[i, :, :, 0] * 127.5 + 127.5, cmap='gray') plt.axis('off') plt.savefig('image_at_epoch_{:04d}.png'.format(epoch)) plt.show() # 开始训练 train(train_dataset, EPOCHS)
最新发布
03-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值