TensorFlow – 如何创建一个所有元素都设置为一个的张量
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
Methods Used:
- tf.ones: This methods accepts the shape and type and returns a tensor of give shape and type having all values set to 1.
- tf.fill: This method accepts shape, value and type and returns a tensor of given shape and type having all values set to value.
示例 1:此示例使用 one() 方法创建一个所有元素都设置为 1 的张量。
Python3
# 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 )
Python3
# 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=float32)
示例 2:此示例使用 value = 1 的 fill() 方法创建一个所有元素都设置为 1 的张量。
Python3
# 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)