[英]Normalizing vectors contained in an array
I've got an array, called X, where every element is a 2d-vector itself. 我有一个名为X的数组,其中每个元素本身都是2d向量。 The diagonal of this array is filled with nothing but zero-vectors.
该数组的对角线仅填充零向量。 Now I need to normalize every vector in this array, without changing the structure of it.
现在,我需要规范化此数组中的每个向量,而无需更改其结构。
First I tried to calculate the norm of every vector and put it in an array, called N. After that I wanted to divide every element of X by every element of N. Two problems occured to me: 首先,我尝试计算每个向量的范数并将其放入一个称为N的数组中。之后,我想将X的每个元素除以N的每个元素。我遇到了两个问题:
1) Many entries of N are zero, which is obviously a problem when I try to divide by them. 1)N的许多条目为零,这在我尝试除以它们时显然是一个问题。
2) The shapes of the arrays don't match, so np.divide() doesn't work as expected. 2)数组的形状不匹配,因此np.divide()不能按预期工作。
Beyond that I don't think, that it's a good idea to calculate N like this, because later on I want to be able to do the same with more than two vectors. 除了我不认为之外,这样计算N是一个好主意,因为稍后我希望能够对两个以上的向量进行相同的计算。
import numpy as np
# Example array
X = np.array([[[0, 0], [1, -1]], [[-1, 1], [0, 0]]])
# Array containing the norms
N = np.vstack((np.linalg.norm(X[0], axis=1), np.linalg.norm(X[1],
axis=1)))
R = np.divide(X, N)
I want the output to look like this: 我希望输出看起来像这样:
R = np.array([[[0, 0], [0.70710678, -0.70710678]], [[-0.70710678, 0.70710678], [0, 0]]])
You do not need to use sklearn
. 您不需要使用
sklearn
。 Just define a function and then use list comprehension: 只需定义一个函数,然后使用列表推导:
Assuming that the 0th dimension of the X is equal to the number of 2D arrays that you have, use this: 假设X的第0维等于您拥有的2D数组的数量,请使用以下命令:
import numpy as np
# Example array
X = np.array([[[0, 0], [1, -1]], [[-1, 1], [0, 0]]])
def stdmtx(X):
X= X - X.mean(axis =1)[:, np.newaxis]
X= X / X.std(axis= 1, ddof=1)[:, np.newaxis]
return np.nan_to_num(X)
R = np.array([stdmtx(X[i,:,:]) for i in range(X.shape[0])])
The desired output R
: 所需的输出
R
:
array([[[ 0. , 0. ],
[ 0.70710678, -0.70710678]],
[[-0.70710678, 0.70710678],
[ 0. , 0. ]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.