Пример #1
0
 public VantagePointTree(IDistance <T> distance, IEnumerable <T> items) : base()
 {
     root          = null;
     this.distance = distance;
     this.items    = items.Select(x => x).ToList();
     root          = BuildFromPoints(0, this.items.Count);
 }
Пример #2
0
        /// <summary>
        ///   Creates a new vantage-point tree from the given points.
        /// </summary>
        ///
        /// <param name="points">The points to be added to the tree.</param>
        /// <param name="distance">The distance function to use.</param>
        /// <param name="inPlace">Whether to perform operations in place, altering the
        ///   original array of points instead of creating an extra copy.</param>
        ///
        /// <returns>A <see cref="VPTree"/> populated with the given data points.</returns>
        ///
        public static VPTree FromData(double[][] points, IDistance distance, bool inPlace = false)
        {
            var tree = new VPTree(distance);

            tree.Root = tree.buildFromPoints(points, 0, points.Length, inPlace);
            return(tree);
        }
Пример #3
0
        internal static void CheckArgs(int k, TInput[] inputs, int[] outputs, IDistance <TInput> distance, double[] weights)
        {
            if (weights != null)
            {
                throw new NotSupportedException("Weights are not supported yet. If are interested in the feature, please submit a request to the proejct's issue tracker.");
            }

            if (inputs == null)
            {
                throw new ArgumentNullException("inputs");
            }

            if (outputs == null)
            {
                throw new ArgumentNullException("inputs");
            }

            if (inputs.Length != outputs.Length)
            {
                throw new DimensionMismatchException("outputs",
                                                     "The number of input vectors should match the number of corresponding output labels");
            }

            if (k <= 0 || k > inputs.Length)
            {
                throw new ArgumentOutOfRangeException("k", "The value for k should be greater than zero and less than total number of input points.");
            }

            if (distance == null)
            {
                throw new ArgumentNullException("distance");
            }
        }
Пример #4
0
        private Dictionary <int, double> GetDistance(IDistance distance)
        {
            // userId with simularity
            Dictionary <int, double> userDis = new Dictionary <int, double>();

            // Getting other user with the same items rated
            foreach (KeyValuePair <int, Dictionary <int, double> > item in _dict)
            {
                int curUser = item.Key;

                List <double> p = new List <double>();
                List <double> q = new List <double>();
                foreach (KeyValuePair <int, double> curArticle in item.Value)
                {
                    if (curUserItems.ContainsKey(curArticle.Key))
                    {
                        p.Add(curUserItems[curArticle.Key]);
                        q.Add(curArticle.Value);
                    }
                }
                // calculate the simularity
                double dis = distance.Calculate(p.ToArray(), q.ToArray());

                userDis.Add(item.Key, dis);
            }
            Console.WriteLine($"Interface = {distance.GetType()} Distance of items:");
            Ranking(userDis);
            return(userDis);
        }
Пример #5
0
        private void init(double[][] inputs, int[] outputs, IDistance <double[]> distance)
        {
            this.distance = distance;

            int symbols   = outputs.Max() + 1;
            int dimension = inputs[0].Length;

            int[] counts = new int[symbols];

            means = new double[symbols][];
            for (int i = 0; i < means.Length; i++)
            {
                means[i] = new double[dimension];
            }


            for (int i = 0; i < inputs.Length; i++)
            {
                int      k    = outputs[i];
                double[] mean = means[k];
                for (int j = 0; j < mean.Length; j++)
                {
                    mean[j] += inputs[i][j];
                }
                counts[k]++;
            }

            for (int i = 0; i < means.Length; i++)
            {
                for (int j = 0; j < means[i].Length; j++)
                {
                    means[i][j] /= counts[i];
                }
            }
        }
Пример #6
0
 /// <summary>
 ///   Initializes a new instance of VoronoiIteration algorithm
 /// </summary>
 ///
 /// <param name="k">The number of clusters to divide input data.</param>
 /// <param name="distance">The distance function to use. Default is to
 /// use the <see cref="Accord.Math.Distance.Manhattan(double[], double[])"/> distance.</param>
 ///
 public VoronoiIteration(int k, IDistance <T[]> distance)
     : base(k, distance)
 {
     Initialization = Seeding.Uniform;
     Tolerance      = 1e-5;
     MaxIterations  = 100;
 }
 public StressMajorizationLayout(int numPoints, IDistance<int> distFunc)
 {
     Utils.ThrowException(numPoints <= 0 ? new ArgumentOutOfRangeException("numPoints") : null);
     Utils.ThrowException(distFunc == null ? new ArgumentNullException("distFunc") : null);
     mNumPoints = numPoints;
     mDistFunc = distFunc;
 }
Пример #8
0
        internal static void CheckArgs(int k, TInput[] inputs, int[] outputs, IDistance <TInput> distance, double[] weights)
        {
            if (inputs == null)
            {
                throw new ArgumentNullException("inputs");
            }

            if (outputs == null)
            {
                throw new ArgumentNullException("inputs");
            }

            if (inputs.Length != outputs.Length)
            {
                throw new DimensionMismatchException("outputs",
                                                     "The number of input vectors should match the number of corresponding output labels");
            }

            if (k <= 0 || k > inputs.Length)
            {
                throw new ArgumentOutOfRangeException("k", "The value for k should be greater than zero and less than total number of input points.");
            }

            if (distance == null)
            {
                throw new ArgumentNullException("distance");
            }
        }
Пример #9
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="ClusterCollection{T,U}"/> class.
 /// </summary>
 ///
 /// <param name="k">The number of clusters K.</param>
 /// <param name="distance">The distance metric to use.</param>
 ///
 public KModesClusterCollection(int k, IDistance <T[], T[]> distance)
     : base(k, distance)
 {
     for (int i = 0; i < k; i++)
     {
         Clusters[i] = new KModesCluster(this, i);
     }
 }
Пример #10
0
        /// <summary>
        /// Find the converter functor from source to target
        /// </summary>
        /// <param name="source">Dimension to convert from</param>
        /// <param name="target">Dimension to concert to</param>
        /// <param name="power"></param>
        /// <returns>A functor to convert from source into target</returns>
        public static Func <double, double> From(IDimension source, IDistance target, int power)
        {
            var dispatcher = new VisitorDispatcher("Convert");

            var result = dispatcher.Accept(source.GetType(), new DistanceConverter(), source, target, power);

            return((Func <double, double>)result);
        }
Пример #11
0
 public KNearestNeighbors(int k, int classes, TInput[] inputs, int[] outputs, IDistance <TInput> distance)
     : this(k, inputs, outputs, distance)
 {
     if (classes != NumberOfOutputs)
     {
         throw new ArgumentException("classes");
     }
 }
Пример #12
0
        /// <summary>
        /// Find the converter functor from source to target
        /// </summary>
        /// <param name="source">Dimension to convert from</param>
        /// <param name="target">Dimension to concert to</param>
        /// <param name="power"></param>
        /// <returns>A functor to convert from source into target</returns>
        public static Func<double, double> From(IDimension source, IDistance target, int power)
        {
            var dispatcher = new VisitorDispatcher("Convert");

            var result = dispatcher.Accept(source.GetType(), new DistanceConverter(), source, target, power);

            return (Func<double, double>)result;
        }
Пример #13
0
 public KnnClassificationModel(BaseVector[] x, int[][] y, int ngroups, int k, IDistance distance)
 {
     this.x        = x;
     this.y        = y;
     this.ngroups  = ngroups;
     this.k        = k;
     this.distance = distance;
 }
Пример #14
0
 public static TSNEState CreateState(T[] data, IDistance <T> distance, IRandom random,
                                     int newDimensions    = 2, double perplexity = 25, double theta      = 0,
                                     int stopLyingIter    = 0, int momSwitchIter = 0, double momentum    = .5,
                                     double finalMomentum = .8, double eta       = 10.0, bool randomInit = true
                                     )
 {
     return(new TSNEState(data, distance, random, newDimensions, perplexity, theta, stopLyingIter, momSwitchIter, momentum, finalMomentum, eta, randomInit));
 }
Пример #15
0
        // works only for small distances, within miles. For rare cases when we have both heading and bearing, but want to move in the "heading" direction.
        public void translateToDirection(IDirection dir, IDistance by)
        {
            double range = by.Meters;
            double angle = (double)dir.heading; // degrees

            m_X += toDegreesX(range * Math.Sin(angle * Math.PI / 180.0d));
            m_Y += toDegreesY(range * Math.Cos(angle * Math.PI / 180.0d));
        }
 internal override void Reset()
 {
     _top    = Percent.Hundred;
     _right  = Percent.Hundred;
     _bottom = Percent.Hundred;
     _left   = Percent.Hundred;
     _fill   = false;
 }
Пример #17
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="KMeansClusterCollection"/> class.
 /// </summary>
 ///
 /// <param name="k">The number of clusters K.</param>
 /// <param name="distance">The distance metric to consider.</param>
 ///
 public ClusterCollection(int k, IDistance <TData, TCentroids> distance)
 {
     // To store centroids of the clusters
     this.proportions = new double[k];
     this.centroids   = new TCentroids[k];
     this.clusters    = new TCluster[k];
     this.Distance    = distance;
 }
Пример #18
0
        public override RegressionModel Train(BaseVector[] x, int[] nominal, double[] y, Parameters param, int ntheads, Action <double> reportProgress)
        {
            x = ClassificationMethod.ToOneHotEncoding(x, nominal);
            int       k        = param.GetParam <int>("Number of neighbours").Value;
            IDistance distance = Distances.GetDistanceFunction(param);

            return(new KnnRegressionModel(x, y, k, distance));
        }
Пример #19
0
        /// <summary>
        ///   Creates a new <see cref="KNearestNeighbors"/>.
        /// </summary>
        ///
        /// <param name="k">The number of nearest neighbors to be used in the decision.</param>
        ///
        /// <param name="inputs">The input data points.</param>
        /// <param name="outputs">The associated labels for the input points.</param>
        /// <param name="distance">The distance measure to use in the decision.</param>
        ///
        public KNearestNeighbors(int k, T[] inputs, int[] outputs, IDistance <T> distance)
        {
            checkArgs(k, null, inputs, outputs, distance);

            int classCount = outputs.Distinct().Count();

            initialize(k, classCount, inputs, outputs, distance);
        }
Пример #20
0
 public Sillhouette(List <Centroid> kmeansCentroids, List <Point> data, IDistance distanceType)
 {
     KmeansCentroids   = kmeansCentroids;
     Data              = data;
     this.distanceType = distanceType;
     DistanceMatrix(data);
     SilhouetteCalculation(KmeansCentroids);
 }
Пример #21
0
        public override ClassificationModel Train(BaseVector[] x, int[][] y, int ngroups, Parameters param, int nthreads,
                                                  Action <double> reportProgress)
        {
            int       k        = param.GetParam <int>("Number of neighbours").Value;
            IDistance distance = Distances.GetDistanceFunction(param);

            return(new KnnClassificationModel(x, y, ngroups, k, distance));
        }
Пример #22
0
        public int[] Generate(Matrix x, int k, IDistance metric)
        {
            if (metric == null)
                metric = new EuclidianDistance();

            X = x;

            var means = InitializeRandom(X, k);
            int[] assignments = new int[X.Rows];

            for (int i = 0; i < 100; i++)
            {
                // Assignment step
                Parallel.For(0, X.Rows, j =>
                {
                    var min_index = -1;
                    var min = double.MaxValue;
                    for (int m = 0; m < means.Rows; m++)
                    {
                        var d = metric.Compute(X[j], means[m]);
                        if (d < min)
                        {
                            min = d;
                            min_index = m;
                        }
                    }

                    assignments[j] = min_index;
                });

                // Update Step
                Matrix new_means = Matrix.Zeros(k, X.Cols);
                Vector sum = Vector.Zeros(k);

                // Part 1: Sum up assignments
                for (int j = 0; j < X.Rows; j++)
                {
                    int a = assignments[j];
                    new_means[a] += X[j, VectorType.Row];
                    sum[a]++;
                }

                // Part 2: Divide by counts
                for (int j = 0; j < new_means.Rows; j++)
                    new_means[j] /= sum[j];

                // Part 3: Check for convergence
                // find norm of the difference
                if ((means - new_means).Norm() < .00001)
                    break;

                means = new_means;
            }

            Centers = means;

            return assignments;
        }
Пример #23
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="KMeansClusterCollection"/> class.
 /// </summary>
 ///
 /// <param name="k">The number of clusters K.</param>
 /// <param name="distance">The distance metric to consider.</param>
 ///
 public KMeansClusterCollection(int k, IDistance <double[]> distance)
     : base(k, distance)
 {
     covariances = new double[k][][];
     for (int i = 0; i < k; i++)
     {
         Clusters[i] = new KMeansCluster(this, i);
     }
 }
        public float Convert(IDistance distance)
        {
            if (distance == default)
            {
                throw new ArgumentNullException(nameof(distance));
            }

            return(distance.GetHashCode());
        }
Пример #25
0
 public void Setup()
 {
     _uut         = new Course();
     _newTracks   = new List <ITrackObject>();
     _velocity    = Substitute.For <IVelocity>();
     _separation  = Substitute.For <ISeparation>();
     _distance    = Substitute.For <IDistance>();
     _listHandler = new ListHandler(_velocity, _uut, _separation, _distance);
 }
Пример #26
0
        public IActionResult ShowResult(KMeansCreateVM model)
        {
            var       data     = _fileService.GetData(model.UploadFile, model.DataType);
            IDistance distance = DistanceFactory.GetDistance(model.DistanceType);
            var       result   = _kMeans.Clustering(data, distance, model.ClustersCount);

            ViewBag.Centroids = result.Centroid;
            return(View(result.Result));
        }
Пример #27
0
        public IActionResult ShowResult(HierarchicalCreateVM model)
        {
            var              data            = _fileService.GetData(model.UploadFile, model.DataType);
            IDistance        distance        = DistanceFactory.GetDistance(model.DistanceType);
            IClusterDistance clusterDistance = ClusterDistanceFactory.GetClusterDistance(model.ClusterUnionType);
            var              result          = _service.Clustering(data, distance, clusterDistance, model.CountOfUnionsInStep);

            return(View(result));
        }
Пример #28
0
            /// <summary>
            ///   Initializes a new instance of the <see cref="KMeansClusterCollection"/> class.
            /// </summary>
            ///
            /// <param name="collection">The collection that contains this instance as a field.</param>
            /// <param name="k">The number of clusters K.</param>
            /// <param name="distance">The distance metric to consider.</param>
            ///
            public ClusterCollection(TCollection collection, int k, IDistance <TData, TCentroid> distance)
                : base(collection, k)
            {
                this.distance  = distance;
                this.centroids = new TCentroid[k];

                collection.NumberOfOutputs = k;
                collection.NumberOfClasses = k;
            }
Пример #29
0
        protected static String SerializePeriodic(IDistance t, IDistance r, IDistance b, IDistance l)
        {
            var top    = t.ToCss();
            var right  = r.ToCss();
            var bottom = b.ToCss();
            var left   = l.ToCss();

            return(SerializePeriodic(top, right, bottom, left));
        }
        public float Convert(IDistance distance)
        {
            if (distance == default)
            {
                throw new ArgumentNullException(nameof(distance));
            }

            return(distance.Maximum * distance.Minimum * 0.5f - 1);
        }
Пример #31
0
        public decimal CalculateRacePoints(IDistance distance, int classificationWeight, TimeSpan classificationPrecision, IRaceResult result, IRaceTime time)
        {
            if (!CanCalculateRacePoints(distance, classificationWeight, classificationPrecision, result, time))
            {
                throw new NotSupportedException();
            }

            return(CalculatePoints(Length(distance), classificationWeight, classificationPrecision, time.Time));
        }
        public Lane ExpectedLane(IDistance distance, int lap, Lane startLane, IEnumerable <IVenueSegment> passedLapSegments)
        {
            if (passedLapSegments.Any(s => s.Flags.HasFlag(VenueSegmentFlags.LaneSwitch)))
            {
                lap++;
            }

            return(ExpectedLane(distance, lap, startLane));
        }
Пример #33
0
        public float Convert(IDistance distance)
        {
            if (distance == default)
            {
                throw new ArgumentNullException(nameof(distance));
            }

            return(distance.Hash / 2147483648.0f);
        }
        /// <summary>
        /// Performs a hierarchical clustering on the the given data matrix.
        /// </summary>
        /// <param name="data">Data matrix that is going to be clustered.</param>
        /// <param name="access">Specifies whether rows or columns are to be clustered</param>
        /// <param name="distance">Defines the distance between two elements</param>
        /// <param name="linkage">Specifies the linkage for the clustering.</param>
        /// <param name="preserveOrder"></param>
        /// <param name="periodic"></param>
        /// <param name="nthreads"></param>
        /// <param name="progress"></param>
        /// <returns>An array of cluster nodes defining the resulting tree.</returns>
        public HierarchicalClusterNode[] TreeCluster(MatrixIndexer data, MatrixAccess access, IDistance distance,
			HierarchicalClusterLinkage linkage, bool preserveOrder, bool periodic, int nthreads, Action<int> progress)
        {
            int nelements = (access == MatrixAccess.Rows) ? data.RowCount : data.ColumnCount;
            if (nelements < 2){
                return new HierarchicalClusterNode[0];
            }
            float[,] distMatrix = DistanceMatrix(data, distance, access);
            return TreeCluster(distMatrix, linkage, preserveOrder, periodic, nthreads, progress);
        }
Пример #35
0
        public Cluster Generate(Descriptor descriptor, IEnumerable<object> examples, int k, IDistance metric = null)
        {
            var data = examples.ToArray();
            Descriptor = descriptor;
            Matrix X = Descriptor.Convert(examples).ToMatrix();

            var assignments = Generate(X, k, metric);

            return GenerateClustering(X, assignments, data);
        }
Пример #36
0
 public KnnRegressionModel(IList<BaseVector> x, IList<float> y, int k, IDistance distance)
 {
     List<int> v = new List<int>();
     for (int i = 0; i < y.Count; i++){
         if (!double.IsNaN(y[i]) && !double.IsInfinity(y[i])){
             v.Add(i);
         }
     }
     this.x = ArrayUtils.SubArray(x, v);
     this.y = ArrayUtils.SubArray(y, v);
     this.k = k;
     this.distance = distance;
 }
 /// <summary>
 /// Create distance matrix from <see cref="IDistance"/>.
 /// </summary>
 /// <param name="data"></param>
 /// <param name="distance"></param>
 public GenericDistanceMatrix(MatrixIndexer data, IDistance distance)
 {
     N = data.RowCount;
     _distances = new double[N * (N - 1) / 2];
     int k = 0;
     for (int i = 0; i < N; i++)
     {
         var xi = data.GetRow(i);
         for (int j = i+1; j < N; j++)
         {
             _distances[k++] = distance.Get(xi, data.GetRow(j));
         }
     }
 }
        public GravitationalClustering(double radius, double step, int iterations, IDistance func)
        {
            Trace.Assert(radius > 0);
            Trace.Assert(step > 0);
            Trace.Assert(iterations >= 1);

            Trace.Assert(func != null);

            this.Iterations = iterations;
            this.Radius = radius;
            this.PercentStep = step;

            this.Distance = func;

            this.planets = new List<Planet>(15);
        }
Пример #39
0
        /// <summary>
        /// Convert an area unit to Imperial
        /// </summary>
        /// <param name="unit">Instance of the measure</param>
        /// <param name="dimension"> New Dimension to convert </param>
        /// <returns> A new measure with the conversion </returns>
        public static IUnit<IArea> In(this IUnit<IArea> unit, IDistance dimension)
        {
            Debug.WriteLine("**** converting area to " + dimension);

            var area = (AreaUnit) unit;

            var converter = DistanceConverter.From(area.Distance.Dimension, dimension, 2);

            if (converter == null)
            {
                var message = string.Format("I don't know how to convert area {0} to {1}", unit, dimension);

                throw new InvalidOperationException(message);
            }

            var quantity = converter(unit.Quantity);

            return new AreaUnit(new DistanceUnit(quantity, dimension));
        }
Пример #40
0
        /// <summary>Generates.</summary>
        /// <param name="descriptor">The descriptor.</param>
        /// <param name="examples">The examples.</param>
        /// <param name="k">The int to process.</param>
        /// <param name="metric">(Optional) the metric.</param>
        /// <returns>An int[].</returns>
        public Cluster Generate(Descriptor descriptor, IEnumerable<object> examples, int k, IDistance metric = null)
        {
            var data = examples.ToArray();
            this.Descriptor = descriptor;
            this.X = this.Descriptor.Convert(data).ToMatrix();

            // generate assignments
            var assignments = this.Generate(this.X, k, metric);

            // begin packing objects into clusters
            var objects = new List<object>[k];
            for (var i = 0; i < assignments.Length; i++)
            {
                var a = assignments[i];
                if (objects[a] == null)
                {
                    objects[a] = new List<object>();
                }

                objects[a].Add(data[i]);
            }

            // create clusters
            var clusters = new List<Cluster>();
            for (var i = 0; i < k; i++)
            {
                if (!this.Centers[i].IsNaN())
                {
                    // check for degenerate clusters
                    clusters.Add(
                        new Cluster
                            {
                                Id = i + 1, Center = this.Centers[i], Members = objects[i].ToArray(),
                                Children = new Cluster[] { }
                            });
                }
            }

            // return single cluster with K children
            return new Cluster { Id = 0, Center = this.X.Mean(VectorType.Row), Children = clusters.ToArray() };
        }
Пример #41
0
 /// <summary>Constructor.</summary>
 /// <param name="metric">The metric.</param>
 public CentroidLinker(IDistance metric)
 {
     _metric = metric;
 }
 public When_double_in_dimension_extension_method_is_called(IDistance expected,
                                                            Func<double, IUnit<IDistance>> generator)
 {
     this._expectedDimension = expected;
     this._generator = generator;
 }
Пример #43
0
 public DistanceTest(IDistance d)
 {
     this.d = d;
 }
Пример #44
0
 public BasicClassifier(IDistance distance)
 {
     this.distance = distance;
 }
Пример #45
0
        // works only for small distances, within miles. For general case - when bearing is missing, or when we need to move towards bearing.
        public void translate(IDirection dir, IDistance by)
		{
            double range = by.Meters;
            double angle = (double)dir.heading; // degrees

            if (dir.bearing.HasValue)
            {
                // if both heading and bearing are supplied, then heading represents robot direction, and bearing - absolute direction to the object.
                // we are interested in translating in the "bearing" direction in this case, it is done to the objects relative to the robot.
                angle = (double)dir.bearing;
            }

            m_X += toDegreesX(new Distance(range * Math.Sin(angle * Math.PI / 180.0d)));
            m_Y += toDegreesY(new Distance(range * Math.Cos(angle * Math.PI / 180.0d)));
		}
Пример #46
0
        // works only for small distances, within miles. For rare cases when we have both heading and bearing, but want to move in the "heading" direction.
        public void translateToDirection(IDirection dir, IDistance by)
		{
            double range = by.Meters;
            double angle = (double)dir.heading; // degrees

            m_X += toDegreesX(new Distance(range * Math.Sin(angle * Math.PI / 180.0d)));
            m_Y += toDegreesY(new Distance(range * Math.Cos(angle * Math.PI / 180.0d)));
		}
Пример #47
0
 public SingleLinker(IDistance distanceMetric)
 {
     _distanceMetric = distanceMetric;
 }
 public When_integer_in_dimension_extension_method_is_called(IDistance dimension, Func<int, IUnit<IDistance>> functor)
 {
     this._expectedDimension = dimension;
     this._generator = functor;
 }
Пример #49
0
        // converts distance along the latitude line (X) into degrees
        public double toDegreesX(IDistance d)
        {
            // horizontal degrees are shorter in meters as we go up the latitude:
            double latitudeFactor = Math.Cos(this.Lat * Math.PI / 180.0d);

            return d.Meters / Distance.METERS_PER_DEGREE / latitudeFactor;
        }
Пример #50
0
        // works only for small distances, within miles.
        public void translate(IDistance byX, IDistance byY)
		{
            m_X += toDegreesX(byX);
            m_Y += toDegreesY(byY);
		}
Пример #51
0
 public CentroidLinker(IDistance distanceMetric)
 {
     _distanceMetric = distanceMetric;
 }
Пример #52
0
 public AverageLinker(IDistance distanceMetric)
 {
     _distanceMetric = distanceMetric;
 }
Пример #53
0
 // converts distance along the longitude line (Y) into degrees
 public double toDegreesY(IDistance d)
 {
     // vertical degrees are the same always:
     return d.Meters / Distance.METERS_PER_DEGREE;
 }
Пример #54
0
 /// <summary>Constructor.</summary>
 /// <param name="metric">The metric.</param>
 public SingleLinker(IDistance metric)
 {
     _metric = metric;
 }
Пример #55
0
        public int[] Generate(IEnumerable<object> examples, int k, IDistance metric = null)
        {
            #region Sanity Checks
            if (examples == null)
                throw new InvalidOperationException("Cannot generate a model will no data!");

            if (k < 2)
                throw new InvalidOperationException("Can only cluter with k > 1");

            if (Descriptor == null)
                throw new InvalidOperationException("Invalid Description!");

            int count = examples.Count();
            if (k >= count)
                throw new InvalidOperationException(
                    string.Format("Cannot cluster {0} items {1} different ways!", count, k));
            #endregion

            Matrix X = Descriptor.Convert(examples).ToMatrix();
            var data = Generate(X, k, metric);
            return data;
        }
 private static float[,] DistanceMatrix(MatrixIndexer data, IDistance distance, MatrixAccess access)
 {
     int nrows = data.RowCount;
     int ncols = data.ColumnCount;
     int nelements = (access == MatrixAccess.Rows) ? nrows : ncols;
     float[,] result = new float[nelements, nelements];
     for (int i = 0; i < nelements; i++){
         for (int j = 0; j < i; j++){
             result[i, j] = (float) distance.Get(GetVector(data, i, access), GetVector(data, j, access));
         }
     }
     return result;
 }
Пример #57
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="AverageLinker" /> class. Constructor.
 /// </summary>
 /// <param name="metric">
 ///     The metric.
 /// </param>
 public AverageLinker(IDistance metric)
 {
     this._metric = metric;
 }
        public HierarchicalClusterNode[] TreeClusterKmeans(MatrixIndexer data, MatrixAccess access, IDistance distance,
			HierarchicalClusterLinkage linkage, bool preserveOrder, bool periodic, int nthreads, int nmeans, int restarts,
			int maxIter, Action<int> progress)
        {
            int nelements = (access == MatrixAccess.Rows) ? data.RowCount : data.ColumnCount;
            if (nelements <= nmeans){
                return TreeCluster(data, access, distance, linkage, preserveOrder, periodic, nthreads, progress);
            }
            float[,] c;
            int[] inds;
            if (access == MatrixAccess.Rows){
                KmeansClustering.GenerateClusters(data, nmeans, maxIter, restarts, progress, out c, out inds);
            } else{
                KmeansClustering.GenerateClusters(data.Transpose(), nmeans, maxIter, restarts, progress, out c, out inds);
            }
            float[,] distMatrix = DistanceMatrix(new FloatMatrixIndexer(c), distance, MatrixAccess.Rows);
            HierarchicalClusterNode[] nodes = TreeCluster(distMatrix, linkage, preserveOrder, periodic, nthreads, progress);
            Dictionary<int, int[]> clusters;
            Dictionary<int, int> singletons;
            RearrangeClusters(inds, c.GetLength(0), out clusters, out singletons);
            HierarchicalClusterNode[] newNodes = new HierarchicalClusterNode[nelements - 1];
            int fill = nelements - nmeans;
            Array.Copy(nodes, 0, newNodes, fill, nodes.Length);
            int pos = 0;
            for (int i = fill; i < newNodes.Length; i++){
                HierarchicalClusterNode node = newNodes[i];
                if (node.left < 0){
                    node.left -= fill;
                } else if (singletons.ContainsKey(node.left)){
                    node.left = singletons[node.left];
                } else{
                    if (clusters.ContainsKey(node.left)){
                        HierarchicalClusterNode[] branch = FillTerminalBranch(clusters[node.left], pos);
                        Array.Copy(branch, 0, newNodes, pos, branch.Length);
                        pos += branch.Length;
                        node.left = -pos;
                    }
                }
                if (node.right < 0){
                    node.right -= fill;
                } else if (singletons.ContainsKey(node.right)){
                    node.right = singletons[node.right];
                } else{
                    if (clusters.ContainsKey(node.right)){
                        HierarchicalClusterNode[] branch = FillTerminalBranch(clusters[node.right], pos);
                        Array.Copy(branch, 0, newNodes, pos, branch.Length);
                        pos += branch.Length;
                        node.right = -pos;
                    }
                }
            }
            return newNodes;
        }
Пример #59
0
 /// <summary>Constructor.</summary>
 /// <param name="metric">The metric.</param>
 public CompleteLinker(IDistance metric)
 {
     _metric = metric;
 }
Пример #60
0
 public BasicClassifier(IDistance distance)
 {
     _distance = distance;
 }