scipy.optimize.curve_fit错误-由于函数不是正确的浮点数数组而导致 [英] scipy.optimize.curve_fit error- result from function not a proper array of floats

查看:166
本文介绍了scipy.optimize.curve_fit错误-由于函数不是正确的浮点数数组而导致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将二维voigt轮廓拟合到图像的一个子部分(主体),其中position是一个数组,该数组在整个图像中保留相应的x和y坐标以供传递.

I'm trying to fit a 2-d voigt profile to a subsection of an image (impart), where position is an array that holds the corresponding x and y coordinates in the whole image for impart.

在我看来,以下代码基于这两个print语句的输出,似乎确实应该工作.

The following code seems to me like it really ought to work, based on the output of the two print statements.

此外,如果有人对如何更快地构造位置数组有任何快速的建议,我将感谢numpy ndarrays的一些建议.我对他们还是个新手.

Also, if anyone has any quick suggestions on how to construct the position array faster, I'd appreciate some advice with numpy ndarrays. I'm still a little new to them.

import numpy as np
from scipy.special import wofz
from scipy.optimize import curve_fit
from math import pi

def voigt2d(pos,a,bx,by,Gc,Lc):
    val = np.zeros((5,5))

    for y in range(5):
        for x in range(5):
            dst = np.sqrt((pos[y][x][0]-bx)**2+(pos[y][x][1]-by)**2)

            z = ((dst+(Lc*1j))/(Gc*np.sqrt(2)))
            val[y][x] = a*wofz(z).real/(Gc*np.sqrt(2*pi))
    print val
    print val.dtype
    return val

x = np.arange(93,98)
y = np.arange(7,12)

xpos = np.array([x,x,x,x,x])
ypos = np.array([y,y,y,y,y])
ypos = np.rot90(ypos,k=3)

position = np.dstack((xpos,ypos))

impart = np.array([
    [971, 2425, 4331, 4280, 2697,],
    [1199, 3416, 6517, 4813, 2412],
    [1333, 3957, 7210, 4019, 2183],
    [1494, 4115, 4817, 3085, 1758],
    [1185, 2273, 2805, 2811, 1797]
    ],dtype=np.float64)

p,cov = curve_fit(voigt2d,position,impart)

推荐答案

我不确定这是否可以为您解决,但我相信您的问题与curve_fit期望您的模型函数返回一维有关模型数据数组.因此,最简单的方法是将自变量(position)表示为一维数组:

I'm not certain this will solve it for you, but I believe your issue is related to the fact curve_fit expects your model function to return a 1D array of model data. So the easiest thing to do would be to express your independent variables (position) as a 1D array:

>>> x = np.arange(93,98)
>>> y = np.arange(7,12)
>>> position = np.transpose([np.tile(x, len(x)), np.repeat(y, len(y))])
>>> position
array([[93,  7],
       [94,  7],
       [95,  7],
       [96,  7],
       [97,  7],
       [93,  8],
       [94,  8],
       [95,  8],
       [96,  8],
       [97,  8],
       [93,  9],
       [94,  9],
       [95,  9],
       [96,  9],
       [97,  9],
       [93, 10],
       [94, 10],
       [95, 10],
       [96, 10],
       [97, 10],
       [93, 11],
       [94, 11],
       [95, 11],
       [96, 11],
       [97, 11]])

然后,您必须调整模型功能以适应此新数组.

Then you would have to adjust your model function to accommodate this new array.

这篇关于scipy.optimize.curve_fit错误-由于函数不是正确的浮点数数组而导致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆