Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

numpy - scipy.optimize.curve_fit: not a proper array of floats error

I'm trying to use optimization.curve_fit to find the least square solution between two arrays, but I keep getting error: Result from function call is not a proper array of floats. I pasted my code below. Any ideas how to fix this? Thank you!

import numpy as np
import scipy.optimize as optimization

pcone = np.array([[-0.01043151],
  [-0.00135030],
  [-0.02566969],
  [-0.02822495],
  [-0.05463625],
  [-0.00969918],
  [-0.01332421],
  [-0.03364439],
  [-0.04009642],
  [-0.03556982]])

pctwo = np.array([[0.02550008],
  [0.04422852],
  [0.06685288],
  [0.04751296],
  [0.02439405],
  [0.09654185],
  [0.03161849],
  [0.03834721],
  [0.01653997],
  [-0.00802414]])

def func(x, a, b, c):
    return a + b*x + c*x*x

print optimization.curve_fit(func, pcone, pctwo)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your arrays have shape (10, 1). That is, they are two-dimensional, with a trivial second dimension. In the simplest case, curve_fit expects one-dimensional arrays. Flatten pcone and pctwo into one-dimensional arrays before passing them to curve_fit.

For example, this works:

In [8]: curve_fit(func, pcone.ravel(), pctwo.ravel())
Out[8]: 
(array([ 0.05720879,  0.65281483, -2.67840575]),
 array([[  5.90887090e-04,   4.15822858e-02,   6.14439732e-01],
        [  4.15822858e-02,   4.07354227e+00,   6.94784914e+01],
        [  6.14439732e-01,   6.94784914e+01,   1.29240335e+03]]))

(You haven't shown how pcone and pctwo were created. It would probably be cleaner to create them as 1-D arrays in the first place, instead of flattening them later.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...