📜  TensorFlow – 如何创建与输入张量具有相同形状的所有张量

📅  最后修改于: 2022-05-13 01:55:27.928000             🧑  作者: Mango

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

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

示例 1:

Python3
# 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 )


Python3
# 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 )


输出:

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

示例 2:此示例明确指定结果张量的类型。

Python3

# 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)