【发布时间】:2020-01-10 13:11:48
【问题描述】:
我正在尝试在没有 ML 框架的情况下使用 Java 中的 PCA 进行特征选择,只使用 Apache 数学矩阵库。
输入测试数据是一个二维数组,4 个特征列 x 100 行实例。我大致经历了以下步骤:
-
加载数据,归一化,存储在
RealMatrix类中并计算协方差矩阵:PCAResultSet pcaResultSet = new PCAResultSet(); double[][] data = dataToDoubleArray(); if (this.normalize == true) data = StatMath.normalize(data); RealMatrix origData = MatrixUtils.createRealMatrix(data); Covariance covariance = new Covariance(origData); /* The eigenvectors of the covariance matrix represent the * principal components (the directions of maximum variance) */ RealMatrix covarianceMatrix = covariance.getCovarianceMatrix(); -
执行特征分解并获得特征向量和特征值
/* Each of those eigenvectors is associated with an eigenvalue which can be * interpreted as the “length” or “magnitude” of the corresponding eigenvector. * If some eigenvalues have a significantly larger magnitude than others, * then the reduction of the dataset via PCA onto a smaller dimensional subspace * by dropping the “less informative” eigenpairs is reasonable. * * Eigenvectors represent the relative basis (axis) for the data * * Computes new variables from the PCA analysis */ EigenDecomposition decomp = new EigenDecomposition(covarianceMatrix); /* The numbers on the diagonal of the diagonalized covariance matrix * are called eigenvalues of the covariance matrix. Large eigenvalues * correspond to large variances. */ double[] eigenvalues = decomp.getRealEigenvalues(); /* The directions of the new rotated axes are called the * eigenvectors of the covariance matrix. * * Rows are eigenvectors */ RealMatrix eigenvectors = decomp.getV(); pcaResultSet.setEigenvectors(eigenvectors); pcaResultSet.setEigenvalues(eigenvalues); -
选择第一个
n特征向量(默认情况下它们是有序的),然后通过将转置的n x m特征向量与转置的原始数据相乘来投影数据/* Keep the first n-cols corresponding to the * highest PCAs */ int rows = eigenvectors.getRowDimension(); int cols = 1; RealMatrix evecTran = eigenvectors.getSubMatrix(0, rows - 1, 0, cols - 1).transpose(); RealMatrix origTran = origData.transpose(); /* The projected data onto the lower-dimension hyperplane */ RealMatrix dataProj = evecTran.multiply(origTran).transpose(); -
最后计算每个主成分的解释方差
/* The variance explained ratio of an eigenvalue λ_j is * simply the fraction of an eigenvalue λ_j and the total * sum of the eigenvalues */ double[] explainedVariance = new double[eigenvalues.length]; double sum = StatMath.sum(eigenvalues); for (int i = 0; i < eigenvalues.length; i++) explainedVariance[i] = ((eigenvalues[i] / sum) * 100); pcaResultSet.setExplainedVariance(explainedVariance); pcaResultSet.print(); Utils.print("PCA", "Projected Data:", 0, true); printMatrix(dataProj); return pcaResultSet;
使用此代码,PC1 解释了大约 90% 的方差,但我如何利用此结果执行特征选择,以确定要从原始数据中删除哪些特征?
像 Weka 这样的框架会对特征进行排名,以显示原始集合中哪个组合产生最高结果,我正在尝试做同样的事情,但不确定特征向量/decop 分数如何映射回原始特征
【问题讨论】:
标签: java machine-learning pca feature-selection