📌  相关文章
📜  TensorFlow – 如何向张量添加填充

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

TensorFlow – 如何向张量添加填充

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

填充意味着在张量值之前和之后添加值。

示例 1:此示例使用常量填充模式,即所有填充索引处的值都将是常量。

Python3
# importing the library
import tensorflow as tf
  
# Initializing the Input
input = tf.constant([[1, 2], [3, 4]])
padding = tf.constant([[2, 2], [2, 2]])
  
# Printing the Input
print("Input: ", input)
print("Padding: ", padding)
  
# Generating padded Tensor
res = tf.pad(input, padding, mode ='CONSTANT')
  
# Printing the resulting Tensors
print("Res: ", res )


Python3
# importing the library
import tensorflow as tf
  
# Initializing the Input
input = tf.constant([[1, 2, 5], [3, 4, 6]])
padding = tf.constant([[1, 1], [2, 2]])
  
# Printing the Input
print("Input: ", input)
print("Padding: ", padding)
  
# Generating padded Tensor
res = tf.pad(input, padding, mode ='REFLECT')
  
# Printing the resulting Tensors
print("Res: ", res )


输出:

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

示例 2:此示例使用 REFLECT 填充模式。要使此模式起作用,paddings[D, 0] 和 paddings[D, 1] 必须小于或等于 tensor.dim_size(D) – 1。

Python3

# importing the library
import tensorflow as tf
  
# Initializing the Input
input = tf.constant([[1, 2, 5], [3, 4, 6]])
padding = tf.constant([[1, 1], [2, 2]])
  
# Printing the Input
print("Input: ", input)
print("Padding: ", padding)
  
# Generating padded Tensor
res = tf.pad(input, padding, mode ='REFLECT')
  
# Printing the resulting Tensors
print("Res: ", res )

输出:

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