Lmfit错误:输入包含nan值

2024-09-27 21:31:55 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

import numpy as np
import matplotlib.pyplot as plt
from lmfit import Model

def gaussian(x, amp, cen, wid):
    """1-d gaussian: gaussian(x, amp, cen, wid)"""
    return (amp / (np.sqrt(2*np.pi*wid)) * np.exp(-(x-cen)**2 / (2*wid**2)))

xFull = []
yFull = []

fileTypex = np.dtype([('xFull', np.float)])
fileTypey = np.dtype([('yFull', np.float)])
fDatax = "xValue.dat"
fDatay = "yValue.dat"
xFull = np.loadtxt(fDatax, dtype=fileTypex)
yFull = np.loadtxt(fDatay, dtype=fileTypey)

TailCoreLim1 = 40
TailCoreLim2 = 100 


xCore = xFull[TailCoreLim1:TailCoreLim2]["xFull"]
yCore = yFull[TailCoreLim1:TailCoreLim2]["yFull"]

fileTypeCore = np.dtype([('Par', np.float)])
CoreFile = "CorePopt.dat"
CoreVal = np.loadtxt(CoreFile, dtype=fileTypeCore)
CoreI = CoreVal[0:1]["Par"]
CoreSig = CoreVal[1:2]["Par"]

gmodel = Model(gaussian)
result = gmodel.fit(yCore, x=xCore, amp=1.09054634, cen=0, wid=2.47388884)

plt.plot(xCore, yCore, 'bo')
plt.plot(xCore, result.best_fit, 'r-')

print 'CORE REPORT:'
print 'I1 = ', CoreI
print 'Sigma1 = ', CoreSig
print(result.fit_report())


xTailsx = xFull[0:(TailCoreLim1)]["xFull"]
yTailsx = yFull[0:(TailCoreLim1)]["yFull"]

fileTypeTail = np.dtype([('Par', np.float)])
TailFile = "TailPopt.dat"
TailVal = np.loadtxt(TailFile, dtype=fileTypeTail)
TailI = TailVal[0:1]["Par"]
TailSig = TailVal[1:2]["Par"]

gmodel = Model(gaussian)
result = gmodel.fit(yTailsx, x=xTailsx, amp=1.12567603, cen=0, wid=3.01133102)

plt.plot(xTailsx, yTailsx, 'bo')
plt.plot(xTailsx, result.best_fit, 'r-')

xTaildx = xFull[(TailCoreLim2):140]["xFull"]
yTaildx = yFull[(TailCoreLim2):140]["yFull"]

gmodel = Model(gaussian)
result = gmodel.fit(yTaildx, x=xTaildx, amp=1.12567603, cen=0, wid=3.01133102)

plt.plot(xTaildx, yTaildx, 'bo')
plt.plot(xTaildx, result.best_fit, 'r-')

print 'TAIL REPORT:'
print 'I2 = ', TailI
print 'Sigma2 = ', TailSig
print(result.fit_report())

plt.show()

当我运行它时,它会返回以下错误:ValueError:输入包含nan值,参考这一行:

^{pr2}$

此外,如果在高斯函数的定义中,我改变了值,那么它会以这种方式返回:

return (amp / (np.sqrt(2*np.pi) * wid)) * np.exp(-(x-cen)**2 / (2*wid**2))

我试着运行这个脚本,它没有任何错误。在

有人能解释一下问题在哪里吗?谢谢!在


Tags: plotnppltresultgaussianfitampprint
1条回答
网友
1楼 · 发布于 2024-09-27 21:31:55

你的例子中有很多额外的和不必要的代码,这使得它有点难以理解。但是,从本质上讲,您正在做(或者可以很容易地减少您的代码以便您这样做):

xFull = np.loadtxt("xValue.dat", dtype=np.float)
yFull = np.loadtxt("yValue.dat", dtype=np.float)

xCore = xFull[40:100]
yCore = yFull[40:100]

gmodel = Model(gaussian)
result = gmodel.fit(yCore, x=xCore, amp=1.09054634, cen=0, wid=2.47388884)

nan的出现可能是因为wid的某个非常小(接近零)的值,尽管我想这不太可能,我不记得曾经见过。在

或者nan可能来自你的数据,我见过很多次,你的代码看起来非常专注于操作你的数据。在

因此,首先验证您的数据xCore和{}不包含nan。当你这样做的时候,你可以绘制数据并验证它是高斯型的,你的初始值ampcen,和{}的初始值没有太远。在

如果所有这些看起来都正常,并且您仍然从fit中得到NaN ValueError,请打印出您的gaussian()函数中的值,以尝试了解是什么参数值导致了NaN。在

相关问题 更多 >

    热门问题