[英]scipy.optimze curve_fit return wrong value
I was trying to fit a specific function with scipy and I got weird results. 我试图用scipy来适应一个特定的功能,我得到了奇怪的结果。 I decided to test something I know the answer to so I created this:
我决定测试一些我知道答案的东西,所以我创建了这个:
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))
I expected to get something around 3, nevertheless, here the output: 我预计会得到3左右的东西,不过,这里输出:
(array([ -2.18158824e-12]), inf)
As a side note, I tried to see what I send something to func
and I got this: 作为旁注,我试着看看我发送了什么东西到
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
What am I doing wrong? 我究竟做错了什么?
Don't use x
and X
as variable names when they carry such different meanings (or perhaps you didn't know Python is case sensitive?): 当它们具有不同的含义时,不要使用
x
和X
作为变量名(或者你可能不知道Python是区分大小写的?):
def func(x,a):
return a+X
X =[]
x
is a numpy array, X
is a list, and a
is a scalar parameter value. x
是一个numpy数组, X
是一个列表, a
是一个标量参数值。
a+X
results in an error since you can not add a scalar to a list. a+X
导致错误,因为您无法将标量添加到列表中。
In func, the argument is x
, but X
is used in the body of the function. 在func中,参数是
x
,但是X
在函数体中使用。
Here's a modified version of your code. 这是您的代码的修改版本。 It uses a few more features of numpy (eg np.random.random() instead of random.random()).
它使用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)
The output is 输出是
(array([ 3.04734293]), array([[ 8.19208558e-05]]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.