Last active
June 25, 2017 22:35
-
-
Save evadne/d32dc5eb544ecca95e97bdf4f0cd9ba3 to your computer and use it in GitHub Desktop.
Cosine Similarity with Elixir
This file contains 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
defmodule Script do | |
def cosine_similarity(lhs, rhs) do | |
{ab, aa, bb} = accumulate(lhs, rhs) | |
ab / (:math.sqrt(aa) * :math.sqrt(bb)) | |
end | |
defp accumulate(lhs, rhs) do | |
accumulate(lhs, rhs, 0, 0, 0) | |
end | |
defp accumulate([], [], ab, aa, bb) do | |
{ab, aa, bb} | |
end | |
defp accumulate([h1|t1], [h2|t2], ab, aa, bb) do | |
accumulate(t1, t2, | |
ab + h1 * h2, | |
aa + h1 * h1, | |
bb + h2 * h2) | |
end | |
end | |
elixir_times = for (_ <- 1 .. 15) do | |
lhs = for (_ <- 1 .. 300), do: :rand.uniform() | |
rhs = for (_ <- 1 .. 300), do: :rand.uniform() | |
{result, _} = :timer.tc fn -> | |
Script.cosine_similarity(lhs, rhs) | |
end | |
result | |
end | |
elixir_average_time = elixir_times | |
|> (fn x -> Enum.sum(x) / length(x) end).() | |
IO.puts "elixir #{elixir_average_time}µs" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment