麻木 [...,None]

Numpy [...,None]

我发现自己需要向现有的 numpy 数组添加功能,这导致了以下代码的最后一部分实际在做什么的问题:

   np.ones(shape=feature_set.shape)[...,None]

设置

举个例子,假设我希望通过使用 numpy 和求解来求解线性回归参数估计:

假设我有一个特征集形状 (50,1),一个形状为 (50,) 的目标变量,并且我希望使用我的目标变量的形状为截距值添加一列。

看起来像这样:

# Create random target & feature set
y_train = np.random.randint(0,100, size = (50,))
feature_set = np.random.randint(0,100,size=(50,1))

# Build a set of 1s after shape of target variable
int_train = np.ones(shape=y_train.shape)[...,None]

# Able to then add int_train to feature set 
X = np.concatenate((int_train, feature_set),1)

我所知道的

我看到包含 [...,None] 与不包含它时的输出差异。这是:

第二个版本returns输入数组需要相同维数的错误,最终我偶然发现了使用[...,None].[=15=的解决方案]

主要问题

虽然我看到 [...,None] 的输出给了我想要的东西,但我正在努力寻找关于 what 的任何信息,它实际上是应该做的。谁能告诉我这段代码的实际含义,None 参数的作用等等?

谢谢!

考虑这段代码:

np.ones(shape=(2,3))[...,None].shape 

如您所见,'None' 短语将 (2,3) 矩阵更改为 (2,3,1) 张量。事实上,它将矩阵放在张量的最后一个索引中。

如果你使用

np.ones(shape=(2,3))[None, ...].shape

它将矩阵放在张量的第一个索引中

[..., None] 的切片由两个“快捷方式”组成:

省略号文字部分:

The dots (...) represent as many colons as needed to produce a complete indexing tuple. For example, if x is a rank 5 array (i.e., it has 5 axes), then

  • x[1,2,...] is equivalent to x[1,2,:,:,:],
  • x[...,3] to x[:,:,:,:,3] and
  • x[4,...,5,:] to x[4,:,:,5,:].

(Source)

None 组件:

numpy.newaxis

The newaxis object can be used in all slicing operations to create an axis of length one. newaxis is an alias for ‘None’, and ‘None’ can be used in place of this with the same result.

(Source)

因此,arr[..., None] 获取维度数组 N 并“在末尾”为维度数组 N+1“添加”一个维度。

示例:

import numpy as np

x = np.array([[1,2,3],[4,5,6]])
print(x.shape)          # (2, 3)

y = x[...,None]
print(y.shape)          # (2, 3, 1)

z = x[:,:,np.newaxis]
print(z.shape)          # (2, 3, 1)

a = np.expand_dims(x, axis=-1)
print(a.shape)          # (2, 3, 1)

print((y == z).all())   # True
print((y == a).all())   # True