2012-08-14 29 views
0

我有一個數據集,我試圖從中得到一個平面的方程。 即:a * x + b * y + c = z 在我的情況下,dT = x,dTa = y,Constant = c,dV = z。求解Python中的平面方程(如在Matlab中)

我能夠在Matlab中做到這一點很容易,代碼:

dT = [8.5; 3.5; .4; 12.9] 

dT = 

    8.5000 
    3.5000 
    0.4000 
    12.9000 

dTa = [8.5; 18; 22; 34.9] 

dTa = 

    8.5000 
    18.0000 
    22.0000 
    34.9000 

dV = [3; 1; .5; 3] 

dV = 

    3.0000 
    1.0000 
    0.5000 
    3.0000 

Constant = ones(size(dT)) 

Constant = 

    1 
    1 
    1 
    1 

coefficients = [dT dTa Constant]\dV 

coefficients = 

    0.2535 
    -0.0392 
    1.0895 

所以,在這裏,係數=(A,B,C)。

在Python中是否有相當的方法來做到這一點? 我一直在嘗試使用numpy模塊(numpy.linalg),但它的工作效果並不好。 其中之一,矩陣必須是方形的,即使如此,它也不會給出非常好的答案。例如:

錯誤:

>>> dT 
[8.5, 3.5, 0.4, 12.9] 
>>> dTa 
[8.5, 18, 22, 34.9] 
>>> dV 
[3, 1, 0.5, 3] 
>>> Constant 
array([ 1., 1., 1., 1.]) 
>>> numpy.linalg.solve([dT, dTa, Constant], dV) 

Traceback (most recent call last): 
    File "<pyshell#45>", line 1, in <module> 
    numpy.linalg.solve([dT, dTa, Constant], dV) 
    File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 312, in solve 
    _assertSquareness(a) 
    File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 160, in _assertSquareness 
    raise LinAlgError, 'Array must be square' 
LinAlgError: Array must be square 

Wokrking與方陣:

>>> dT 
array([ 8.5, 3.5, 12.9]) 
>>> dTa 
array([ 8.5, 18. , 34.9]) 
>>> dV 
array([3, 1, 3]) 
>>> Constant 
array([ 1., 1., 1.]) 
>>> numpy.linalg.solve([dT, dTa, Constant], dV) 
array([ 2.1372267 , 2.79746835, -1.93469505]) 

這些甚至還沒有接近我之前得到的值!

任何想法傢伙?任何意見讚賞。

+0

在您對問題的解釋中,您是不是指'dT = x,dTa = y'? – 2012-08-15 06:47:33

+0

對,我完全搞砸了。將立即編輯。 – sirgogo 2012-08-15 18:42:14

回答

0

所以,我發現這幅畫

,並適應它包括一個常數。這裏是我的解決代碼:

X = 0 
    XX = 0 
    XY = 0 
    XZ = 0 

    Y = 0 
    YY = 0 
    YZ = 0 

    Z = 0 

    for j in range(0, len(dTemp)): 
     X = X + dTemp[j] 
     XX = XX + (dTemp[j] * dTemp[j]) 
     XY = XY + (dTemp[j] * dTempA[j]) 
     XZ = XZ + (dTemp[j] * Applied[j]) 

     Y = Y + dTempA[j] 
     YY = YY + (dTempA[j] * dTempA[j]) 
     YZ = YZ + (dTempA[j] * Applied[j]) 

     Z = Z + Applied[j] 


    lhs = numpy.array([[XX, XY, X], [XY, YY, Y], [X, Y, 1]]) 
    rhs = numpy.array([XZ, YZ, Z]) 

    coefficients = numpy.linalg (lhs, rhs) 

    a = coefficients[0] 
    b = coefficients[1] 
    c = coefficients[2] 

我認爲做的伎倆!仍然值得一點,但也許這是因爲Matlab使用不同的算法?

1

在第一個示例中,您需要使用numpy.linalg.lstsq。無論哪種方式,你似乎混淆了矩陣的行和列。使用類似numpy.linalg.solve(zip(dT, dTa, Constant), dV)的方法修復它。

+0

對,我實際上使用scipy.array(dT).transpose()來翻轉它們。 – sirgogo 2012-08-15 18:49:13