scipy.optimize.least_squares 的实现导致“TypeError: only size-1 arrays can be convert to Python scalars least_squares”的原因

问题描述

我正在尝试将正态分布拟合到来自 seaborn 的直方图值。我正在使用以下代码

from scipy.optimize import least_squares
from math import exp


def model_normal_dist(x,u):
    return x[0]*exp(-((x[1]-u)/x[2])**2)

def model_residual(x,u,y):
    print(model_normal_dist(x,u) - y)
    return model_normal_dist(x,u) - y

u=np.array([h.xy[0]+.5*h.get_width() for h in sns.histplot(data=data,x='visitor_prop1').patches])
y=np.array([h.get_height() for h in  sns.histplot(data=data,x='visitor_prop1').patches])
x=np.array([10000,.2,1])


res_1 = least_squares(model_residual,x,args=(u,y),verbose=1)

其中 data 是一个带有列的数据框,浮点值的“visitor_prop1”。当我运行它时,我得到 TypeError: only size-1 arrays can be converted to Python scalars。我试过将打印语句放在上述函数中,但它们显然从未运行过。

我已经测试过 u 和 y 是浮点数组。一个例子是:

print(u[0:30])
print(y[0:30])

[0.00109038 0.00327085 0.00545132 0.00763179 0.00981227 0.01199274
 0.01417321 0.01635368 0.01853415 0.02071462 0.02289509 0.02507556
 0.02725603 0.0294365  0.03161697 0.03379744 0.03597791 0.03815838
 0.04033886 0.04251933 0.0446998  0.04688027 0.04906074 0.05124121
 0.05342168 0.05560215 0.05778262 0.05996309 0.06214356 0.06432403]
[ 704.  658.  757.  754.  848.  920.  924.  980. 1048. 1124. 1134. 1300.
 1343. 1420. 1516. 1593. 1689. 1752. 1821. 1970. 1997. 2142. 2162. 2234.
 2409. 2602. 2624. 2715. 2914. 2927.]

我检查过 type(model_residual(x,u[5],y[5])) 返回 numpy.float64,它似乎是一个 python 标量 导致此错误的原因是什么?

解决方法

这个错误是由 math.exp() 引起的,它只适用于标量。 scipy.optimize.least_squares 需要能够对数组进行操作。解决方案是用 numpy.exp() 替换 math.exp():

def model_normal_dist(x,u):
    return x[0]*np.exp(-((x[1]-u)/x[2])**2)

或保持原样并更改导入:

from numpy import exp

打印语句无法运行,因为错误出在它们必须评估以打印的函数中。