Reputation: 53
I tried to use scipy.optimize package for regression. The model of the function is defined in func with parameters named as coeffs. I want to use the data xdata and ydata to learn the parameters using LS criterion.
I have the following TypeError: only length-1 arrays can be converted to Python scalars
from __future__ import division
import numpy
import scipy
from math import exp
import scipy.optimize as optimization
global m0,t0
t0 = 0.25
m0=1
def func(t, coeffs):
a = coeffs[0]
b = coeffs[1]
m = (a/b + m0 )*exp(b*(t-t0))-a/b
return m
# fitting test
x0 = numpy.array([5, -5], dtype=float)
def residuals(coeffs, y, t):
return y - func(t, coeffs)
xdata = numpy.array([0.25,0.5,1])
ydata = numpy.array([1.0,0.803265329856,0.611565080074])
from scipy.optimize import leastsq
x = leastsq(residuals, x0, args=(ydata, xdata))
return parameters are expected around [2,-1].
Upvotes: 0
Views: 88
Reputation: 1981
Do not use from math import exp
, replace it by from numpy import exp
so that your arrays are correctly handled: the numpy.exp
function will return the array expected by scipy, with each element converted to its exponential value.
Upvotes: 2