[英]Polynomial fit matlab with some constraints on the coefficients
我有数据,我应该插入一个必须是以下类型的函数:
f(x) = ax 4 + bx 2 + c
a > 0
且b ≤ 0
。 不幸的是,MATLAB的polyfit
不允许对多项式的系数进行任何约束。 有人知道是否有MATLAB功能吗? 否则,我该如何实现它?
非常感谢你提前,
伊丽莎白
您可以尝试使用fminsearch
, fminunc
手动定义目标函数。
或者,您可以将问题定义为略有不同:
f(x) = a 2 x 4 - b 2 x 2 + c
现在,新的a
和b
可以在没有约束的情况下进行优化,同时确保您正在寻找的最终a
和b
是正数(负分别)。
没有约束,问题可以作为简单的线性系统编写和解决:
% Your design matrix ([4 2 0] are the powers of the polynomial)
A = bsxfun(@power, your_X_data(:), [4 2 0]);
% Best estimate for the coefficients, [a b c], found by
% solving A*[a b c]' = y in a least-squares sense
abc = A\your_Y_data(:)
如果约束模型确实是您数据的基础,那么这些约束当然会自动得到满足。 例如,
% some example factors
a = +23.9;
b = -15.75;
c = 4;
% Your model
f = @(x, F) F(1)*x.^4 + F(2)*x.^2 + F(3);
% generate some noisy XY data
x = -1:0.01:1;
y = f(x, [a b c]) + randn(size(x));
% Best unconstrained estimate a, b and c from the data
A = bsxfun(@power, x(:), [4 2 0]);
abc = A\y(:);
% Plot results
plot(x,y, 'b'), hold on
plot(x, f(x, abc), 'r')
xlabel('x (nodes)'), ylabel('y (data)')
但是,如果对受约束模型未准确描述的数据施加约束,则可能会出现问题:
% Note: same data, but flipped signs
a = -23.9;
b = +15.75;
c = 4;
f = @(x, F) F(1)*x.^4 + F(2)*x.^2 + F(3);
% generate some noisy XY data
x = -1:0.01:1;
y = f(x, [a b c]) + randn(size(x));
% Estimate a, b and c from the data, Forcing a>0 and b<0
abc = fmincon(@(Y) sum((f(x,Y)-y).^2), [0 0 0], [-1 0 0; 0 +1 0; 0 0 0], zeros(3,1));
% Plot results
plot(x,y, 'b'), hold on
plot(x, f(x, abc), 'r')
xlabel('x (nodes)'), ylabel('y (data)')
(此解决方案具有a == 0
,表示模型选择不正确)。
如果a == 0
的完全相等是一个问题:如果设置a == eps(0)
,当然没有区别。 从数字上看,这对于真实世界的数据来说并不明显,但它仍然是非零的。
无论如何,我怀疑你的模型没有很好地选择,并且约束是一个“修复”以使一切正常工作,或者你的数据在尝试做任何适合之前实际上应该是无偏/重新调整的,或者某些类似的前提条件适用(我经常看到人们做这种事情,所以是的,我在这方面有点偏颇:)。
那么......这些限制背后的真正原因是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.