在 tensorflow 2.0 中添加无维度 [英] Add None dimension in tensorflow 2.0

查看:69
本文介绍了在 tensorflow 2.0 中添加无维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为 xx 的张量:

<预><代码>>>>xx.shapeTensorShape([32, 32, 256])

如何添加前导 None 维度以获取:

<预><代码>>>>xx.shapeTensorShape([无, 32, 32, 256])

我在这里看到了很多答案,但都与 TF 1.x 相关

TF 2.0 的直接方法是什么?

解决方案

您可以使用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

这篇关于在 tensorflow 2.0 中添加无维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆