理解IPython中的numpy.linalg.norm()

use*_*779 11 python arrays numpy ipython

我正在为监督学习创建一个线性回归模型.

我在图表(x1,y1),(x2,y2),(x3,y3)等上绘制了一堆数据点,其中x是真实数据,y值是训练数据值.

作为编写基本最近邻居算法的下一步的一部分,我想创建一个距离度量来测量两个实例之间的距离(和相似性).

如果我想编写一个泛型函数来计算ipython中的L-Norm距离,我知道很多人都使用numpy.linalg.norm(arr,ord =,axis =).我很困惑的是如何格式化我的数据点数组,以便正确计算L-norm值.

如果我只有两个数据点,比如说(3,4)和(5,9),我的数组是否需要看起来像这样,每个数据点的值在一行中?

arry = ([[3,4] 
         [5,9]])
Run Code Online (Sandbox Code Playgroud)

或者它需要看起来像这样,所有的x轴值都在一行,y在另一行?

arry = ([[3,5]
         [4,9]])
Run Code Online (Sandbox Code Playgroud)

wfl*_*nny 8

numpy.linalg.norm(x) == numpy.linalg.norm(x.T)where .T表示转置.所以没关系.

例如:

>>> import numpy as np
>>> x = np.random.rand(5000, 2)
>>> x.shape
(5000, 2)
>>> x.T.shape
(2, 5000)
>>> np.linalg.norm(x)
57.82467111195578
>>> np.linalg.norm(x.T)
57.82467111195578
Run Code Online (Sandbox Code Playgroud)

编辑:

鉴于你的矢量基本上是

x = [[real_1, training_1],
     [real_2, training_2],
      ...
     [real_n, training_n]]
Run Code Online (Sandbox Code Playgroud)

然后Frobenius规范基本上是计算

np.sqrt(np.sum(x**2))
Run Code Online (Sandbox Code Playgroud)

您确定这是正确的指标吗?还有很多其他规范.这是3

np.sum((x[:,0]**2 - x[:,1]**2) # N-dimensional euclidean norm
np.sqrt(np.sum(x[:,0]**2) + np.sum(x[:,1]**2)) # L^2 norm
np.sqrt(x[:,0].dot(x[:,1])) # sqrt dot product
Run Code Online (Sandbox Code Playgroud)