我想我发现了一个python numpy.polyfit()的bug

时间:2017-02-21 12:38:08

标签: python numpy

我想我发现了一个python numpy.polyfit()的bug。我使用numpy.polyfit和两个相同的数据,一个来自txt,另一个来自打字。但结果是不同的。为什么?请帮助我。

这是我的代码:

# -*- coding:utf-8 -*-
import re
from numpy.polynomial import polynomial
import numpy
import matplotlib.pyplot as plt
fl=open(r'C:\Users\yanzhiquan\Desktop\4-6.txt','r')
def stof(str):#把txt文件中的string变成数据
    if str:
        [e, t] = re.split(' ',str)
        e=int(e)
        t=float(re.sub('\n','',t))
        return e,t
def avi(fl):#生成x y
    x=[]
    y=[]
    for s in fl:
        [tx,ty]=stof(s)
        x.append(tx)
        y.append(ty)
    return x,y
x,y=avi(fl)
f=polynomial.polyfit(x,y,5)
f=numpy.poly1d(f)
print f
print x[0:10],type(x),type(x[1])
print y[0:10],type(y),type(y[1])
plt.plot(x,f(x),'g',x,y,'d')
plt.show()

结果:

        5         4         3          2
-0.6467 x + 3.384 x - 2.032 x + 0.5557 x - 0.06226 x + 0.00241
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <type 'list'> <type 'int'>
[1.2, 1.5, 1.9, 2.1, 4.0, 4.4, 4.9, 5.1, 4.0, 4.1] <type 'list'> <type 'float'>

txt文件的内容就是数据。 像这样:

1 1.2
2 1.5
3 1.9
4 2.1
5 4
6 4.4
7 4.9
8 5.1
9 4
10 4.1

这是我的测试代码,其结果应该是正确的:

import numpy
import matplotlib.pyplot as plt
x=[1,2,3,4,5,6,7,8,9,10]
y=[1.2,1.5,1.9,2.1,4.0,4.4,4.9,5.1,4.0,4.1]
f=numpy.polyfit(x,y,5)
f=numpy.poly1d(f)
print f
t=[]
i=0
while True:
    t.append(i)
    i=i+0.01
    if i>10:
       break
print x,type(x),type(x[1])
print y,type(y),type(y[1])
plt.plot(t,f(t),'r',x,y,'d')
plt.show()

结果:

         5           4          3         2
0.00241 x - 0.06226 x + 0.5557 x - 2.032 x + 3.384 x - 0.6467
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] <type 'list'> <type 'int'>
[1.2, 1.5, 1.9, 2.1, 4.0, 4.4, 4.9, 5.1, 4.0, 4.1] <type 'list'> <type 'float'>

3 个答案:

答案 0 :(得分:0)

您使用两种不同的polyfit例程。

numpy.polynomia.polynomial.polyfit

  

从低到高排序的多项式系数。

nupmy.polyfit

  

多项式系数,最高功率。

这就是为什么序数是系数的原因在第一个例子中得到了体现。 如果系数传递给numpy.poly1d,则nupmy.polyfit是要使用的正确函数。否则系数需要反转。

答案 1 :(得分:0)

为了使用从polynomy.poly1d获得的系数,你必须颠倒顺序。

这可以通过使用:

来完成
f = polynomial.polyfit(x,y,5)
f = numpy.poly1d(f[::-1])  ## Here is the change

您应该改进编码风格,以便能够解决更难的问题。您正在使用变量f,它在脚本过程中完全改变了它的含义。为什么不使用一个变量fit_params和另一个fit_function?通过这样做,您可以通过比较fit_params轻松找到您的错误。

你应该看到python和numpy的基本功能。使用标准的numpy代码可以非常低效地替换某些代码。例如:

t=[]
i=0
while True:
    t.append(i)
    i=i+0.01
    if i>10:
       break

可以是:

t2 = numpy.linspace(0, 10, 10001)

当你花时间学习一些基础教程时,你会好得多,例如:这里有一些很好的链接: Best online resource to learn Python?

答案 2 :(得分:0)

看到kazemakase如何更快地发现问题并写出答案,我只想补充一点,你可以在第一个例子中替换这行代码:

f = polynomial.polyfit(x, y, 5)

这一行:

f = polynomial.polyfit(x, y, 5)[::-1]

在两种情况下获得相同的系数顺序。

相关问题