这篇文章将为大家详细讲解有关Spark中怎么实现矩阵相乘操作,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
1,Pom.xml引入 Spark-Mllib 类库
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-mllib --> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-mllib_2.11</artifactId> <version>2.3.1</version> <scope>runtime</scope> </dependency>
这里需要注意,因为我们需要使用相关API,所以这里<scope>runtime</scope>这句要去掉,使用默认的依赖方式就行了
<dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-mllib_2.11</artifactId> <scope>runtime</scope> </dependency>
2,代码
public static void main(String[] args) { SparkConf sparkConf = new SparkConf().setAppName("Mllib-test").setMaster("local"); JavaSparkContext jpc = new JavaSparkContext(sparkConf); double[][] data = new double[4][4] ; data[0][0] = 0.0; data[0][1] = 2.0; data[0][2] = 3.0; data[0][3] = 4.0; data[1][0] = 1.0; data[1][1] = 3.0; data[1][2] = 4.0; data[1][3] = 5.0; data[2][0] = 2.0; data[2][1] = 4.0; data[2][2] = 5.0; data[2][3] = 6.0; data[3][0] = 3.0; data[3][1] = 5.0; data[3][2] = 6.0; data[3][3] = 7.0; JavaRDD<IndexedRow> rdd=jpc.parallelize(Arrays.asList(data)).map(f->{ long key = new Double(f[0]).longValue(); double[] value = new double[f.length-1]; for(int i = 1;i<f.length;i++) { value[i-1] = f[i]; } return new IndexedRow(key,Vectors.dense(value)); }); BlockMatrix block = new IndexedRowMatrix(rdd.rdd()).toBlockMatrix(2, 2); double[][] data1 = new double[3][3] ; data1[0][0] = 0.0; data1[0][1] = 100.0; data1[0][2] = 10.0; data1[1][0] = 1.0; data1[1][1] = 10.0; data1[1][2] = 100.0; data1[2][0] = 2.0; data1[2][1] = 1.0; data1[2][2] = 1000.0; JavaRDD<IndexedRow> rdd1 = jpc.parallelize(Arrays.asList(data1)).map(f->{ long key = new Double(f[0]).longValue(); double[] value = new double[f.length-1]; for(int i = 1;i<f.length;i++) { value[i-1] = f[i]; } return new IndexedRow(key,Vectors.dense(value)); }); BlockMatrix block1 = new IndexedRowMatrix(rdd1.rdd()).toBlockMatrix(2, 2); block = block.multiply(block1); }
关于Spark中怎么实现矩阵相乘操作就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。