0

其他一切正常,但是当我使用lealesq 函数时,pydev 编辑器出现错误,提示 Undefined variable from import: leastsq 这是怎么回事?

代码是麻省理工学院的python成本模型timing.py,网址为:http: //ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011 /readings/python-cost-model/timing.py 和 minimumsq 部分在函数中:

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

2 回答 2

0

在我看来,你给 LSQ 函数两个关键字参数,而它需要三个。您为它提供了函数、初始值,但没有提供要进行 LSQ 的实际值?

于 2013-06-03T11:10:01.237 回答
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

于 2019-09-07T15:40:58.367 回答