python - How do I iterate over an ndarray without using for/while loops?
问题描述
For two given 1-d arrays or lists I can calculate the squared Euclidean distance via the function
import numpy as np
def npdistance(x1, x2):
return sum((np.array(x1)-np.array(x2))**2)
Now for a given vector v and 2d-array X I would like to find the shortest squared Euclidean distance of any vector contained in X to the vector u without iterating over the elements of X with for/while loops. My attempt is
def npnearest(u, X):
L=npdistance(u,X)
return min(L)
which does not give me what I want. For example
npnearest(np.array([1,1,1]), np.array([[1,1,1],[2,3,4]]))
would give me 16 instead of 0. How can I do it?
解决方案
在 numpy 的情况下,更喜欢np.sum
and np.min
,而不是 Python buildinssum
和min
.
我们可以适应npdistance
2D numpy 向量:
def npdistance(x1, x2):
return np.sum((np.array(x1)-np.array(x2))**2, axis=1)
考虑矩阵x2
:
x2 = np.array([[1,1,1],[2,3,4]])
矩阵x2
有两个轴:
- 第零个是向量号:
x2[0]
isnp.array([1, 1, 1])
和x2[1]
isnp.array([2, 3, 4])
, - 第一个轴用于向量维度:
x2[1][1]
是3
(第一个向量的第二个元素)。
我们执行求和以获得每个向量axis=1
的距离。
- 没有
np.sum
axis=1
它会返回标量, - 使用 buildin
sum
给出所有向量的总和 (alaaxis=0
)。
npnearest
在这种情况下工作正常。
def npnearest(u, X):
L=npdistance(u,X)
return min(L)
npnearest(np.array([1,1,1]), np.array([[1,1,1],[2,3,4]]))
给出 0。
推荐阅读
- flutter - Flutter web中的容器装饰图像错误
- javascript - React JS 中的异步 API 获取
- visual-studio - TFS中绑定有什么用
- python - MYSQL 不接受来自插入语句的值
- android - webview中的React Native文本字段在最后一个文本字段重叠
- c++ - 骑士巡回赛问题没有给出正确的输出
- php - 如果数字大于 12,则使用 PHP 使数字从 1 开始
- python - 复制行和更改值 MySQL
- angular - Angular 9 - 如果输入由浏览器自动填充,则表单在 onInit 无效
- shell - csvcut:错误:无法识别的参数:filename.csv