0

I am trying to fit a polynomial curve into my data. x is the input and y is the expected output. for this aim I used the following code:

import numpy as np
from scipy.optimize import curve_fit

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

psnr_bitrate = np.vstack([
    np.loadtxt(path, dtype='float')
    for path in glob.iglob(r'E:/pythoncode/classification/*.txt')
])

x = np.zeros((11562,1))
y = np.zeros((11562,1))
x[0:1927] = 1
x[1927:3854] = 2
x[3854:5781] = 3
x[5781:7708] = 4
x[7708:9635] = 5
x[9635:11562] = 6

y[0:1927] = np.reshape(psnr_bitrate[:, 0], (1927, 1))
y[1927:3854] = np.reshape(psnr_bitrate[:, 1], (1927, 1))
y[3854:5781] = np.reshape(psnr_bitrate[:, 2], (1927, 1))
y[5781:7708] = np.reshape(psnr_bitrate[:, 3], (1927, 1))
y[7708:9635] = np.reshape(psnr_bitrate[:, 4], (1927, 1))
y[9635:11562] = np.reshape(psnr_bitrate[:, 5], (1927, 1))

popt, _ = curve_fit(objective, x, y)

But it produced the following error:

ValueError: object too deep for desired array
Traceback (most recent call last):
  File "<ipython-input-10-da34de5166d8>", line 1, in <module>
    popt, _ = curve_fit(objective, x, y)
  File "D:\software\Anaconda3\envs\py37\lib\site-packages\scipy\optimize\minpack.py", line 784, in curve_fit
    res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
  File "D:\software\Anaconda3\envs\py37\lib\site-packages\scipy\optimize\minpack.py", line 423, in leastsq
    gtol, maxfev, epsfcn, factor, diag)
error: Result from function call is not a proper array of floats.

What is the problem?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
david
  • 1,255
  • 4
  • 13
  • 26
  • I think you need to create the arrays 1-dimensional: `x=np.zeros(11562)` and `.reshape(..,1927)`. Removing the `,1` for all of those occurrences. – Raphael Feb 02 '22 at 12:52
  • Does this answer your question? [ValueError: object too deep for desired array while using convolution](https://stackoverflow.com/questions/15923081/valueerror-object-too-deep-for-desired-array-while-using-convolution) – mkrieger1 Feb 02 '22 at 12:58
  • What is your cost function? I'd guess it's MSE by default... If so, why wouldn't you use pseudo-inverse matrix to solve the least-squares optimization? – SomethingSomething Feb 02 '22 at 13:00

1 Answers1

0

I have to use x[:,0] instead of x, and for y is the same.

david
  • 1,255
  • 4
  • 13
  • 26