[PR & ML 2] [Introduction] Example: Polynomial Curve Fitting

啊啊啊,竟然不支持latex,竟然HTML代码不能包含javascript,代码编辑器也不支持Matlab!!!我要吐槽博客的编辑器。。。T_T只能贴图凑合看了,代码不是图,但这次为了省脑细胞,写的不简洁,凑合看吧。。。

 

 

numPoints = 10;
lnlambda = [-Inf -18 0];
M = 9; % [0, 1, 3, 9];
x = linspace(0,1);
% gt data for plotting
t = sin(2*pi*x);
ttest = t + normrnd(0,0.2, size(x));
    
% generate observed data  
if exist('C0_Curve_Fitting_data.mat', 'file')
    load('C0_Curve_Fitting_data.mat');
else
    xob = 0:1/(numPoints-1):1;
    tob = sin(2*pi*xob) + normrnd(0,0.2, size(xob));
    save('C0_Curve_Fitting_data.mat', 'xob', 'tob');
end

ERMStest = zeros(size(M));
ERMStrain = zeros(size(M));
figCount = 0;
% for i = 1:length(M)
i = 1;
for l = 1:length(lnlambda)
    Aob = [];
    A = [];
    for j = 0:M(i)
        Aob = [Aob (xob.^j)']; %#ok<AGROW>
        A = [A (x.^j)']; %#ok<AGROW>
    end

    w = (Aob'*Aob+eye(M(i)+1)*exp(lnlambda(l)))\(Aob'*tob');
    tpred = A*w;
    
    ERMStest(i) = sqrt(2*0.5*sum((tpred' - ttest).^2)/length(x));
    ERMStrain(i) = sqrt(2*0.5*sum((Aob*w - tob').^2)/length(x));
    figure(3);
    if M(i)==0 || M(i)==1 || M(i)==3 || M(i)==9
        disp('w=')
        disp(w);
        figCount = figCount + 1;
        subplot(1, 3, figCount);
        plot(xob,tob,'or');
        hold on;
        plot(x,t,'b');
        plot(x,tpred, 'g')
        hold off;
        text(0.6,1,['M = ' num2str(M(i))],'FontSize',14);
        text(0.6,1.3,['ln\lambda = ' num2str(lnlambda(l))], 'FontSize',14);
        xlabel('x');
        ylabel('t');
        set(gca,'FontSize',14)
    end
end

% figure(2)
% h1 = plot(M,ERMStest,'go-', 'LineWidth', 2);
% hold on;
% h2 = plot(M,ERMStrain,'bo-', 'LineWidth', 2);
% hold off;
% legend([h1, h2], 'Test', 'Training')
% set(gca,'FontSize',14)

 

 

posted @ 2016-08-18 18:13  TinaSmile  阅读(348)  评论(0编辑  收藏  举报