TensorFlow 创建全 1 张量:``tf.ones()`` 与 ``tf.fill()`` 用法详解


发布日期 : 2021-06-06 17:37:04 UTC

访问量: 10 次浏览

TensorFlow – 如何创建一个所有元素都设置为1的张量

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

使用的方法

  • tf.ones:这个方法接受形状和类型,并返回一个给定形状和类型的张量,所有值都设置为1。
  • tf.fill:这个方法接受 shapevaluetype ,并返回一个给定的 shapetype 的张量,所有的值都设置为 value

示例

实例1:
本实例使用 ones() 方法创建一个所有元素都设置为1的张量。

# importing the library
import tensorflow as tf

# Generating a Tensor of shape (2, 3)
res = tf.ones(shape = (2, 3))

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

输出:

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

实例2:
本实例使用 fill() 方法,其值=1,创建一个所有元素都设置为1的张量。

# importing the library
import tensorflow as tf

# Generating a Tensor of shape (2, 3)
res = tf.fill(dims = (2, 3), value = 1)

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

输出:

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