NumPy:无法使用 `.reshape()` 添加维度。

huangapple go评论38阅读模式
英文:

NumPy: Can't add Dimension using .reshape()

问题

作为Conv2D任务的一部分,我被要求处理一个形状为(60000, 28, 28)的训练集,这包括训练图像的数量以及x轴和y轴的维度。在我正在进行的项目中,我被要求添加一个附加维度,使形状变为(60000, 28, 28, 1)。同时,一张图像也应返回形状(28, 28, 1)作为结果。

我尝试过images = training_images.reshape(60000, 28, 28, 1),但似乎只返回形状为(60000, 28, 28),并未返回额外的维度。

英文:

As part of a Conv2D task I've been set, I have a training set that is shape (60000, 28, 28), this consists of number of training images, x axis and y axis dimensions respectively. I'm asked in the project I'm working on to add an additional dimension that would result in the shape being (60000, 28, 28, 1). One image should also return the shape (28, 28, 1) as a result.

I have tried images = training_images.reshape(60000, 28, 28, 1) however this only seems to return the shape as (60000, 28, 28) and does not return the extra dimension.

答案1

得分: 2

你可以使用 expand_dims 在数组的任何轴上添加大小为 1 的维度。

import numpy as np

a = np.zeros((400, 28, 28))
b = np.expand_dims(a, axis=-1)
b.shape

> (400, 28, 28, 1)

或者,如果你需要一种更简洁的方式(例如在表达式中使用):

a = np.zeros((400, 28, 28))
a[..., np.newaxis].shape

> (400, 28, 28, 1)

这里的 ... 表示数组的每个维度(就像写 a[:, :, :, np.newaxis] 一样)。

如果你需要使用 reshape:

a = np.zeros((400, 28, 28))
a.reshape(*a.shape, 1).shape

> (400, 28, 28, 1)

*a.shape 展开了形状元组,并将每个元素作为 reshape 函数的参数传递(就像你写 a.reshape(400, 28, 28, 1) 一样)。

英文:

You can use expand_dims to add a dimension of size 1 in any of the array axis.

import numpy as np

a = np.zeros((400, 28, 28))
b = np.expand_dims(a, axis=-1)
b.shape

> (400, 28, 28, 1)

Or, if you need a shorter way (to use for example in an expression)

a = np.zeros((400, 28, 28))
a[..., np.newaxis].shape

> (400, 28, 28, 1)

where ... means every dimension of the array (it's like writing a[:, :, :, np.newaxis]).

If you need to use reshape:

a = np.zeros((400, 28, 28))
a.reshape(*a.shape, 1).shape

> (400, 28, 28, 1)

*a.shape unpacks the shape tuple and passes each element as an argument of the reshape function (exactly as if you wrote a.reshape(400, 28, 28, 1))

答案2

得分: 1

你需要这样做:

images = np.expand_dims(images, axis=-1)
英文:

You have to do it with:

images = np.expand_dims(images, axis=-1)

答案3

得分: 1

你也可以使用 np.newaxis

images = images[:, :, :, np.newaxis]

或者

images = images[..., np.newaxis]
英文:

You can also use np.newaxis:

images = images[:, :, :, np.newaxis]

or

images = images[..., np.newaxis]

huangapple
  • 本文由 发表于 2023年6月19日 18:41:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76505839.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定