scipy.optimize.curve_fit, typeerror: unsupported operand type

• Last Update :
• Techknowledgy :

Here is an example:

```import numpy as np
import scipy.optimize as optimize
def func2(x, a, b):
return a * np.exp(b * (x ** 2))

x = np.linspace(0, 1, 6).reshape(2, -1)
y = func2(x, 1, 1)
x = x.tolist()
y = y.tolist()
print(x)
#[[0.0, 0.2, 0.4], [0.6000000000000001, 0.8, 1.0]]
print(y)
#[[1.0, 1.0408107741923882, 1.1735108709918103], [1.4333294145603404, 1.8964808793049517, 2.718281828459045]]

popt, pcov = optimize.curve_fit(func2, x, y)
# TypeError: unsupported operand type(s) for ** or pow(): 'list'
and 'int'```

If we pass an array of shape (6,) then `func2` will return an array of shape (6,). Perfect. That's will do just fine:

```x = np.asarray(x).ravel()
y = np.asarray(y).ravel()
popt, pcov = optimize.curve_fit(func2, x, y)
print(popt)
#[1. 1.]```

What `x` values did you use? Following example works for me.

```from scipy.optimize
import curve_fit
import numpy as np

def func2(x, a, b):
return a * np.exp(b * (x ** 2))

x = np.linspace(0, 4, 50)
y = func2(x, 2.5, 2.3)
yn = y + 6. * np.random.normal(size = len(x))
popt, pcov = curve_fit(func2, x, yn)
print popt, pcov```

It gives the result depending on the `random` function:

```[1.64182333 2.00134505][
[1.77331612e+11 - 6.77171181e+09]
[-6.77171181e+09 2.58627411e+08]
]```

Are your `x` and `yn` values of type list? Following example gives your error message:

```print range(10) ** 2

TypeError: unsupported operand type(s) for ** or pow(): 'list'
and 'int'```

Python is trying to do something like this:

`[1, 2, 3] * 4`

This worked for me:

```def second_order_polynomial(x, a, b, c):
return [a * x0 ** 2 + b * x0 + c
for x0 in x
]```

Suggestion : 2

The reason you get this error seems to be that your function average returns None. Since you haven’t posted your code for average I can’t help you much more than that.,Hi Michael, Thank you so much for your reply. You are right, I forget to write a return in average function. ,Why I got an error : TypeError: unsupported operand type(s) for : ‘NoneType’ and ‘float’. It seems that there are something wrong in ‘ print average(lloyd[‘homework’])0.1’ How to fix it.,ResourcesArrow Chevron Down Filled IconProjectsNewInterview ChallengesDocsCheatsheetsArticlesVideosBlogCareer Center

Code 1: lloyd = { “name”: “Lloyd”, “homework”: [90.0, 97.0, 75.0, 92.0], “quizzes”: [88.0, 40.0, 94.0], “tests”: [75.0, 90.0] }

`print average(lloyd['homework'])`

Code 2: lloyd = { “name”: “Lloyd”, “homework”: [90.0, 97.0, 75.0, 92.0], “quizzes”: [88.0, 40.0, 94.0], “tests”: [75.0, 90.0] }

`print average(lloyd['homework']) * 0.1`

Suggestion : 3

Initial guess for the parameters (length N). If None, then the initial values will all be 1 (if the number of parameters for the function can be determined using introspection, otherwise a ValueError is raised).,The model function, f(x, …). It must take the independent variable as the first argument and the parameters to fit as separate remaining arguments.,The estimated covariance of popt. The diagonals provide the variance of the parameter estimate. To compute one standard deviation errors on the parameters use perr = np.sqrt(np.diag(pcov)).,Lower and upper bounds on parameters. Defaults to no bounds. Each element of the tuple must be either an array with the length equal to the number of parameters, or a scalar (in which case the bound is taken to be the same for all parameters). Use np.inf with an appropriate sign to disable bounds on all or some parameters.

```>>>
import matplotlib.pyplot as plt >>>
from scipy.optimize
import curve_fit```
```>>> def func(x, a, b, c):
...
return a * np.exp(-b * x) + c```
```>>> xdata = np.linspace(0, 4, 50) >>>
y = func(xdata, 2.5, 1.3, 0.5) >>>
rng = np.random.default_rng() >>>
y_noise = 0.2 * rng.normal(size = xdata.size) >>>
ydata = y + y_noise >>>
plt.plot(xdata, ydata, 'b-', label = 'data')```
```>>> popt, pcov = curve_fit(func, xdata, ydata) >>>
popt
array([2.56274217, 1.37268521, 0.47427475]) >>>
plt.plot(xdata, func(xdata, * popt), 'r-',
...label = 'fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))```
```>>> popt, pcov = curve_fit(func, xdata, ydata, bounds = (0, [3., 1., 0.5])) >>>
popt
array([2.43736712, 1., 0.34463856]) >>>
plt.plot(xdata, func(xdata, * popt), 'g--',
...label = 'fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))```
```>>> plt.xlabel('x') >>>
plt.ylabel('y') >>>
plt.legend() >>>
plt.show()```

Suggestion : 4

Given a Python list of values and a calculation you need to perform on each value, you might write a loop that runs the calculation for each value. After all, Python can’t run calculations on every element in a list at once, called element-wise operations, using basic operators:,We use np.array() to convert Python lists to NumPy arrays. Also, many of NumPy’s mathematical functions, such as np.sqrt(), can perform both scalar (number to number) and element-wise (array to array) operations. Here is an example that calculates the hypotenuse for 5 right triangles.,threshold is the optional argument that indicates the required vertical distance to its neighboring samples,You may be familiar with viewing, graphing, and performing calculations on your data in Excel, MATLAB, or R. We’ll show you in this tutorial that Python can be just as useful for data analysis!

```>>> x = [1, 2, 3, 4, 5] >>>
x / 2
TypeError: unsupported operand type(s) for /: 'list'
and 'int'```
```>>>
import numpy as np

>>>
a = np.array([1, 3, 5, 7, 9]) >>>
b = np.array([0, 4, 12, 24, 40]) >>>
c = np.sqrt(a ** 2 + b ** 2) >>>
c
array([1., 5., 13., 25., 41.])```
```>>> my2DArray = np.array([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]
])```
```>>> my2DArray[: , 0]
array([1, 4, 7, 10])

>>>
my2DArray[1,: ]
array([4, 5, 6])```
```>>> len(my2DArray) # length of array
4
>>>
np.size(my2DArray) # number of elements in array
12
>>>
np.shape(my2DArray) # dimensions of array(4, 3)```
```>>> x = np.array([1, 2, 3]) * u.m
>>> x / (4 * u.s)
<Quantity([0.25 0.5 0.75], 'meter / second' )>```

Suggestion : 5

Exercise 5 - Well type using Arps equation for multiple wells (Partial Solution)

```import pandas as pd
import os
import matplotlib.pyplot as plt
from functools
import partial
from scipy.optimize
import curve_fit```
```pair = {
'x': 1,
'y': 2
}
pair```
```{
'x': 1,
'y': 2
}```
`print(pair)`
```class Pair(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
#return 'Pair({0.x!r}, {0.y!r})'.format(self)
return f 'Pair({self.x},{self.y})'
def __str__(self):
return '({0.x!s}, {0.y!s})'.format(self)```
```class Pair(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
#return 'Pair({0.x!r}, {0.y!r})'.format(self)
print('This is the way the object is represented')
return f 'Pair({self.x},{self.y})'
def __str__(self):
print('This is the way I print')
return '({0.x!s}, {0.y!s})'.format(self)```