#!/usr/bin/env python
# -*- coding:utf-8 -*-
# python: Python 3.7.3
# pandas: pandas 0.25.3
# numpy : numpy 1.16.2
# scipy : scipy 1.4.1
import pandas as pd
import numpy as np
from scipy.linalg import qr, inv, pinv
import scipy.stats
from sklearn.cross_decomposition import PLSRegression
from progress.bar import Bar
from matplotlib import pyplot as plt
from sklearn.model_selection import LeaveOneOut
class SPA:
def _projections_qr(self, X, k, M):
'''
原版连续投影算法使用MATLAB内置的QR函数
该版本改用scipy.linalg.qr函数
https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.linalg.qr.html
X : 预测变量矩阵
K :投影操作的初始列的索引
M : 结果包含的变量个数
return :由投影操作生成的变量集的索引
'''
X_projected = X.copy()
# 计算列向量的平方和
norms = np.sum((X**2), axis=0)
# 找到norms中数值最大列的平方和
norm_max = np.amax(norms)
# 缩放第K列 使其成为“最大的”列
X_projected[:, k] = X_projected[:, k] * 2 * norm_max/norms[k]
# 矩阵分割 ,order 为列交换索引
_, __, order = qr(X_projected, 0, pivoting=True)
return order[:M].T
def _validation(self, Xcal, ycal, var_sel, Xval=None, yval=None):
'''
[yhat,e] = validation(Xcal,var_sel,ycal,Xval,yval) --> 使用单独的验证集进行验证
[yhat,e] = validation(Xcal,ycalvar_sel) --> 交叉验证
'''
N = Xcal.shape[0] # N 测试集的个数
if Xval is None: # 判断是否使用验证集
NV = 0
else:
NV = Xval.shape[0] # NV 验证集的个数
y