tf.expand_dims()

概述

tf.expand_dims()的功能、用法与np.expand_dims()相同,传入一个数组,改变该数组的维度后,并返回

语法

tf.expand_dims(
    input,
    axis,
    name=None
)
参数
  • input:一个Tensor
  • axis:整数,指定在哪个轴上增加维度

例子

对一维数组进行操作

import tensorflow as tf

a=tf.Variable([1,2,3,4])
print("a.shape:",a.shape)
print("a:",a)

print("-"*50)
a2 = tf.expand_dims(a,0)
print("a2.shape:",a2.shape)
print("a2:",a2)

print("-"*50)
a3 = tf.expand_dims(a,1)
print("a3.shape:",a3.shape)
print("a3:",a3)

执行结果:

a.shape: (4,)
a: <tf.Variable 'Variable:0' shape=(4,) dtype=int32, numpy=array([1, 2, 3, 4])>
--------------------------------------------------
a2.shape: (1, 4)
a2: tf.Tensor([[1 2 3 4]], shape=(1, 4), dtype=int32)
--------------------------------------------------
a3.shape: (4, 1)
a3: tf.Tensor(
[[1]
 [2]
 [3]
 [4]], shape=(4, 1), dtype=int32)

例子2

对二维数组进行操作


b=tf.constant([[1,2,3],[4,5,6]])
print("b.shape:",b.shape)
print("b:",b)

print("-"*50)
b2 = tf.expand_dims(b,1)
print("b2.shape:",b2.shape)
print("b2:",b2)

print("-"*50)
b3 = tf.expand_dims(b,2)
print("b3.shape:",b3.shape)
print("b3:",b3)

执行结果:

b.shape: (2, 3)
b: tf.Tensor(
[[1 2 3]
 [4 5 6]], shape=(2, 3), dtype=int32)
--------------------------------------------------
b2.shape: (2, 1, 3)
b2: tf.Tensor(
[[[1 2 3]]

 [[4 5 6]]], shape=(2, 1, 3), dtype=int32)
--------------------------------------------------
b3.shape: (2, 3, 1)
b3: tf.Tensor(
[[[1]
  [2]
  [3]]

 [[4]
  [5]
  [6]]], shape=(2, 3, 1), dtype=int32)

原文出处:/show_1EF4hVIIflen.html