-1

i want to plot this function ( y = a * ln(x) + b ) in python. This is my Code:

def func(x, a, b):
return a * np.log(x) + b

popt, _ = curve_fit(func, x, y)
a, b = popt
x_line = arrange(min(x), max(x), 1)
y_line = func(x_line, a, b)
plt.plot(x_line, y_line)
plt.show()

My "x" contains this

array([[1790],
       [1800],
       [1810],
       [1820],
       [1830],
       [1840],
       [1850],
       [1860],
       [1870],
       [1880],
       [1900],
       [1910],
       [1920],
       [1930],
       [1940],
       [1950],
       [1960],
       [1970],
       [1980],
       [1990],
       [2000],
       [2010]], dtype=int64)

and my "y" this

array([[  3.929214],
       [  5.308483],
       [  7.239881],
       [  9.638453],
       [ 12.86602 ],
       [ 17.069453],
       [ 23.191876],
       [ 31.443321],
       [ 39.818449],
       [ 50.189209],
       [ 76.212168],
       [ 92.228496],
       [106.021537],
       [123.202624],
       [132.164569],
       [151.325798],
       [179.323175],
       [203.302031],
       [226.542199],
       [248.718302],
       [281.424603],
       [308.745538]])

But when i rund the code i always get this error:

object too deep for desired array

I hope someone can help me because i spend to much time on this.

Chrissi
  • 15
  • 8
  • 1
    why are the arrays (n,1) shape instead of (n,)? – hpaulj May 10 '21 at 21:35
  • 2
    Are these `x`, `y` really numpy arrays? Your errors suggest the source is a pandas dataframe and/or Series. (re)read what `curve_fit` requires. – hpaulj May 10 '21 at 21:46
  • Does this answer your question? [What does "ValueError: object too deep for desired array" mean and how to fix it?](https://stackoverflow.com/questions/15923081/what-does-valueerror-object-too-deep-for-desired-array-mean-and-how-to-fix-it) – mkrieger1 Feb 02 '22 at 13:03

2 Answers2

0

Try reshaping your arrays :

popt, _ = curve_fit(func, x.reshape(-1), y.reshape(-1))
Charles Dupont
  • 995
  • 3
  • 9
0

Your x and y variables are 2D (22 x 1) arrays because of the inner set of square brackets when scipy.optimize.curve_fit requires 1D arrays.

Either you can remove the inner brackets or slice x and y:

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def func(x, a, b):
  return a * np.log(x) + b

popt, _ = curve_fit(func, x[:,0], y[:,0])
a, b = popt
x_line = np.arange(min(x), max(x), 1)
y_line = func(x_line, a, b)
plt.plot(x_line, y_line)
plt.show()
user213305
  • 402
  • 2
  • 10
  • Okay now i get this Error: key of type tuple not found and not a MultiIndex – Chrissi May 10 '21 at 21:44
  • Are x and y numpy arrays? My example works for `x = np.array([[...]])`. If not you need to include your import statements to make it clear. – user213305 May 10 '21 at 21:46