MyMediaLite.Correlation.BinaryCosine.ComputeCorrelations C# (CSharp) Method

ComputeCorrelations() public method

public ComputeCorrelations ( IBooleanMatrix entity_data ) : void
entity_data IBooleanMatrix
return void
        public override void ComputeCorrelations(IBooleanMatrix entity_data)
        {
            var transpose = entity_data.Transpose();

            var overlap = new SparseMatrix<int>(entity_data.NumberOfRows, entity_data.NumberOfRows);

            // go over all (other) entities
            for (int row_id = 0; row_id < transpose.NumberOfRows; row_id++)
            {
                var row = ((IBooleanMatrix) transpose).GetEntriesByRow(row_id);

                for (int i = 0; i < row.Count; i++)
                {
                    int x = row[i];

                    for (int j = i + 1; j < row.Count; j++)
                    {
                        int y = row[j];

                        if (x < y)
                            overlap[x, y]++;
                        else
                            overlap[y, x]++;
                    }
                }
            }

            // the diagonal of the correlation matrix
            for (int i = 0; i < num_entities; i++)
                this[i, i] = 1;

            // compute cosine
            foreach (var index_pair in overlap.NonEmptyEntryIDs)
            {
                int x = index_pair.First;
                int y = index_pair.Second;

                this[x, y] = (float) (overlap[x, y] / Math.Sqrt(entity_data.NumEntriesByRow(x) * entity_data.NumEntriesByRow(y) ));
            }
        }

Usage Example

		[Test()] public void TestCreate()
		{
			var sparse_boolean_matrix = new SparseBooleanMatrix();
			sparse_boolean_matrix[0, 1] = true;
			sparse_boolean_matrix[0, 4] = true;
			sparse_boolean_matrix[1, 0] = true;
			sparse_boolean_matrix[1, 2] = true;
			sparse_boolean_matrix[1, 4] = true;
			sparse_boolean_matrix[3, 1] = true;
			sparse_boolean_matrix[3, 3] = true;
			sparse_boolean_matrix[3, 4] = true;

			var correlation_matrix = new BinaryCosine(sparse_boolean_matrix.NumberOfRows);
			correlation_matrix.ComputeCorrelations(sparse_boolean_matrix);
			
			Assert.AreEqual(4, correlation_matrix.NumberOfRows);
			Assert.IsTrue(correlation_matrix.IsSymmetric);
			
			Assert.AreEqual(1 / Math.Sqrt(6), correlation_matrix[0, 1], DELTA);
			Assert.AreEqual(1 / Math.Sqrt(6), correlation_matrix[1, 0], DELTA);
			Assert.AreEqual(1 / 3d, correlation_matrix[1, 3], DELTA);

			Assert.AreEqual(0f, correlation_matrix[2, 0]);
			Assert.AreEqual(0f, correlation_matrix[2, 1]);
			Assert.AreEqual(1f, correlation_matrix[2, 2]);
			Assert.AreEqual(0f, correlation_matrix[2, 3]);

			Assert.AreEqual(0f, correlation_matrix[0, 2]);
			Assert.AreEqual(0f, correlation_matrix[1, 2]);
			Assert.AreEqual(0f, correlation_matrix[3, 2]);
		}
All Usage Examples Of MyMediaLite.Correlation.BinaryCosine::ComputeCorrelations