Python ``tensorflow.expand_dims()`` 函数用法详解与示例


发布日期 : 2022-08-24 15:49:32 UTC

访问量: 10 次浏览

Python – tensorflow.expand\_dims()

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

expand\_dims()
用于在输入张量中插入一个额外的维度。

语法:
tensorflow.expand_dims( input, axis, name)

参数:

  • input: 它是输入的张量。
  • axis: 它定义了要插入的尺寸的索引。如果输入有D个维度,那么轴的值必须在[-(D+1), D]范围内。
  • name (可选):它定义了该操作的名称。

返回:
它返回一个扩展维度的张量。

示例 1:

# Importing the library
import tensorflow as tf

# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])

# Printing the input
print('x:', x)

# Calculating result
res = tf.expand_dims(x, 1)

# Printing the result
print('res: ', res)

输出:

x: tf.Tensor(
[[ 2 3 6]
[ 4 8 15]], shape=(2, 3), dtype=int32)
res: tf.Tensor(
[[[ 2 3 6]]

[[ 4 8 15]]], shape=(2, 1, 3), dtype=int32)

# shape has changed from (2, 3) to (2, 1, 3)

示例 2:

# Importing the library
import tensorflow as tf

# Initializing the input
x = tf.constant([[2, 3, 6], [4, 8, 15]])

# Printing the input
print('x:', x)

# Calculating result
res = tf.expand_dims(x, 0)

# Printing the result
print('res: ', res)

输出:

x: tf.Tensor(
[[ 2 3 6]
[ 4 8 15]], shape=(2, 3), dtype=int32)
res: tf.Tensor(
[[[ 2 3 6]
[ 4 8 15]]], shape=(1, 2, 3), dtype=int32)

# shape has changed from (2, 3) to (1, 2, 3)