0

我有一个数据集,我试图从中得到一个平面的方程。即:a*x + b*y + c = z 在我的例子中,dT = x,dTa = y,Constant = c,dV = z。

我可以在 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

使用方阵:

>>> 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])

这些甚至不接近我以前得到的值!

有什么想法吗?任何建议表示赞赏。

4

2 回答 2

1

在第一个示例中,您需要使用numpy.linalg.lstsq. 无论哪种方式,您似乎都混淆了矩阵的行和列。使用类似的东西修复它numpy.linalg.solve(zip(dT, dTa, Constant), dV)

于 2012-08-14T23:33:59.830 回答
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 使用了不同的算法?

于 2012-08-15T18:47:56.117 回答