在tensorflow 2.0中添加None维

xyhw6mcr  于 2023-10-23  发布在  其他
关注(0)|答案(3)|浏览(110)

我有一个Tensorxx,形状为:

>>> xx.shape
TensorShape([32, 32, 256])

如何添加前导None维以获得:

>>> xx.shape
TensorShape([None, 32, 32, 256])

我在这里看到了很多答案,但都与TF 1.x有关。
TF 2.0的直接方式是什么?

quhf5bfb

quhf5bfb1#

你可以使用“None”或者numpy的“newaxis”来创建新的维度。

**一般提示:**您也可以使用None代替np.newaxis;实际上是same objects

下面是解释这两个选项的代码。

try:
  %tensorflow_version 2.x
except Exception:
  pass
import tensorflow as tf

print(tf.__version__)

# TensorFlow and tf.keras
from tensorflow import keras

# Helper libraries
import numpy as np

#### Import the Fashion MNIST dataset
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

#Original Dimension
print(train_images.shape)

train_images1 = train_images[None,:,:,:]
#Add Dimension using None
print(train_images1.shape)

train_images2 = train_images[np.newaxis is None,:,:,:]
#Add dimension using np.newaxis
print(train_images2.shape)

#np.newaxis and none are same
np.newaxis is None

上面代码的输出是

2.1.0
(60000, 28, 28)
(1, 60000, 28, 28)
(1, 60000, 28, 28)
True
luaexgnf

luaexgnf2#

在TF2中,您可以使用tf.expand_dims:

xx = tf.expand_dims(xx, 0)
xx.shape
> TensorShape([1, 32, 32, 256])
mqxuamgl

mqxuamgl3#

我认为不可能简单地增加一个“无”维度。
然而,假设你试图给你的Tensor添加一个可变大小的批量维度,你可以使用另一个Tensor的tf.shape()tf.repeat你的Tensor。

y = tf.keras.layers.Input(shape=(32, 32, 3))   # Shape: [None, 32, 32, 3]
...
batch_size = tf.shape(y)[0]                    # Will be None initially, but is mutable
xx = tf.ones(shape=(32, 32, 356))              # Shape: [32, 32, 356]
xx = tf.expand_dims(xx, 0)                     # Shape: [1, 32, 32, 356]
xx = tf.repeat(xx, repeats=batch_size, axis=0) # Shape: [None, 32, 32, 356]

这可能比仅仅将第一个维度硬编码为None更有用,因为您可能实际上想做的是根据批量大小将它沿着第一个维度一起复制。

相关问题