CosineDistance extends FastDistance { @Override public void updateLabel(FastDistanceData data) { if (data instanceof FastDistanceVectorData) { FastDistanceVectorData vectorData = (FastDistanceVectorData)data; double vectorLabel = Math.sqrt(MatVecOp.dot(vectorData.vector, vectorData.vector)); if(vectorLabel > 0){ vectorData.vector.scaleEqual(1.0 / vectorLabel); } } else { FastDistanceMatrixData matrix = (FastDistanceMatrixData)data; int vectorSize = matrix.vectors.numRows(); double[] matrixData = matrix.vectors.getData(); int cnt = 0; while (cnt < matrixData.length) { int endIndex = cnt + vectorSize; double vectorLabel = 0.; while (cnt < endIndex) { vectorLabel += matrixData[cnt] * matrixData[cnt]; cnt++; } vectorLabel = Math.sqrt(vectorLabel); if(vectorLabel > 0) { BLAS.scal(1.0 / vectorLabel, matrixData, cnt - vectorSize, vectorSize); } } } }  @Override double calc(double[] array1, double[] array2); @Override double calc(Vector vec1, Vector vec2); @Override void updateLabel(FastDistanceData data);  }
@Test public void testUpdateLabel() { Vector vec = distance.prepareVectorData(Tuple2.of(denseVector1, null)).getVector(); Assert.assertEquals(vec.normL2(), 1.0, 0.01); FastDistanceMatrixData matrixData = initMatrixData(); DenseMatrix matrix = matrixData.getVectors(); for (int i = 0; i < matrix.numCols(); i++) { double[] data = matrix.getColumn(i); Assert.assertEquals(Math.sqrt(BLAS.dot(data, data)), 1.0, 0.01); } }