简体   繁体   English

循环以最小化python中的数组函数

[英]Loops to minimize function of arrays in python

I have some large arrays each with i elements, call them X, Y, Z, for which I need to find some values a, b--where a and b are real numbers between 0 and 1--such that, for the following functions, 我有一些大的数组,每个都有i个元素,称之为X,Y,Z,我需要找到一些值a,b - 其中a和b是0到1之间的实数 - 这样,对于以下职能,

r = X - a*Y - b*Z
r_av = Sum(r)/i
rms = Sum((r - r_av)^2), summing over the i pixels

I want to minimize the rms. 我想最小化rms。 Basically I'm looking to minimize the scatter in r, and thus need to find the right a and b to do that. 基本上我正在寻找最小化r中的散射,因此需要找到正确的a和b来做到这一点。 So far I have thought to do this in nested loops in one of two ways: either 1)just looping through a range of possible a,b and then selecting out the smallest rms, or 2)inserting a while statement so that the loop will terminate once rms stops decreasing with decreasing a,b for instance. 到目前为止,我已经考虑过以下两种方式之一在嵌套循环中执行此操作:1)只循环一系列可能的a,b然后选择最小的rms,或2)插入while语句以便循环将例如,一旦rms停止下降,a,b减小就终止。 Here's some pseudocode for these: 这是一些伪代码:

1) List

for a = 1
for b = 1
calculate m
b = b - .001
a = a - .001
loop 1000 times
sort m values, from smallest
print (a,b) corresponding to smallest m

2) Terminate

for a = 1
for b = 1
calculate m
while m > previous step, 
    b = b - .001
a = a - .001

Is one of these preferable? 其中一个更好吗? Or is there yet another, better way to go about this? 还是还有另一种更好的方法吗? Any tips would be greatly appreciated. 任何提示将非常感谢。

There is already a handy formula for least squares fitting. 最小二乘拟合已经有了一个方便的公式

I came up with two different ways to solve your problem. 我提出了两种不同的方法来解决你的问题。


For the first one, consider the matrix K : 对于第一个,考虑矩阵K

L = len(X)
K = np.identity(L) - np.ones((L, L)) / L

In your case, A and B are defined as: 在您的情况下, AB定义为:

A = K.dot(np.array([Y, Z]).transpose())
B = K.dot(np.array([X]).transpose())

Apply the formula to find C that minimizes the error A * C - B : 应用公式找到最小化误差A * C - B

C = np.linalg.inv(np.transpose(A).dot(A))
C = C.dot(np.transpose(A)).dot(B)

Then the result is: 然后结果是:

a, b = C.reshape(2)

Also, note that numpy already provides linalg.lstsq that does the exact same thing: 另外,请注意numpy已经提供了完全相同的linalg.lstsq

a, b = np.linalg.lstsq(A, B)[0].reshape(2)

A simpler way is to define A as: 更简单的方法是将A定义为:

A = np.array([Y, Z, [1]*len(X)]).transpose()

Then solve it against X to get the coefficients and the mean: 然后针对X解决它以获得系数和均值:

a, b, mean = np.linalg.lstsq(A, X)[0]

If you need a proof of this result, have a look at this post . 如果您需要此结果的证明,请查看此帖子


Example: 例:

>>> import numpy as np
>>> X = [5, 7, 9, 5]
>>> Y = [2, 0, 4, 1]
>>> Z = [7, 2, 4, 6]
>>> A = np.array([Y, Z, [1] * len(X)]).transpose()
>>> a, b, mean = np.linalg.lstsq(A, X)[0]
>>> print(a, b, mean)
0.860082304527 -0.736625514403 8.49382716049

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

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