【问题标题】:divide by zero encountered in true_divide error without having zeros in my data在我的数据中没有零的情况下遇到 true_divide 错误除以零
【发布时间】:2022-01-08 05:08:05
【问题描述】:

这是我的代码,这是我的数据,这是代码的输出。我尝试在 x 轴上添加一个值,认为也许值这么少可以解释为零。我不知道 true_divide 可能是什么,我无法解释这个除以零错误,因为我的数据中没有一个零,检查了我所有的 2500 个数据点。希望你们中的一些人可以提供一些澄清。提前致谢。

import pandas as pd
import matplotlib.pyplot as plt
from iminuit import cost, Minuit
import numpy as np

frame = pd.read_excel('/Users/lorenzotecchia/Desktop/Analisi Laboratorio/Analisi     dati/Quinta Esperienza/500Hz/F0000CH2.xlsx', 'F0000CH2')
data =  pd.read_excel('/Users/lorenzotecchia/Desktop/Analisi Laboratorio/Analisi     dati/Quinta Esperienza/500Hz/F0000CH1.xlsx', 'F0000CH1')
# tempi_500Hz = pd.DataFrame(frame,columns=['x'])
# Vout_500Hz = pd.DataFrame(frame,columns=['y'])
tempi_500Hz = pd.DataFrame(frame,columns=['x1'])
Vout_500Hz = pd.DataFrame(frame,columns=['y1']) 
# Vin_500Hz = pd.DataFrame(data,columns=['y'])

def fit_esponenziale(x, α, β):
    return α * (1 - np.exp(-x / β))

plt.xlabel('ω(Hz)')
plt.ylabel('Attenuazioni')
plt.title('Fit Parabolico')
plt.scatter(tempi_500Hz, Vout_500Hz)
least_squares = cost.LeastSquares(tempi_500Hz, Vout_500Hz, np.sqrt(Vout_500Hz), fit_esponenziale)
m = Minuit(least_squares, α=0, β=0)
m.migrad()
m.hesse()
plt.errorbar(tempi_500Hz, Vout_500Hz, fmt="o", label="data")
plt.plot(tempi_500Hz, fit_esponenziale(tempi_500Hz, *m.values), label="fit")
fit_info = [
f"$\\chi^2$ / $n_\\mathrm{{dof}}$ = {m.fval:.1f} / {len(tempi_500Hz) - m.nfit}",]

for p, v, e in zip(m.parameters, m.values, m.errors):
    fit_info.append(f"{p} = ${v:.3f} \\pm {e:.3f}$")

plt.legend()
plt.show()

input

output and example of data

【问题讨论】:

  • 嗨洛伦佐。几厘米。 1)尝试给出一个最小的工作示例,即如果可能,提供一个导致相同错误的最小数据集。 excel表格的图像没有帮助。 2)您的数据为负数,因此 fit 函数中的偏移量可能是个好主意。 3) 非线性拟合中的搜索算法可能会测试beta=0,因此会产生除以零。更好地使用y = off + a * ( 1 - exp( - b * x ) )。错误将b 传播到beta
  • 嗨!真的很感谢您的回答,所以我的拟合中使用的偏移量应该与我调整数据时使用的偏移量相同,以便成为非负数?
  • 当然,您可以像这样反转问题...它会在误差范围内为正
  • 不幸的是,将 10 添加到我的值没有用,而且我得到了相同的输出....,我认为我在之前的回复中所说的操作与您在您的第一次重播,显然我一开始没看懂
  • 试试def fit( x, a, b, c) : return a * ( 1- exp( - b * x ) ) + c

标签: pandas numpy data-analysis curve-fitting iminuit


【解决方案1】:

实际上有一种方法可以完全拟合这种线性。 参见例如here

import matplotlib.pyplot as plt
import numpy as np

from scipy.integrate import cumtrapz



def fit_exp(x, a, b, c):
    return a * (1 - np.exp( -b * x) ) + c

nn = 170
xl = np.linspace( 0, 0.001, nn )
yl = fit_exp( xl, 15, 5300, -8.1 ) + np.random.normal( size=nn, scale=0.05 )

"""
with y = a( 1- exp(-bx) ) + c
we have Y = int y = -1/b y + d x + h ....try it out or see below
so we get a linear equation for b (actually 1/b ) to optimize
this goes as:
"""

Yl = cumtrapz( yl, xl, initial=0 )
ST = [xl, yl, np.ones( nn ) ]
S = np.transpose( ST )

eta = np.dot( ST, Yl )
A = np.dot( ST, S )

sol = np.linalg.solve( A, eta )
bFit = -1/sol[1]
print( bFit )
"""
now we can do a normal linear fit
"""

ST = [ fit_exp(xl, 1, bFit, 0), np.ones( nn ) ]
S = np.transpose( ST )
A = np.dot( ST, S )
eta = np.dot( ST, yl )
aFit, cFit = np.linalg.solve( A, eta )

print( aFit, cFit )
print(aFit + cFit, sol[0] ) ### consistency check

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1 )
ax.plot(xl, yl, marker ='+', ls='' )
## at best a sufficient fit, at worst a good start for a non-linear fit
ax.plot(xl, fit_exp( xl, aFit, bFit, cFit ) ) 

plt.show()

"""
a ( 1 - exp(-b x)) + c = a + c - a exp(-b x) = d - a exp( -b x )
int y = d x + a/b exp( -b x ) + g
    = d x +a/b exp( -b x ) + a/b - a/b + c/b - c/b + g
    = d x - 1/b ( a - a exp( -b x ) + c ) + c/b + a/b + g
    = d x + k y + h
with k = -1/b and h = g + c/b + a/b.
d and h are fitted but not used, but as a+c = d we can check 
for consistency
"""


【讨论】:

  • 再次感谢您的帮助,虽然我不理解一致性检查,因为我的输出提供的结果与正上方的结果不同
  • 第一次拟合是将指数衰减作为线性拟合的技巧。通常这会引入其他对原始问题没有用的线性拟合参数。它们被丢弃。在知道b 拟合ac 之后是一个简单的线性任务。在这种情况下,有趣的是,在第一次拟合中弹出的附加参数之一是a + c。所以为了我们的安心,我们可以检查这个参数是否与第二次拟合的a + c一致。没有必要这样做。为了完整起见,我只想提及这一点。
  • 谢谢,你是我的救星!!
【解决方案2】:

这是一个有效的 Minuitcurve_fit 示例。我对函数进行了缩放,使得指数的衰减约为 1(对于非线性拟合通常是一个好主意)。最终,两种方法都给出了非常相似的结果。

注意:无论错误是否有意义,我都将其保持打开状态。初始值为零绝对是个坏主意。

import pandas as pd
import matplotlib.pyplot as plt
from iminuit import cost, Minuit
from scipy.optimize import curve_fit
import numpy as np

def fit_exp(x, a, b, c):
    return a * (1 - np.exp(- 1000 * b * x) ) + c

nn = 170
xl = np.linspace( 0, 0.001, nn )
yl = fit_exp( xl, 15, 5.3, -8.1 ) + np.random.normal( size=nn, scale=0.05 )

#######################
### Minuit
#######################
least_squares = cost.LeastSquares(xl, yl, np.sqrt( np.abs( yl ) ), fit_exp )
print(least_squares)
m = Minuit(least_squares, a=1, b=5, c=-7)
print( "grad: ")
print( m.migrad() ) ### needs to be called to get fit values
print( m.values )### gives slightly different output
print("Hesse:")
print( m.hesse() )

#######################
### curve_fit
#######################

opt, cov = curve_fit(
    fit_exp, xl, yl, sigma=np.sqrt( np.abs( yl ) ),
    absolute_sigma=True
)
print( " curve_fit: ")
print( opt )
print( " covariance ")
print( cov )

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1 )
ax.plot(xl, yl, marker ='+', ls='' )

ax.plot(xl, fit_exp(xl, *m.values), ls="--")
ax.plot(xl, fit_exp(xl, *opt), ls=":")


plt.show()

【讨论】:

  • @Lorenzo 欢迎...看看我的第二个帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-11
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多