|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | + * contributor license agreements. See the NOTICE file distributed with |
| 4 | + * this work for additional information regarding copyright ownership. |
| 5 | + * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | + * (the "License"); you may not use this file except in compliance with |
| 7 | + * the License. You may obtain a copy of the License at |
| 8 | + * |
| 9 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | + * |
| 11 | + * Unless required by applicable law or agreed to in writing, software |
| 12 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | + * See the License for the specific language governing permissions and |
| 15 | + * limitations under the License. |
| 16 | + */ |
| 17 | + |
| 18 | +package org.apache.spark.examples.mllib |
| 19 | + |
| 20 | +import org.apache.spark.{SparkConf, SparkContext} |
| 21 | +import org.apache.spark.mllib.linalg.distributed.{MatrixEntry, CoordinateMatrix, RowMatrix} |
| 22 | + |
| 23 | +/** |
| 24 | + * Compute the similar columns of a matrix, using cosine similarity. |
| 25 | + */ |
| 26 | +object CosineSimilarity { |
| 27 | + def main(args: Array[String]) { |
| 28 | + val conf = new SparkConf().setAppName("CosineSimilarity") |
| 29 | + val sc = new SparkContext(conf) |
| 30 | + |
| 31 | + // Number of rows |
| 32 | + val M = 1000 |
| 33 | + // Number of columns |
| 34 | + val U = 1000 |
| 35 | + // Number of nonzeros per row |
| 36 | + val NNZ = 10 |
| 37 | + // Number of partitions for data |
| 38 | + val NUMCHUNKS = 4 |
| 39 | + |
| 40 | + // Create data |
| 41 | + val R = sc.parallelize(0 until M, NUMCHUNKS).flatMap{i => |
| 42 | + val inds = new scala.collection.mutable.TreeSet[Int]() |
| 43 | + while (inds.size < NNZ) { |
| 44 | + inds += scala.util.Random.nextInt(U) |
| 45 | + } |
| 46 | + inds.toArray.map(j => MatrixEntry(i, j, scala.math.random)) |
| 47 | + } |
| 48 | + |
| 49 | + val mat = new CoordinateMatrix(R, M, U).toRowMatrix() |
| 50 | + |
| 51 | + // Compute similar columns perfectly, with brute force. |
| 52 | + val simsPerfect = mat.columnSimilarities() |
| 53 | + |
| 54 | + println("Pairwise similarities are: " + simsPerfect.entries.collect.mkString(", ")) |
| 55 | + |
| 56 | + // Compute similar columns with estimation focusing on pairs more similar than 0.8 |
| 57 | + val simsEstimate = mat.columnSimilarities(0.8) |
| 58 | + |
| 59 | + println("Estimated pairwise similarities are: " + simsEstimate.entries.collect.mkString(", ")) |
| 60 | + |
| 61 | + sc.stop() |
| 62 | + } |
| 63 | +} |
0 commit comments