且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 tensorflow 2.0 中添加无维度

更新时间:2022-10-19 08:36:56

您可以使用None"或 numpy 的newaxis"来创建新维度.

一般提示:您也可以使用 None 代替 np.newaxis;这些实际上是相同的对象.

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

尝试:%tensorflow_version 2.x除了例外:经过将张量流导入为 tf打印(tf.__version__)# TensorFlow 和 tf.keras从 tensorflow 导入 keras# 辅助库将 numpy 导入为 np#### 导入时尚 MNIST 数据集fashion_mnist = keras.datasets.fashion_mnist(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()#原始维度打印(train_images.shape)train_images1 = train_images[无,:,:,:]#使用无添加维度打印(train_images1.shape)train_images2 = train_images[np.newaxis 是 None,:,:,:]#使用 np.newaxis 添加维度打印(train_images2.shape)#np.newaxis 和 none 是相同的np.newaxis 是 None

以上代码的输出为

2.1.0(60000, 28, 28)(1, 60000, 28, 28)(1, 60000, 28, 28)真的

I have a tensor xx with shape:

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

How can I add a leading None dimension to get:

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

I have seen many answers here but all are related to TF 1.x

What is the straight forward way for TF 2.0?

You can either use "None" or numpy's "newaxis" to create the new dimension.

General Tip: You can also use None in place of np.newaxis; These are in fact the same objects.

Below is the code that explains both the options.

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

The Output of the above code is

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