Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 曲线拟合不能进行线性拟合_Python 2.7_Curve Fitting_Curve - Fatal编程技术网

Python 2.7 曲线拟合不能进行线性拟合

Python 2.7 曲线拟合不能进行线性拟合,python-2.7,curve-fitting,curve,Python 2.7,Curve Fitting,Curve,我有一个非常简单的数据,曲线拟合不能给我一个线性拟合。 代码如下: import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit ################# def linear(x,a,b): return a*x+b ################# N=[200,250,300,400,500,600,700] sp=[17,18,20,23,26,28,31

我有一个非常简单的数据,曲线拟合不能给我一个线性拟合。 代码如下:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
#################
def linear(x,a,b):
    return a*x+b
#################
N=[200,250,300,400,500,600,700]
sp=[17,18,20,23,26,28,31]
tp=[19,21.5,23.5,27,30,33,36]
#################
error=[0]*len(N)
for i in range(len(N)):
      error[i]=abs(sp[i]-tp[i])/(1.0*sp[i])*100
a,b=curve_fit(linear,N,error)
print a
plt.figure()
plt.plot(N,error,'r-o',label=r'${\rm relative\ error}$')
plt.plot(N,linear(N,*a))
plt.grid()
plt.savefig('error.pdf')
plt.show()
我得到的是毫无意义的:
所发生的事情可能不是最好的,因为
N
是一个列表,
a
大约为零。如果您调用
plt.plot(N,linear(np.array(N),*a))
,它应该可以工作。 此外,我强烈建议将变量重命名为
curve\u fit
返回最佳值数组和协方差矩阵。因此
bestFit,pcov=curve_fit(线性,N,误差)
然后
plt。plot(N,线性(np.array(N),*bestFit))
可能更好,避免混淆<代码>a,b=(曲线拟合(线性,N,误差))[0]可能会起作用,但您必须通过
plt.plot(N,线性(np.array(N,a,b))

最后,我会这样做:

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
#################
def linear( x, a, b):
    return a * x + b
#################
N =  np.array([ 200, 250, 300, 400, 500, 600, 700 ], np.float )
sp = np.array([ 17, 18, 20, 23, 26, 28, 31 ], np.float )
tp = np.array([ 19, 21.5, 23.5, 27, 30, 33, 36 ], np.float )
#################
error = np.fromiter( ( abs( s - t ) / s * 100 for s, t in zip( sp, tp ) ), np.float)
bestFit, pcov = curve_fit( linear, N, error )
fig = plt.figure()
ax = fig.add_subplot( 1, 1, 1 )
ax.plot( N, error, 'r-o', label=r'${\rm relative\ error}$' )
ax.plot( N,  linear( N, *bestFit ) )
ax.grid()
plt.show()

因此,它应该发挥作用