我需要用 Java 实现 PCA。我有兴趣找到有据可查、实用且易于使用的东西。有什么推荐吗?
现在有许多 Java 的主成分分析实现。
Apache Spark:https://spark.apache.org/docs/latest/mllib-dimensionity-reduction#principal-component-analysis-pca
SparkConf conf = new SparkConf().setAppName("PCAExample").setMaster("local");
try (JavaSparkContext sc = new JavaSparkContext(conf)) {
//Create points as Spark Vectors
List<Vector> vectors = Arrays.asList(
Vectors.dense( -1.0, -1.0 ),
Vectors.dense( -1.0, 1.0 ),
Vectors.dense( 1.0, 1.0 ));
//Create Spark MLLib RDD
JavaRDD<Vector> distData = sc.parallelize(vectors);
RDD<Vector> vectorRDD = distData.rdd();
//Execute PCA Projection to 2 dimensions
PCA pca = new PCA(2);
PCAModel pcaModel = pca.fit(vectorRDD);
Matrix matrix = pcaModel.pc();
}
ND4J:https://javadoc.io/doc/org.nd4j/nd4j-api/latest/org/nd4j/linalg/Dimensionalityreduction/PCA.html
//Create points as NDArray instances
List<INDArray> ndArrays = Arrays.asList(
new NDArray(new float [] {-1.0F, -1.0F}),
new NDArray(new float [] {-1.0F, 1.0F}),
new NDArray(new float [] {1.0F, 1.0F}));
//Create matrix of points (rows are observations; columns are features)
INDArray matrix = new NDArray(ndArrays, new int [] {3,2});
//Execute PCA - again to 2 dimensions
INDArray factors = PCA.pca_factor(matrix, 2, false);
Apache Commons Math(单线程;无框架)
//create points in a double array
double[][] pointsArray = new double[][] {
new double[] { -1.0, -1.0 },
new double[] { -1.0, 1.0 },
new double[] { 1.0, 1.0 } };
//create real matrix
RealMatrix realMatrix = MatrixUtils.createRealMatrix(pointsArray);
//create covariance matrix of points, then find eigenvectors
//see https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues
Covariance covariance = new Covariance(realMatrix);
RealMatrix covarianceMatrix = covariance.getCovarianceMatrix();
EigenDecomposition ed = new EigenDecomposition(covarianceMatrix);
注意,奇异值分解也可用于查找主成分,具有等效的实现。
这是一个:PCA 类。
此类包含具有最大方差旋转的基本主成分分析所需的方法。可以选择使用协方差或相关矩阵进行分析。使用蒙特卡罗模拟进行并行分析。可以使用基于特征值大于统一、大于蒙特卡罗特征值百分位数或大于蒙特卡罗特征值均值的提取标准。
检查http://weka.sourceforge.net/doc.stable/weka/attributeSelection/PrincipalComponents.html weka 实际上有许多其他算法可以与 PCA 一起使用,而且 weka 还会不时添加更多算法。所以我认为,如果你正在使用 java,那么请切换到 weka api。
Smile 是一个成熟的 Java 机器学习库。您尝试一下它的 PCA 实现。请参阅:https://haifengl.github.io/smile/api/java/smile/projection/PCA.html
还有带有 Smile 的 PCA tutorial,但教程使用 Scala。
您可以在DataMelt项目中看到PCA的一些实现:
https://jwork.org/dmelt/code/index.php?keyword=PCA
(它们是用 Jython 重写的)。它们包括一些降维的图形示例。它们展示了几个 Java 包的用法,例如 JSAT、DatumBox 等。