1

我试图用 scipy 拟合一个特定的函数,结果很奇怪。我决定测试一些我知道答案的东西,所以我创建了这个:

from scipy.optimize import curve_fit as cf
import numpy as np
import random

def func(x,a):
    return a+X

X =[]
for i in range (10):
    V = random.random()
    X.append(i+3 + V/10)

print cf(func, np.array(range(10)),np.array(X))

我希望得到大约 3 的东西,但是,这里的输出:

(array([ -2.18158824e-12]), inf)

作为旁注,我试图查看我发送的东西func,我得到了这个:

print func(np.array(range(10)),3)

Traceback (most recent call last):
  File "/tmp/py1759O-P", line 16, in <module>
    print func(np.array(range(10)),3)
  File "/tmp/py1759O-P", line 6, in func
    return a+X
TypeError: unsupported operand type(s) for +: 'int' and 'list

我究竟做错了什么?

4

2 回答 2

3

当它们具有如此不同的含义时,不要使用xandX作为变量名(或者你可能不知道 Python 区分大小写?):

def func(x,a):
    return a+X

X =[]

x是一个 numpy 数组,X是一个列表,a是一个标量参数值。

a+X导致错误,因为您无法将标量添加到列表中。

于 2012-09-06T15:59:03.803 回答
1

在 func 中,参数是x, 但X在函数体中使用。

这是您的代码的修改版本。它使用了 numpy 的更多功能(例如 np.random.random() 而不是 random.random())。

from scipy.optimize import curve_fit as cf
import numpy as np


def func(x, a):
    return a + x


n = 10
xdata = np.arange(n)
ydata = func(xdata, 3) + np.random.random(n) / 10

print cf(func, xdata, ydata)

输出是

(array([ 3.04734293]), array([[  8.19208558e-05]]))
于 2012-09-06T16:02:32.787 回答