天道酬勤,学无止境

受约束的 np.polyfit(Constrained np.polyfit)

问题

我正在尝试对一些实验数据进行二次拟合,并在 numpy 中使用 polyfit。 我希望得到一条凹曲线,因此要确保二次项的系数为负,并且拟合本身也是加权的,因为点上有一些权重。 有没有简单的方法来做到这一点? 谢谢。

回答1

此处描述了权重的使用(numpy.polyfit)。 基本上,您需要一个与 x 和 y 长度相同的权重向量。

为了避免系数中的错误符号,您可以使用拟合函数定义,如

def fitfunc(x,a,b,c):
    return -1 * abs(a) * x**2 + b * x + c 

这将始终为您提供 x**2 的负系数。

回答2

您可以使用 curve_fit 。

或者你可以运行 rank 2 的 polyfit,如果最后一个系数大于 0。再次运行 linear polyfit(polyfit rank 1)

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • Python 中的约束回归(Constrained regression in Python)
    问题 我有这个简单的回归模型: y = a + b * x + c * z + error 对参数有限制: c = b - 1 SO 上发布了类似的问题(如 Python 中的约束线性回归)。 但是,约束的类型是lb <= parameter =< ub 。 处理这个特定约束线性回归问题的可用选项有哪些? 回答1 这是如何使用 GLM 完成的: import statsmodels import statsmodels.api as sm import numpy as np # Set the link function to identity statsmodels.genmod.families.links.identity() OLS_from_GLM = sm.GLM(y, sm.add_constant(np.column_stack(x, z))) '''Setting the restrictions on parameters in the form of (R, q), where R and q are constraints' matrix and constraints' values, respectively. As for the restriction in the aforementioned regression model, i.e., c
  • Constrained np.polyfit
    I am trying to fit a quadratic to some experimental data and using polyfit in numpy. I am looking to get a concave curve, and hence want to make sure that the coefficient of the quadratic term is negative, also the fit itself is weighted, as in there are some weights on the points. Is there an easy way to do that? Thanks.
  • Python编程-numpy polyfit说NAN(Python programming - numpy polyfit saying NAN)
    问题 我编写的一个非常简单的代码有一些问题。 我有4组数据,并想使用numpy polyfit生成多项式最佳拟合线。 使用polyfit时,列表中的3个产生数字,但是使用polyfit时,第三个数据集产生NAN。 下面是代码和打印输出。 有任何想法吗? 代码: 所有的“ ind_#”都是数据列表。 下面将它们转换为numpy数组,然后可以生成多项式最佳拟合线 ind_1=np.array(ind_1, np.float) dep_1=np.array(dep_1, np.float) x_1=np.arange(min(ind_1)-1, max(ind_1)+1, .01) ind_2=np.array(ind_2, np.float) dep_2=np.array(dep_2, np.float) x_2=np.arange(min(ind_2)-1, max(ind_2)+1, .01) ind_3=np.array(ind_3, np.float) dep_3=np.array(dep_3, np.float) x_3=np.arange(min(ind_3)-1, max(ind_3)+1, .01) ind_4=np.array(ind_4, np.float) dep_4=np.array(dep_4, np.float) x_4=np.arange(min(ind
  • numpy.polyfit有什么错误?(What's the error of numpy.polyfit?)
    问题 我想使用numpy.polyfit进行物理计算,因此我需要误差的大小。 回答1 如果在对polyfit的调用中指定full=True ,则它将包括其他信息: >>> x = np.arange(100) >>> y = x**2 + 3*x + 5 + np.random.rand(100) >>> np.polyfit(x, y, 2) array([ 0.99995888, 3.00221219, 5.56776641]) >>> np.polyfit(x, y, 2, full=True) (array([ 0.99995888, 3.00221219, 5.56776641]), # coefficients array([ 7.19260721]), # residuals 3, # rank array([ 11.87708199, 3.5299267 , 0.52876389]), # singular values 2.2204460492503131e-14) # conditioning threshold 返回的残差值是拟合误差的平方和,不确定这是否是您想要的结果: >>> np.sum((np.polyval(np.polyfit(x, y, 2), x) - y)**2) 7.1926072073491056 在1.7版中,还有一个cov关键字
  • How to fit a polynomial with some of the coefficients constrained?
    Using NumPy's polyfit (or something similar) is there an easy way to get a solution where one or more of the coefficients are constrained to a specific value? For example, we could find the ordinary polynomial fitting using: x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) z = np.polyfit(x, y, 3) yielding array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) But what if I wanted the best fit polynomial where the third coefficient (in the above case z[2]) was required to be 1? Or will I need to write the fitting from scratch?
  • 多维的 NumPy PolyFit 和 PolyVal?(NumPy PolyFit and PolyVal in Multiple Dimensions?)
    问题 假设一个 n 维观察数组被重新整形为二维数组,每行是一个观察集。 使用这种重塑方法, np.polyfit可以计算整个 ndarray(矢量化)的二阶拟合系数: fit = np.polynomial.polynomialpolyfit(X, Y, 2) 其中 Y 是形状 (304000, 21),X 是向量。 这会产生一个 (304000,3) 系数数组,拟合。 使用迭代器可以为每一行调用np.polyval(fit, X) 。 当可能存在矢量化方法时,这是低效的。 fit结果是否可以不迭代地应用于整个观察数组? 如果是这样,如何? 这与this SO question的思路一致。 回答1 np.polynomial.polynomial.polyval采用多维系数数组: >>> x = np.random.rand(100) >>> y = np.random.rand(100, 25) >>> fit = np.polynomial.polynomial.polyfit(x, y, 2) >>> fit.shape # 25 columns of 3 polynomial coefficients (3L, 25L) >>> xx = np.random.rand(50) >>> interpol = np.polynomial.polynomial.polyval
  • 如何从 Numpy 的 polyfit 推导出方程?(How to derive equation from Numpy's polyfit?)
    问题 给定一个 x 和 y 值数组,以下代码将计算这些数据点的回归曲线。 # calculate polynomial z = np.polyfit(x, y, 5) f = np.poly1d(z) # calculate new x's and y's x_new = np.linspace(x[0], x[-1], 50) y_new = f(x_new) plt.plot(x,y,'o', x_new, y_new) plt.xlim([x[0]-1, x[-1] + 1 ]) plt.show() 我怎样才能使用上面的来推导出这条曲线的实际方程? 回答1 如果要显示方程,可以使用sympy输出乳胶: from sympy import S, symbols, printing from matplotlib import pyplot as plt import numpy as np x=np.linspace(0,1,100) y=np.sin(2 * np.pi * x) p = np.polyfit(x, y, 5) f = np.poly1d(p) # calculate new x's and y's x_new = np.linspace(x[0], x[-1], 50) y_new = f(x_new) x = symbols("x") poly =
  • 在 numpy polyfit 中使用的权重值是多少,拟合的误差是多少(What are the weight values to use in numpy polyfit and what is the error of the fit)
    问题 我正在尝试对 numpy 中的某些数据进行线性拟合。 Ex(其中 w 是我对该值的样本数,即对于点(x=0, y=0)我只有 1 个测量值并且该测量值是2.2 ,但是对于点(1,1)我有 2 个测量值,值为3.5 。 x = np.array([0, 1, 2, 3]) y = np.array([2.2, 3.5, 4.6, 5.2]) w = np.array([1, 2, 2, 1]) z = np.polyfit(x, y, 1, w = w) 所以,现在的问题是:对于这些情况,在 polyfit 中使用w=w是否正确,或者我应该使用w = sqrt(w)我应该使用什么? 另外,如何从 polyfit 获得拟合误差? 回答1 如果您有正态分布的测量值,那么每个值的不确定度将与1/sqrt(n)成正比,其中n是测量值的数量。 你想通过你的不确定性的倒数来衡量你的适合度,所以你的第二个猜测是最好的: w=np.sqrt(n) 要获得参数的协方差,还可以给出cov=True 。 x = np.array([0, 1, 2, 3]) y = np.array([2.2, 3.5, 4.6, 5.2]) n = np.array([1, 2, 2, 1]) p, c = np.polyfit(x, y, 1, w=np.sqrt(n), cov=True)
  • 从 polyfit 中找到曲线的交点(Finding the intersection of a curve from polyfit)
    问题 这看起来很简单,但我无法弄清楚。 我有一条从 x,y 数据计算出来的曲线。 然后我有一条线。 我想找到两者相交处的 x、y 值。 这是我到目前为止所得到的。 这非常令人困惑,并且没有给出正确的结果。 我可以查看图表并找到交点 x 值并计算正确的 y 值。 我想删除这个人为的步骤。 import numpy as np import matplotlib.pyplot as plt from pylab import * from scipy import linalg import sys import scipy.interpolate as interpolate import scipy.optimize as optimize w = np.array([0.0, 11.11111111111111, 22.22222222222222, 33.333333333333336, 44.44444444444444, 55.55555555555556, 66.66666666666667, 77.77777777777777, 88.88888888888889, 100.0]) v = np.array([0.0, 8.333333333333332, 16.666666666666664, 25.0, 36.11111111111111, 47
  • Numpy / Polyfit-禁止打印Intel MKL错误消息(Numpy / Polyfit - Suppress printing of Intel MKL Error message)
    问题 我在程序执行过程中多次计算polyfit ,我的一些输入是np.nan ,并且将解决算法问题。 我知道这一点,在此应用程序中我不在乎。 当事情变得混乱时,这将打印到控制台: Intel MKL ERROR: Parameter 4 was incorrect on entry to DELSD. 我只是想抑制这个错误。 我已经尝试过: import warnings warnings.simplefilter('ignore', np.RankWarning) warnings.simplefilter('ignore', np.ComplexWarning) warnings.filterwarnings('ignore', "Intel MKL ERROR") 它取消了一些警告,但不消除英特尔MKL的警告。 我只是想阻止它在控制台中打印(因为它破坏了我正在打印的其他状态消息)。 以下应该触发该问题: import numpy as np def line_fit(R, X): num_rows = np.shape(R)[0] p = np.zeros(num_rows) for i in range(num_rows): temp = np.polyfit(R[i, :], X[i, :], 1) p[i] = temp[1] return p temp = np
  • Python programming - numpy polyfit saying NAN
    I am having some issues with a pretty simple code I have written. I have 4 sets of data, and want to generate polynomial best fit lines using numpy polyfit. 3 of the lists yield numbers when using polyfit, but the third data set yields NAN when using polyfit. Below is the code and the print out. Any ideas? Code: all of the 'ind_#'s are the lists of data. Below converts them into numpy arrays that can then generate polynomial best fit line ind_1=np.array(ind_1, np.float) dep_1=np.array(dep_1, np.float) x_1=np.arange(min(ind_1)-1, max(ind_1)+1, .01) ind_2=np.array(ind_2, np.float) dep_2=np.array
  • numpy.polyfit vs numpy.polynomial.polynomial.polyfit
    Why do numpy.polyfit and numpy.polynomial.polynomial.polyfit produce different plots in the test below? import numpy as np from numpy.polynomial.polynomial import polyfit import matplotlib.pyplot as plt x = np.linspace(0, 10, 50) y = 5 * x + 10 + (np.random.random(len(x)) - 0.5) * 5 plt.scatter(x, y,marker='.', label='Data for regression') plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)), label='numpy.polyfit') plt.plot(np.unique(x), np.poly1d(polyfit(x, y, 1))(np.unique(x)), label='polynomial.polyfit') plt.legend() plt.show()
  • 将 numpy.polyfit 应用于 xarray 数据集(Applying numpy.polyfit to xarray Dataset)
    问题 Xarray 是否支持 numpy 计算函数,例如 polyfit? 或者是否有一种有效的方法可以将此类函数应用于数据集? 示例:我想计算拟合到两个变量(温度和高度)的直线的斜率,以计算失效率。 我有一个数据集(如下),其中包含这两个维度为(垂直、时间、xgrid_0、ygrid_0)的变量。 <xarray.Dataset> Dimensions: (PressLev: 7, time: 48, xgrid_0: 685, ygrid_0: 485) Coordinates: gridlat_0 (ygrid_0, xgrid_0) float32 44.6896 44.6956 44.7015 44.7075 ... gridlon_0 (ygrid_0, xgrid_0) float32 -129.906 -129.879 -129.851 ... * ygrid_0 (ygrid_0) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... * xgrid_0 (xgrid_0) int64 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 ... * time (time) datetime64[ns] 2016-08-15T01:00:00 2016-08-15T02:00
  • 用numpy拟合数据(fitting data with numpy)
    问题 首先,我告诉我我所得到的可能不是我所期望的,也许您可​​以在这里为我提供帮助。 我有以下数据: >>> x array([ 3.08, 3.1 , 3.12, 3.14, 3.16, 3.18, 3.2 , 3.22, 3.24, 3.26, 3.28, 3.3 , 3.32, 3.34, 3.36, 3.38, 3.4 , 3.42, 3.44, 3.46, 3.48, 3.5 , 3.52, 3.54, 3.56, 3.58, 3.6 , 3.62, 3.64, 3.66, 3.68]) >>> y array([ 0.000857, 0.001182, 0.001619, 0.002113, 0.002702, 0.003351, 0.004062, 0.004754, 0.00546 , 0.006183, 0.006816, 0.007362, 0.007844, 0.008207, 0.008474, 0.008541, 0.008539, 0.008445, 0.008251, 0.007974, 0.007608, 0.007193, 0.006752, 0.006269, 0.005799, 0.005302, 0.004822, 0.004339, 0.00391 , 0.003481, 0.003095]) 现在,我想用一个4度多项式来拟合这些数据。
  • Fitting a quadratic function in python without numpy polyfit
    I am trying to fit a quadratic function to some data, and I'm trying to do this without using numpy's polyfit function. Mathematically I tried to follow this website https://neutrium.net/mathematics/least-squares-fitting-of-a-polynomial/ but somehow I don't think that I'm doing it right. If anyone could assist me that would be great, or If you could suggest another way to do it that would also be awesome. What I've tried so far: import numpy as np import matplotlib.pyplot as plt import pandas as pd ones = np.ones(3) A = np.array( ((0,1),(1,1),(2,1))) xfeature = A.T[0] squaredfeature = A.T[0] *
  • Covariance matrix from np.polyfit() has negative diagonal?
    Problem: the cov=True option of np.polyfit() produces a diagonal with non-sensical negative values. UPDATE: after playing with this some more, I am really starting to suspect a bug in numpy? Is that possible? Deleting any pair of 13 values from the dataset will fix the problem. I am using np.polyfit() to calculate the slope and intercept coefficients of a dataset. A plot of the values produces a very linear (but not perfectly) linear graph. I am attempting to get the standard deviation on these coefficients with np.sqrt(np.diag(cov)); however, this throws an error because the diagonal contains
  • Numpy / Polyfit - Suppress printing of Intel MKL Error message
    I'm computing a polyfit multiple times during a program, and some of my inputs are np.nan and are going to get the algorithm problems. I know this, and in this application I don't care. When things mess up, this is printed to the console: Intel MKL ERROR: Parameter 4 was incorrect on entry to DELSD. I simply want to suppress this error. I've already tried: import warnings warnings.simplefilter('ignore', np.RankWarning) warnings.simplefilter('ignore', np.ComplexWarning) warnings.filterwarnings('ignore', "Intel MKL ERROR") Which suppresses some warnings, but not the Intel MKL one. I simply want
  • 沿 dask 数组的轴应用函数(Applying a function along an axis of a dask array)
    问题 我正在分析来自气候模型模拟的海洋温度数据,其中 4D 数据数组(时间、深度、纬度、经度;在下面表示为dask_array )通常具有 ( dask_array ) 的形状dask_array 25GB 的大小(因此我希望使用 dask;我在尝试使用 numpy 处理这些数组时遇到了内存错误)。 我需要在每个级别/纬度/经度点沿时间轴拟合三次多项式并存储生成的 4 个系数。 因此,我设置了chunksize=(6000, 1, 1, 1)以便每个网格点都有一个单独的块。 这是我获取三次多项式系数的函数( time_axis轴值是在别处定义的全局 1D numpy 数组): def my_polyfit(data): return numpy.polyfit(data.squeeze(), time_axis, 3) (所以在这种情况下, numpy.polyfit返回长度为 4 的列表) 这是我认为需要将其应用于每个块的命令: dask_array.map_blocks(my_polyfit, chunks=(4, 1, 1, 1), drop_axis=0, new_axis=0).compute() 时间轴现在消失了(因此drop_axis=0 )并且在它的位置有一个新的系数轴(长度为 4)。 当我运行这个命令时,我得到IndexError: tuple index out
  • Fitting a polynomial using np.polyfit in 3 dimensions
    I have an array of data, with dimensions (N,3) for some integer N, that specifies the trajectory of a particle in 3D space, i.e. each row entry is the (x,y,z) coordinates of the particle. This trajectory is smooth and uncomplicated and I want to be able to fit a polynomial to this data. I can do this with just the (x,y) coordinates using np.polyfit: import numpy as np #Load the data some_file = 'import_file.txt' data = np.loadtxt(some_file) x = data[:,0] y = data[:,1] #Fit a 4th order polynomial fit = np.polyfit(x,y,4) This gives me the coefficients of the polynomial, no problems. How would I
  • How to fix “polyfit maybe poorly conditioned” in numpy?
    I am trying to do a polyfit on a set of data using numpy package. The following is the code, it can run successfully. The fitted line seems to fit the data when the order reaches around 20(very high). However, at the end, it says "Polyfit may be poorly conditioned". If I am not wrong, it is that when the degree gets higher, the fitting will be sensitive to the data, i.e. easily influenced by the data? How can I fix this? def gen_data_9(length=5000): x = 2.0 * (np.random.rand(length) - 0.5) * np.pi * 2.0 f = lambda x: np.exp(-x**2) * (-x) * 5 + x / 3 y = f(x) + np.random.randn(len(x)) * 0.5