Cosine Similarity Painless Snippet

int i = 0; int j = 0; double sum = 0; while (i < doc['interest.keys'].length && j < params.keys.length) { if (doc['interest.keys'][i] == params.keys[j]) { sum += doc['interest.values'][i] * params.values[j]; ++i; ++j; continue; } if (doc['interest.keys'][i] > params.keys[j]) { ++j; } else { ++i; } } double norm0 = 0; for (i=0; i<params.values.length; i++){ norm0 += params.values[i] * params.values[i]; } double norm1 = 0; for (i=0; i<doc['interest.values'].length; i++){ norm1 += doc['interest.values'][i] * doc['interest.values'][i]; } if(norm0 == 0) return 0; double norm = norm0 * norm1; return sum/norm;

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.