- Timestamp:
- 11/20/17 15:29:53 (6 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/Weighted TSNE/3.4/TSNE/Distances/CosineDistance.cs
r15234 r15479 22 22 using System; 23 23 using System.Collections.Generic; 24 using System.Linq;25 24 using HeuristicLab.Common; 26 25 using HeuristicLab.Core; … … 28 27 29 28 namespace HeuristicLab.Algorithms.DataAnalysis { 30 31 29 /// <summary> 32 30 /// The angular distance as defined as a normalized distance measure dependent on the angle between two vectors. … … 35 33 [Item("CosineDistance", "The angular distance as defined as a normalized distance measure dependent on the angle between two vectors.")] 36 34 public class CosineDistance : DistanceBase<IEnumerable<double>> { 37 38 35 #region HLConstructors & Cloning 39 36 [StorableConstructor] … … 48 45 49 46 #region statics 50 public static double GetDistance(IReadOnlyList<double> point1, IReadOnlyList<double> point2) { 51 if (point1.Count != point2.Count) throw new ArgumentException("Cosine distance not defined on vectors of different length"); 52 var innerprod = 0.0; 53 var length1 = 0.0; 54 var length2 = 0.0; 55 56 for (var i = 0; i < point1.Count; i++) { 57 double d1 = point1[i], d2 = point2[i]; 58 innerprod += d1 * d2; 59 length1 += d1 * d1; 60 length2 += d2 * d2; 47 public static double GetDistance(IEnumerable<double> point1, IEnumerable<double> point2) { 48 using (IEnumerator<double> p1Enum = point1.GetEnumerator(), p2Enum = point2.GetEnumerator()) { 49 var innerprod = 0.0; 50 var length1 = 0.0; 51 var length2 = 0.0; 52 var p1Next = p1Enum.MoveNext(); 53 var p2Next = p2Enum.MoveNext(); 54 while (p1Next && p2Next) { 55 double d1 = p1Enum.Current, d2 = p2Enum.Current; 56 innerprod += d1 * d2; 57 length1 += d1 * d1; 58 length2 += d2 * d2; 59 p1Next = p1Enum.MoveNext(); 60 p2Next = p1Enum.MoveNext(); 61 } 62 var divisor = Math.Sqrt(length1 * length2); 63 if (divisor.IsAlmost(0)) throw new ArgumentException("Cosine distance is not defined on vectors of length 0"); 64 if (p2Next || p1Next) throw new ArgumentException("Cosine distance not defined on vectors of different length"); 65 return 1 - innerprod / divisor; 61 66 } 62 var l = Math.Sqrt(length1 * length2);63 if (l.IsAlmost(0)) throw new ArgumentException("Cosine distance is not defined on vectors of length 0");64 return 1 - innerprod / l;65 67 } 66 68 #endregion 67 69 public override double Get(IEnumerable<double> a, IEnumerable<double> b) { 68 return GetDistance(a .ToArray(), b.ToArray());70 return GetDistance(a, b); 69 71 } 70 72 }
Note: See TracChangeset
for help on using the changeset viewer.