将日志函数拟合到数据时出错。TypeError:只有大小为1的数组才能转换为Python标量

将日志函数拟合到数据时出错。TypeError:只有大小为1的数组才能转换为Python标量,python,Python,我试图回答一个问题,其中我必须定义函数,并使用曲线拟合将各种类型的函数拟合到一些数据点。我能够为线性、指数和幂函数创建函数。然而,当我尝试为对数函数创建一个函数时,我总是遇到相同的错误,如下所示 from pylab import * from numpy import * from scipy.optimize import * from scipy.stats import * import math # DATA # Demand x = np.array([3420, 3400,

我试图回答一个问题,其中我必须定义函数,并使用曲线拟合将各种类型的函数拟合到一些数据点。我能够为线性、指数和幂函数创建函数。然而,当我尝试为对数函数创建一个函数时,我总是遇到相同的错误,如下所示

from pylab import *
from numpy import *
from scipy.optimize import *
from scipy.stats import *
import math

# DATA

# Demand
x = np.array([3420,  3400, 3250, 3410, 3190, 3250, 2860, 2830, 3160, 2820, 2780, 2900, 2810, 2580, 2520, 2430])

# Price
y = np.array([127, 134, 136, 139, 140, 141, 148, 149, 151, 154, 155, 157, 159, 167, 168, 171])

# LINEAR

def linreg(x, a, b):
    return a*x + b

attributes, variances = curve_fit(linreg, x, y)
y_modeled = linreg(x, *attributes)
print("Linear")
plot(x, y, 'ob', markersize = 2)
plot(x, y_modeled, '-r', linewidth = 1)
show()

# EXPONENTIAL

def exp(x, a, b):
    return a*b**x

attributes, variances = curve_fit(exp, x, y)
y_modeled = exp(x, *attributes)
print("Exponential")
plot(x, y, 'ob', markersize = 2)
plot(x, y_modeled, '-r', linewidth = 1)
show()

# LOGARITHMIC 

def logarithmic(x, a):
    return math.log(x, a)

attributes, variances = curve_fit(logarithmic, x, y)
y_modeled = logarithmic(x, *attributes)
print("Logarithmic")
plot(x, y, 'ob', markersize = 2)
plot(x, y_modeled, '-r', linewidth = 1)
show()

# POWER CURVE

def power(x, a, b):
    return b*x**a

attributes, variances = curve_fit(power, x, y)
y_modeled = power(x, *attributes)
print("Power")
plot(x, y, 'ob', markersize = 2)
plot(x, y_modeled, '-r', linewidth = 1)
show()
我得到的错误如下:

TypeError: only size-1 arrays can be converted to Python scalars
以下是错误的附加输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-749e04792e23> in <module>
     44     return math.log(x, a)
     45 
---> 46 attributes, variances = curve_fit(logarithmic, x, y)
     47 y_modeled = logarithmic(x, *attributes)
     48 print("Logarithmic")

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs)
    782         # Remove full_output from kwargs, otherwise we're passing it in twice.
    783         return_full = kwargs.pop('full_output', False)
--> 784         res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
    785         popt, pcov, infodict, errmsg, ier = res
    786         ysize = len(infodict['fvec'])

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag)
    408     if not isinstance(args, tuple):
    409         args = (args,)
--> 410     shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
    411     m = shape[0]
    412 

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape)
     22 def _check_func(checker, argname, thefunc, x0, args, numinputs,
     23                 output_shape=None):
---> 24     res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
     25     if (output_shape is not None) and (shape(res) != output_shape):
     26         if (output_shape[0] != 1):

~\anaconda3\lib\site-packages\scipy\optimize\minpack.py in func_wrapped(params)
    482     if transform is None:
    483         def func_wrapped(params):
--> 484             return func(xdata, *params) - ydata
    485     elif transform.ndim == 1:
    486         def func_wrapped(params):

<ipython-input-31-749e04792e23> in logarithmic(x, a)
     42 
     43 def logarithmic(x, a):
---> 44     return math.log(x, a)
     45 
     46 attributes, variances = curve_fit(logarithmic, x, y)
---------------------------------------------------------------------------
TypeError回溯(最近一次调用上次)
在里面
44返回数学日志(x,a)
45
--->46属性,方差=曲线拟合(对数,x,y)
47 y_=对数(x,*属性)
48打印(“对数”)
~\anaconda3\lib\site packages\scipy\optimize\minpack.py曲线拟合(f、扩展数据、ydata、p0、西格玛、绝对西格玛、检查有限、边界、方法、jac、**kwargs)
782#删除kwargs的完整输出,否则我们将传入两次。
783 return\u full=kwargs.pop('full\u output',False)
-->784 res=leastsq(func,p0,Dfun=jac,满输出=1,**kwargs)
785 popt、pcov、infodict、ERRMG、ier=res
786 ysize=len(infodict['fvec'])
最少TSQ中的~\anaconda3\lib\site packages\scipy\optimize\minpack.py(func、x0、args、Dfun、完整输出、col_deriv、ftol、xtol、gtol、maxfev、epsfcn、factor、diag)
408如果不是isinstance(参数、元组):
409 args=(args,)
-->410形状,数据类型=_check_func('leastsq','func',func,x0,args,n)
411米=形状[0]
412
~\anaconda3\lib\site packages\scipy\optimize\minpack.py in\u check\u func(checker,argname,thefunc,x0,args,numinput,output\u shape)
22定义检查功能(检查程序、argname、thefunc、x0、args、numinputs、,
23输出(形状=无):
--->24 res=至少1d(thefunc(*(x0[:numput],)+args)))
25如果(输出形状不是无)和(形状(分辨率)!=输出形状):
26如果(输出_形[0]!=1):
函数包装中的~\anaconda3\lib\site packages\scipy\optimize\minpack.py(参数)
482如果转换为“无”:
483 def func_包装(参数):
-->484返回函数(扩展数据,*参数)-ydata
485 elif transform.ndim==1:
486 def func_包装(参数):
对数(x,a)
42
43 def对数(x,a):
--->44返回数学日志(x,a)
45
46属性,方差=曲线拟合(对数,x,y)

您不想调用
math.log
,而是
numpy.log
。由于您执行了
*
星型导入(不推荐,但很好),因此只需调用
日志
而不是
对数
即可解决此问题。