如何解决ValueError:操作数无法按形状(100,) (2,)广播的问题
曲线拟合报错:ValueError: operands could not be broadcast together with shapes (100,) (2,)
我需要绘制一张实现曲线拟合的图表,拟合公式为:
2*np.pi*np.sqrt((lx/g)*1+1/16*a**2)
运行代码时出现如下错误:
ValueError: operands could not be broadcast together with shapes (100,) (2,)
我推测是函数返回了矩阵导致绘图失败,目前使用的代码如下:
from scipy.optimize import curve_fit import matplotlib.pyplot as plt import numpy as np ##defining function of mathematical pendulum my_data =genfromtxt('lundd_3.csv',delimiter=',',skip_header=1) ##defining my variables lx=my_data[:,0].reshape(1,-1).flatten() ty=my_data[:,1] Xerr=my_data[:,2] Yerr=my_data[:,3] a=my_data[:,4] def mathPen(lx,a,g): ##here must be the error because it somehow creates here the matrix but I don't know why?? return 2*np.pi*np.sqrt((lx/g)*1+1/16*a**2) Fit=curve_fit(mathPen, lx, ty) fitParameter = Fit[0] fehlerMatrix = Fit[1] ##defining variable again g = fitParameter ##creating new values xFunk = np.linspace(np.min(lx),np.max(lx),100) print(xFunk) yFunk = mathPen(xFunk,a,g) plt.plot(xFunk,yFunk) plt.plot(lx,ty,markers='x',linestyle = 'none',color='blue') plt.show()
我已尝试使用np.reshape和flatten函数调整xFunk的形状,但问题仍未解决。请问能否通过改写函数或调整数值形状来解决该问题?
问题分析与解决方法
核心问题
- 拟合参数定义错误:你把已知变量
a放进了拟合函数的待拟合参数列表里,curve_fit会把a和g都当成需要拟合的参数,最后得到的fitParameter是包含两个值的数组,赋值给g后就变成了长度为2的数组。 - 数组广播不匹配:生成的
xFunk是长度100的数组,而a是原数据里的数组(长度和原始数据行数一致),两者形状不兼容,计算时触发广播错误。
修正步骤
- 重构拟合函数:把已知变量
a从待拟合参数中移除,函数只保留自变量lx和待拟合参数g,a作为外部参数传入。 - 正确调用
curve_fit:用args参数把已知的a传递给拟合函数,同时给g一个初始猜测值(比如9.8,接近重力加速度)。 - 修正参数传递逻辑:拟合完成后,
g取拟合结果的单个数值,避免数组维度问题。
修正后的完整代码
from scipy.optimize import curve_fit import matplotlib.pyplot as plt import numpy as np # 读取数据(补上漏掉的np.) my_data = np.genfromtxt('lundd_3.csv', delimiter=',', skip_header=1) # 定义变量,flatten已足够,无需额外reshape lx = my_data[:, 0].flatten() ty = my_data[:, 1] Xerr = my_data[:, 2] Yerr = my_data[:, 3] a = my_data[:, 4] # 修正拟合函数:仅保留自变量lx和待拟合参数g,a作为外部参数 def mathPen(lx, g, a): return 2 * np.pi * np.sqrt((lx / g) + (1/16) * (a ** 2)) # 调用curve_fit,用args传入已知的a,p0给g初始猜测值 Fit, fehlerMatrix = curve_fit(mathPen, lx, ty, p0=[9.8], args=(a,)) g_fit = Fit[0] # 拟合得到的g是单个数值 # 生成拟合曲线的x轴数据 xFunk = np.linspace(np.min(lx), np.max(lx), 100) # 计算拟合曲线的y值,参数顺序和函数定义一致 yFunk = mathPen(xFunk, g_fit, a) # 绘图,用scatter画散点更直观 plt.plot(xFunk, yFunk, label='拟合曲线') plt.scatter(lx, ty, marker='x', color='blue', label='原始数据') plt.xlabel('lx') plt.ylabel('ty') plt.legend() plt.show()
额外提示
- 如果需要展示误差棒,可以添加一行:
plt.errorbar(lx, ty, xerr=Xerr, yerr=Yerr, fmt='none', ecolor='gray') - 初始猜测值
p0可以根据你的数据范围调整,能提升拟合效率和准确性
内容的提问来源于stack exchange,提问作者Ann_neu
相关产品推荐
相关产品推荐

