简体   繁体   English

NumPy 的 sum 方法中的参数 -1 是什么意思?

[英]What does the parameter -1 means in the sum method of the NumPy?

Consider the following code:考虑以下代码:

X = rand.rand(10, 2)
differences = X[:, np.newaxis, :] - X[np.newaxis, :, :]
differences = X[:, np.newaxis, :] - X[np.newaxis, :, :]
sq_differences = differences ** 2
dist_sq = sq_differences.sum(-1)

In this code, we're calculating the squared distance between the points in the cartesian plane (points are stored in the array X).在这段代码中,我们计算笛卡尔平面中点之间的平方距离(点存储在数组 X 中)。 Please explain the last step in this code, especially that -1 parameter in the sum method.请解释这段代码的最后一步,尤其是 sum 方法中的 -1 参数。

When Numpy.sum() is used to sum a multi dimenstional array it allows you to specify a dimension.当 Numpy.sum() 用于对多维数组求和时,它允许您指定维度。 For example dimension = 0 works along the column while dimemen =1 works along the row.例如,维度 = 0 沿列工作,而 dimemen =1 沿行工作。

This is explained better here Numpy.sum这在Numpy.sum 中有更好的解释

Now why -1 is used took a little more digging but is a very simple and sensible answer when you find it.现在为什么使用 -1 需要更多的挖掘,但是当你找到它时是一个非常简单和明智的答案。

When you pass dimensions as -1 it means to pick the last dimension in the array.当您将维度传递为 -1 时,这意味着选择数组中的最后一个维度。 Such that in a 2D array this would be column这样在二维数组中这将是列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM