在 tensorflow 2.0 中添加 None 维度
Add None dimension in tensorflow 2.0
我有一个张量 xx
,形状为:
>>> xx.shape
TensorShape([32, 32, 256])
如何添加前导 None
维度以获得:
>>> xx.shape
TensorShape([None, 32, 32, 256])
我在这里看到了很多答案,但都与 TF 有关 1.x
TF 2.0 的直接方法是什么?
您可以使用 "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
在 TF2 中你可以使用 tf.expand_dims:
xx = tf.expand_dims(xx, 0)
xx.shape
> TensorShape([1, 32, 32, 256])
我有一个张量 xx
,形状为:
>>> xx.shape
TensorShape([32, 32, 256])
如何添加前导 None
维度以获得:
>>> xx.shape
TensorShape([None, 32, 32, 256])
我在这里看到了很多答案,但都与 TF 有关 1.x
TF 2.0 的直接方法是什么?
您可以使用 "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
在 TF2 中你可以使用 tf.expand_dims:
xx = tf.expand_dims(xx, 0)
xx.shape
> TensorShape([1, 32, 32, 256])