TensorFlow 中如何扩展张量维度
在 TensorFlow 中,可以使用 tf.expand_dims() 函数来对张量进行维度扩展。
tf.expand_dims() 函数的语法如下:
tf.expand_dims(input, axis)
其中,input 表示要扩展维度的张量,axis 表示要在哪个位置插入新的维度。
以下是一些示例,展示了如何使用 tf.expand_dims() 函数扩展张量的维度:
import tensorflow as tf
# 创建一个形状为(2, 3)的二维张量
x = tf.constant([[1, 2, 3], [4, 5, 6]])
# 在第0个位置插入新的维度
expanded_x = tf.expand_dims(x, 0)
print(expanded_x.shape) # 输出:(1, 2, 3)
# 在第1个位置插入新的维度
expanded_x = tf.expand_dims(x, 1)
print(expanded_x.shape) # 输出:(2, 1, 3)
# 在最后一个位置插入新的维度
expanded_x = tf.expand_dims(x, -1)
print(expanded_x.shape) # 输出:(2, 3, 1)
在上述示例中,通过 tf.expand_dims() 函数分别在不同的位置插入了新的维度,扩展了张量的维度。
原文地址: https://www.cveoy.top/t/topic/bnit 著作权归作者所有。请勿转载和采集!