Last active
August 17, 2018 11:47
-
-
Save adekunleba/1e85a7e4836026057de90e745c1f0cae to your computer and use it in GitHub Desktop.
Basic Distance Calculation of two Vectors with Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import math._ | |
| object DistanceMetrics { | |
| /** | |
| * distance method helps get the Euclidean Distance between two vectors | |
| * Euclidean Distance tests the space betweeen two Vectors and the result is | |
| * between 0 and 2 where: | |
| * 0 means the space between them is 0 | |
| * 2 meanns the space between the two vector is at maximum | |
| * @param xs | |
| * @param ys | |
| * @return | |
| */ | |
| def distance(xs: Array[Double], ys: Array[Double]): Double = { | |
| sqrt( | |
| (xs zip ys).map { case (x, y) => pow(y - x, 2) }.sum) | |
| } | |
| /** | |
| * Compute the Cosine Similarity between Two Vectors. | |
| * It makes use of the dot_product and magnitute function | |
| * Answer of the Cosine Similarity should range between -1 and 1 | |
| * Where -1 means the Similarity between the two arrays is 180 and | |
| * 1 means there Similarity is at 0 | |
| * @param xs: X - Array[Double] to compare | |
| * @param ys Y - Array[DOuble] to compare | |
| * @return | |
| */ | |
| def cosine_similarity(xs: Array[Double], ys: Array[Double]): Double = { | |
| require(xs.length == ys.length) | |
| dot_product(xs, ys)/(get_magnitude(xs) * get_magnitude(ys)) | |
| } | |
| /** | |
| * Compute the Dot product of two 1-D Array[Double] | |
| * @param xs | |
| * @param ys | |
| * @return | |
| */ | |
| def dot_product(xs: Array[Double], ys: Array[Double]): Double = { | |
| xs.zip(ys).map { case (x, y) => x*y}.sum | |
| } | |
| def get_magnitude(xs: Array[Double]): Double= | |
| sqrt( | |
| xs.map(i => i * i).sum | |
| ) | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment