函数中使用数组出错:numpy.ufunc与float不支持**或pow()操作
Hey there, let's fix this error and get your curve fitting working properly! Here's what's going wrong and how to correct it step by step:
1. 核心错误:误用numpy的exp函数
The error you're seeing comes directly from this line in your Radio function:
return (n*(exp**(-(t/tao)))) + b
exp is a numpy universal function (ufunc)—it's not a numerical value, so you can't use the ** (power operator) on it. The correct way to calculate the exponential of -t/tao is to pass that value as an argument to the exp() function, like this:
return n * exp(-t / tao) + b
2. 函数参数顺序问题(潜在的拟合失败隐患)
Looking at how you're using curve_fit, your function's parameter order is backwards. curve_fit expects the first parameter to be the independent variable (in your case, t or T), followed by the parameters you want to fit. Your current definition has n (the dependent data) as the first parameter, which will cause curve_fit to misinterpret your inputs.
Fix the function definition to match the correct order. For example, if you're fitting the model N(t) = N0 * exp(-t/tao) + b, define it as:
def Radio(t, n0, tao, b): return n0 * exp(-t / tao) + b
3. 语法错误:无效的猜测值元组
Your guesses = (1,1...) line has invalid syntax—you can't use ... in a tuple like that. Replace it with concrete initial guess values for your parameters. For example, if you expect n0 around 100, tao around 5, and b around 0, write:
guesses = (100, 5, 0)
修正后的完整代码片段
Here's how your corrected code might look (adjust the guess values based on your actual data):
import numpy as np import matplotlib.pyplot as plt from numpy import sqrt, exp, log from scipy import linalg from scipy.optimize import curve_fit data1 = np.loadtxt('decay1.txt', float, skiprows=1) t = data1[:,0] n = data1[:,1] data2 = np.loadtxt('decay2.txt', float, skiprows=1) T = data2[:,0] N = data2[:,1] # Corrected function definition def Radio(t, n0, tao, b): return n0 * exp(-t / tao) + b # Valid initial guesses (adjust these to match your data's expected values) guesses = (100, 5, 0) # Example curve fit call for the first dataset params, covariance = curve_fit(Radio, t, n, p0=guesses) n_fit = Radio(t, *params) # Plot to check the fit plt.scatter(t, n, label='Raw data') plt.plot(t, n_fit, 'r-', label='Fitted curve') plt.xlabel('Time') plt.ylabel('Count') plt.legend() plt.show()
为什么这些修改有效?
- Fixing the
exp()syntax removes the invalid operation between a ufunc and a float, which was causing your original error. - Reordering the function parameters ensures
curve_fitcorrectly maps your independent variable (t) and dependent data (n) to the model. - Using a valid tuple for guesses avoids syntax errors and helps
curve_fitconverge to the correct parameters faster.
内容的提问来源于stack exchange,提问作者Brandon SeedlessBananas Mc-Wil

