Created
April 2, 2025 14:20
-
-
Save olavfosse/35f935dfe5bc521a23c5396872c72745 to your computer and use it in GitHub Desktop.
Clojure Cosine Similarity
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
#?(:clj (defn cosine-similarity [vec1 vec2] | |
(let [dot-product (reduce + (map * vec1 vec2)) | |
magnitude-vec1 (Math/sqrt (reduce + (map #(Math/pow % 2) vec1))) | |
magnitude-vec2 (Math/sqrt (reduce + (map #(Math/pow % 2) vec2)))] | |
(if (or (zero? magnitude-vec1) (zero? magnitude-vec2)) | |
0 | |
(/ dot-product (* magnitude-vec1 magnitude-vec2)))))) | |
#?(:clj (defn double1:dot-product [^double/1 v1 ^double/1 v2] | |
(let [n (alength v1)] | |
(loop [sum 0.0 idx 0] | |
(if (= n idx) | |
sum | |
(recur (+ (* (aget v1 idx) (aget v2 idx)) | |
sum) | |
(inc idx))))))) | |
#?(:clj (defn double1:magnitude [^double/1 v] | |
(let [n (alength v)] | |
(loop [sum 0.0 idx 0] | |
(if (= n idx) | |
sum | |
(recur (+ (* (aget v idx) (aget v idx)) | |
sum) | |
(inc idx))))))) | |
#?(:clj (defn double1:cosine-similarity [^double/1 v1 ^double/1 v2] | |
(let [dot-product (double1:dot-product v1 v2) | |
magnitude-vec1 (double1:magnitude v1) | |
magnitude-vec2 (double1:magnitude v2)] | |
(if (or (zero? magnitude-vec1) (zero? magnitude-vec2)) | |
0 | |
(/ dot-product (Math/sqrt (* magnitude-vec1 magnitude-vec2))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The double-array implementation is somewhat optimised, but could probably be a lot faster :^)