TensorFlow 生成同形状全 1 张量方法


发布日期 : 2020-08-08 02:18:47 UTC

访问量: 10 次浏览

TensorFlow – 如何创建一个与输入张量形状相同的所有1的张量

TensorFlow是谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。

使用的方法:

  • ones\_like :这个方法接受一个张量作为输入,并返回一个具有相同形状的张量,所有的值都设置为1。

示例 1:

# importing the library
import tensorflow as tf

# Initializing the Input
input = tf.constant([[1, 2, 3], [4, 5, 6]])

# Generating Tensor with having all values as 1
res = tf.ones_like(input)

# Printing the resulting Tensors
print("Res: ", res )

输出:

Res: tf.Tensor(
[[1 1 1]
[1 1 1]], shape=(2, 3), dtype=int32)

例子2:
这个例子明确规定了产生的张量的类型。

# importing the library
import tensorflow as tf

# Initializing the Input
input = tf.constant([[1, 2, 3], [4, 5, 6]])

# Printing the Input
print("Input: ", input)

# Generating Tensor with having all values as 1
res = tf.ones_like(input, dtype = tf.float64)

# Printing the resulting Tensors
print("Res: ", res )

输出:

Input: tf.Tensor(
[[1 2 3]
[4 5 6]], shape=(2, 3), dtype=int32)
Res: tf.Tensor(
[[1. 1. 1.]
[1. 1. 1.]], shape=(2, 3), dtype=float64)