Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Cosine similarity function

I am trying to create a cosine similarity function and then display the results in a HTML element. I have written the following:

function cosinesim(A,B){
        var dotproduct=0;
        var mA=0;
        var mB=0;
        for(i = 0; i < A.length;){
            dotproduct += (A[i] * B[i]);
            mA += (A[i]*A[i]);
            mB += (B[i]*B[i]);
        }
        mA = Math.sqrt(mA);
        mB = Math.sqrt(mB);
        var similarity = (dotproduct)/(mA)*(mB)
        return similarity;
    }

//.....

var array1 = [1,0,0,1];
var array2 = [1,0,0,0];

var p = cosinesim(array1,array2);
document.getElementById("sim").innerHTML = String(p);

I have tested and both the arrays I am inputting are the same length, however when my code runs to this bit it crashes and I cant seem to find what is wrong.

Any help is appreciated, thanks.

like image 241
Future Avatar asked Mar 27 '26 05:03

Future


1 Answers

function cosinesim(A, B) {
    var dotproduct = 0;
    var mA = 0;
    var mB = 0;

    for(var i = 0; i < A.length; i++) {
        dotproduct += A[i] * B[i];
        mA += A[i] * A[i];
        mB += B[i] * B[i];
    }

    mA = Math.sqrt(mA);
    mB = Math.sqrt(mB);
    var similarity = dotproduct / (mA * mB);

    return similarity;
}


var array1 = [1, 0, 0, 1];
var array2 = [1, 0, 0, 0];

var p = cosinesim(array1, array2);

console.log(p);

This should give the actual cosine similarity. You were missing:

  1. The var i and i++ in your for loop, as mentioned before.
  2. Extra brackets around (mA * mB) in this line: var similarity = dotproduct / (mA * mB); Without them, the division is done before the multiplication.
like image 126
DiffXP Avatar answered Mar 28 '26 17:03

DiffXP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!