其他一切正常但是当我使用leasesq函数时,pydev编辑器有一个错误,表示导入的未定义变量:leastsq这里发生了什么?
代码是网址:http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/readings/python-cost-model/timing.py的麻省理工学院的python成本模型timing.py 而且最小部分在函数中:
def fit2(A,b):
""" Relative error minimizer """
def f(x):
assert len(x) == len(A[0])
resids = []
for i in range(len(A)):
sum = 0.0
for j in range(len(A[0])):
sum += A[i][j]*x[j]
relative_error = (sum-b[i])/b[i]
resids.append(relative_error)
return resids
ans = scipy.optimize.leastsq(f,[0.0]*len(A[0]))
# print "ans:",ans
if len(A[0])==1:
x = [ans[0]]
else:
x = ans[0]
resids = sum([r*r for r in f(x)])
return (x,resids,0,0)
答案 0 :(得分:0)
在我看来,你给LSQ函数提供了两个关键字参数,而它需要三个。你是在为它提供函数,初始值,而不是用LSQ作实际值吗?
答案 1 :(得分:0)
与其对残差的计算进行硬编码,请尝试仅将残差包装为一个函数,该函数是数据值与最小化函数之间的差:
例如,仅将高斯函数拟合到某些数据集:
M = np.array(data) # your data as a Nx2 Matrix of (x, y) data points
initials = [3,2,1] # just some initial guess values
def gaussian(x, p):
return p[0]*np.exp((-(x-p[1])**2.0)/p[2]**2.0) # definition of the function
def residuals(p, y, x):
return y - gaussian(x, p) # definition of the residual
cnsts = leastsq(residuals, initials, args=(M[:,1], M[:,0]))[0] # outputs optimized initials