简体   繁体   中英

scipy.optimze curve_fit return wrong value

I was trying to fit a specific function with scipy and I got weird results. 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:

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

As a side note, I tried to see what I send something to func and I got this:

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?):

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

X =[]

x is a numpy array, X is a list, and a is a scalar parameter value.

a+X results in an error since you can not add a scalar to a list.

In func, the argument is x , but X is used in the body of the function.

Here's a modified version of your code. It uses a few more features of numpy (eg np.random.random() instead of 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]]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM