拟合数据求极值时用UnivariateSpline报错:x must be increasing if s>0
解决UnivariateSpline的"x must be increasing if s > 0"错误并拟合求最小值
错误原因
UnivariateSpline在默认平滑参数s>0时,要求输入的x数组必须是严格单调递增的,你的ar_dist数组大概率是乱序的,因此触发了该报错。
解决步骤
- 先将
x和y按照x的升序重新排序,保证x单调递增 - 调整插值的
xs范围,贴合排序后x的实际区间,避免无效外插
修改后的完整代码
import matplotlib.pyplot as plt from scipy.interpolate import UnivariateSpline import numpy as np import pandas as pd # 读取数据 list_dist = pd.read_csv('C:/.../dist.txt') dist = list_dist['Distanze'] ar_dist = np.array(dist) list_energy = pd.read_csv('C:/.../energy.txt') energy = list_energy['Energie'] ar_energy = np.array(energy) x = ar_dist y = ar_energy # 关键:按照x升序排序,保证x和y对应关系不变 sort_indices = np.argsort(x) x_sorted = x[sort_indices] y_sorted = y[sort_indices] # 创建样条插值 s = UnivariateSpline(x_sorted, y_sorted) # 生成贴合数据范围的插值点 xs = np.linspace(x_sorted.min(), x_sorted.max(), 10000) ys = s(xs) # 寻找最小值 ys_min = np.min(ys) ys_min_pos = np.argmin(ys) xs_min = xs[ys_min_pos] print('UnivariateSpline: ') print(f'dist_min: {xs_min}\ten_min: {ys_min}') plt.plot(x_sorted, y_sorted, 'o') plt.plot(xs, ys) plt.show()
额外说明
- 如果不需要平滑效果,可以设置
s=0强制通过所有数据点,但此时仍要求x严格递增(无重复值),排序步骤依然必要 - 用
np.argsort获取排序索引,能确保x和y的对应关系不被破坏
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

