load spectra;
temp = randperm(size(NIR, 1)); P_train = NIR(temp(1:50),:);
T_train = octane(temp(1:50),:); P_test = NIR(temp(51:end),:);
T_test = octane(temp(51:end),:); [PCALoadings,PCAScores,PCAVar] = princomp(NIR); figure
percent_explained = 100 * PCAVar / sum(PCAVar);
pareto(percent_explained)
xlabel('主成分')
ylabel('贡献率(%)')
title('PCA:调用princomp函数实现各个主成分的贡献率—Jason niu') [PCALoadings,PCAScores,PCAVar] = princomp(P_train);
figure
plot(PCAScores(:,1),PCAScores(:,2),'r+')
title('PCA:通过PCA判断样本的测试集是否都在训练范围内—Jason niu')
hold on
[PCALoadings_test,PCAScores_test,PCAVar_test] = princomp(P_test);
plot(PCAScores_test(:,1),PCAScores_test(:,2),'o')
xlabel('1st Principal Component')
ylabel('2nd Principal Component')
legend('Training Set','Testing Set','location','best') k = 4;
betaPCR = regress(T_train-mean(T_train),PCAScores(:,1:k));
betaPCR = PCALoadings(:,1:k) * betaPCR;
betaPCR = [mean(T_train)-mean(P_train) * betaPCR;betaPCR]; N = size(P_test,1);
T_sim = [ones(N,1) P_test] * betaPCR; error = abs(T_sim - T_test) ./ T_test; R2 = (N * sum(T_sim .* T_test) - sum(T_sim) * sum(T_test))^2 / ((N * sum((T_sim).^2) - (sum(T_sim))^2) * (N * sum((T_test).^2) - (sum(T_test))^2)); result = [T_test T_sim error] figure
plot(1:N,T_test,'b:*',1:N,T_sim,'r-o')
legend('真实值','预测值','location','best')
xlabel('预测样本')
ylabel('辛烷值')
string = {'PCA:利用PCA降维提高《测试集辛烷值含量预测结果对比》的准确度—Jason niu';['R^2=' num2str(R2)]};
title(string)