Last active
August 29, 2015 14:11
-
-
Save renanreismartins/edf319dcf973d48cc781 to your computer and use it in GitHub Desktop.
manhattan distance
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
(use 'clojure.set) | |
(use 'clojure.math.numeric-tower) | |
(def data | |
{:Hailey {"Broken Bells" 4, | |
"Deadmau5" 1, | |
"Norah Jones" 4, | |
"The Strokes" 4, | |
"Vampire Weekend" 1} | |
:Veronica {"Blues Traveler" 3, | |
"Norah Jones" 5, | |
"Phoenix" 4, | |
"Slightly Stoopid" 2.5, | |
"The Strokes" 3} | |
:Jordyn {"Broken Bells" 4.5, | |
"Deadmau5" 4, | |
"Norah Jones" 5, | |
"Phoenix" 5, | |
"Slightly Stoopid" 4.5, | |
"The Strokes" 4, | |
"Vampire Weekend" 4.0}} | |
) | |
(def select-values (comp vals select-keys)) | |
(defn common-users-ratings [user-1 user-2] | |
(let [user-1-data (user-1 data) | |
user-2-data (user-2 data) | |
data-intersection (intersection (set (keys user-1-data)) | |
(set (keys user-2-data)))] | |
[(select-values user-1-data data-intersection) | |
(select-values user-2-data data-intersection)])) | |
(defn abs [n] (max n (- n))) | |
(defn manhattan-distance [ratings-a ratings-b] | |
(reduce + | |
(map (comp abs -) ratings-a ratings-b))) | |
(defn nearest-neighbor [user] | |
(let [other-users (remove (hash-set user) (keys data))] | |
(sort-by last (apply merge | |
(map (fn x [neighbor] | |
{neighbor (apply manhattan-distance | |
(common-users-ratings user neighbor))}) | |
other-users))))) | |
(defn recommend [user] | |
(let [nearest (first (first (nearest-neighbor user)))] | |
(sort-by last > (apply merge(map (fn x [band] | |
{band (get (nearest data) band)}) | |
(remove (set (keys (user data))) | |
(set (keys(nearest data)))))))) | |
) | |
(recommend :Hailey) | |
(defn pearson-correlation [ratings-1 ratings-2] | |
(let [numerator-first-expression (reduce + (map * ratings-1 ratings-2)) | |
ratings-1-sum (reduce + ratings-1) | |
ratings-2-sum (reduce + ratings-2) | |
numerator-second-expression (/ (* ratings-1 ratings-2) count(ratings-1)) | |
numerator (- numerator-first-expression numerator-second-expression) | |
])) | |
(expt 2 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bruno's Tavares solution: https://gist.github.com/bltavares/a6e665f6183390df0ea7