/// <summary> /// Compute L2-norm. L2-norm computation doesn't subtract the mean from the source values. /// However, we substract the mean here in case subMean is true (if subMean is false, mean is zero). /// </summary> private static Float L2Norm(Float[] values, int count, Float mean = 0) { if (count == 0) { return(0); } return(MathUtils.Sqrt(SseUtils.SumSq(mean, values, 0, count))); }
/// <summary> /// Compute Standard Deviation. /// We have two overloads of StdDev instead of one with <see cref="Nullable{Float}"/> mean for perf reasons. /// </summary> private static Float StdDev(Float[] values, int count, int length, Float mean) { Contracts.Assert(0 <= count && count <= length); if (count == 0) { return(0); } Float sumSq = 0; if (count != length && mean != 0) { // Sparse representation. Float meanSq = mean * mean; sumSq = (length - count) * meanSq; } sumSq += SseUtils.SumSq(mean, values, 0, count); return(MathUtils.Sqrt(sumSq / length)); }
/// <summary> /// Compute Standard Deviation. In case of both subMean and useStd are true, we technically need to compute variance /// based on centered values (i.e. after subtracting the mean). But since the centered /// values mean is approximately zero, we can use variance of non-centered values. /// </summary> private static Float StdDev(Float[] values, int count, int length) { Contracts.Assert(0 <= count && count <= length); if (count == 0) { return(0); } // We need a mean to compute variance. Float tmpMean = SseUtils.Sum(values, 0, count) / length; Float sumSq = 0; if (count != length && tmpMean != 0) { // Sparse representation. Float meanSq = tmpMean * tmpMean; sumSq = (length - count) * meanSq; } sumSq += SseUtils.SumSq(tmpMean, values, 0, count); return(MathUtils.Sqrt(sumSq / length)); }
private static Float L2DistSquaredHalfSparse(Float[] valuesA, int lengthA, Float[] valuesB, int[] indicesB, int countB) { Contracts.AssertValueOrNull(valuesA); Contracts.AssertValueOrNull(valuesB); Contracts.AssertValueOrNull(indicesB); Contracts.Assert(0 <= lengthA && lengthA <= Utils.Size(valuesA)); Contracts.Assert(0 <= countB && countB <= Utils.Size(indicesB)); Contracts.Assert(countB <= Utils.Size(valuesB)); var normA = SseUtils.SumSq(valuesA, 0, lengthA); if (countB == 0) { return(normA); } var normB = SseUtils.SumSq(valuesB, 0, countB); var dotP = SseUtils.DotProductSparse(valuesA, valuesB, indicesB, countB); var res = normA + normB - 2 * dotP; return(res < 0 ? 0 : res); }
public static float SumSq(float[] src, int offset, int count) => SseUtils.SumSq(src, offset, count);
/// <summary> /// Returns the L2 norm of the vector (sum of squares of the components). /// </summary> public static Float Norm(Float[] a) { return(MathUtils.Sqrt(SseUtils.SumSq(a, a.Length))); }