Created
July 30, 2012 03:52
-
-
Save wetmore/3204211 to your computer and use it in GitHub Desktop.
Cosine similarity calculator
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
var _ = require('underscore'); | |
var freqVector = function(word, letters) { | |
var freq = _.groupBy(word.split(''), function(l) {return l;}); | |
return _.map(letters, function(l) { | |
return freq[l] ? freq[l].length : 0; | |
}); | |
}; | |
var dot = function(v1, v2) { | |
return _.reduce(_.zip(v1, v2), function(acc, els) { | |
return acc + els[0] * els[1]; | |
}, 0); | |
}; | |
var mag = function(v) { | |
return Math.sqrt(_.reduce(v, function(acc, el) { | |
return acc + el * el; | |
}, 0)); | |
}; | |
var f = function(word1, word2) { | |
var letters = _.union(word1.split(''), word2.split('')); | |
var v1 = freqVector(word1, letters); | |
var v2 = freqVector(word2, letters); | |
return dot(v1, v2) / (mag(v1) * mag(v2)); | |
}; | |
var args = process.argv; | |
process.stdout.write(f(args[2], args[3]) + '\n'); | |
// usage: | |
// $ node cosine-sim.js apple application | |
// => 0.6416889479197478 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment