Ejemplo n.º 1
0
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        double shift_coef = 1.0;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real = Load.load_numbers("../data/fm_test_real.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test = new RealFeatures(testdata_real);

        EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

        MultiquadricKernel kernel = new MultiquadricKernel(feats_train, feats_test, shift_coef, distance);

        double[,] km_train = kernel.get_kernel_matrix();
        kernel.init(feats_train, feats_test);
        double[,] km_test = kernel.get_kernel_matrix();

        foreach(double item in km_train) {
            Console.Write(item);
        }

        foreach(double item in km_test) {
            Console.Write(item);
        }

        modshogun.exit_shogun();
    }
 public void ReviewersThatHaveReviewedUniqueTitlesShouldNotBeSimilar()
 {
     var r1 = ReviewerBuilder.BuildReviewer1();
     var r2 = ReviewerBuilder.BuildAReviewerThatReviewedSomethingUnique();
     euclideanDistance = new EuclideanDistance(r1, r2);
     Assert.AreEqual(0, euclideanDistance.Score());
 }
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        int k = 3;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real = Load.load_numbers("../data/fm_test_real.dat");

        double[] trainlab = Load.load_labels("../data/label_train_multiclass.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test = new RealFeatures(testdata_real);
        EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

        MulticlassLabels labels = new MulticlassLabels(trainlab);

        KNN knn = new KNN(k, distance, labels);
        knn.train();
        double[] out_labels = MulticlassLabels.obtain_from_generic(knn.apply(feats_test)).get_labels();

        foreach(double item in out_labels) {
            Console.Write(item);
        }

        modshogun.exit_shogun();
    }
	public static void Main() {
		modshogun.init_shogun_with_defaults();

		double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
		double[,] testdata_real = Load.load_numbers("../data/fm_test_real.dat");

		RealFeatures feats_train = new RealFeatures(traindata_real);
		RealFeatures feats_test = new RealFeatures(testdata_real);

		EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);
		distance.set_disable_sqrt(true);

		double[,] dm_train = distance.get_distance_matrix();
		distance.init(feats_train, feats_test);
		double[,] dm_test = distance.get_distance_matrix();


		foreach(double item in dm_train) {
			Console.Write(item);
		}

		foreach(double item in dm_test) {
			Console.Write(item);
		}

	}
Ejemplo n.º 5
0
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        double degree = 1.0;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real = Load.load_numbers("../data/fm_test_real.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test = new RealFeatures(testdata_real);

        EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

        PowerKernel kernel = new PowerKernel(feats_train, feats_test, degree, distance);

        double[,] km_train = kernel.get_kernel_matrix();
        kernel.init(feats_train, feats_test);
        double[,] km_test = kernel.get_kernel_matrix();

        foreach (double item in km_train)
            Console.Write(item);

        foreach (double item in km_test)
            Console.Write(item);
    }
Ejemplo n.º 6
0
 public void PointsDistanceEuclidean()
 {
     Point p1 = new Point(10.0, 15.0);
     Point p2 = new Point(7.0, 19.0);
     IDistanceMetric metric = new EuclideanDistance();
     PointsDistance distance = new PointsDistance(metric);
     Assert.AreEqual(5.0, distance.CalculateDistance(p1, p2));
 }
Ejemplo n.º 7
0
        public Node(double[] weights, int x, int y)
        {
            Weights    = weights;
            Coordinate = new Coordinate(x, y);
            Count      = 0;

            _distanceMeasure = new EuclideanDistance();
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            IKMeans   _kMeans   = new KMeans();
            IDistance _distance = new EuclideanDistance();
            Random    rnd       = new Random(0);

            int objCount     = 10;
            int intrstsCount = 2;
            int clusterCount = 2;

            List <ClusterEntityDTO> clusters = new List <ClusterEntityDTO>();

            for (int i = 0; i < objCount; i++)
            {
                ClusterEntityDTO dTO = new ClusterEntityDTO
                {
                    Name = string.Format("{0:yyyyMMddHHmmss}", DateTime.Now),
                    Id   = i
                };
                List <Interest> interests = new List <Interest>();
                Console.WriteLine("___" + dTO.Name + "___");
                for (int j = 0; j < intrstsCount; j++)
                {
                    double   rand = Math.Round(rnd.NextDouble() * 200.0);
                    Interest intr = new Interest
                    {
                        Name    = string.Format("intr{0:yyyyMMddHHmmss}", DateTime.Now),
                        Weight  = rand,
                        Weight2 = rand
                    };
                    Console.WriteLine("--- " + intr.Weight + "---");
                    interests.Add(intr);
                }
                Console.WriteLine("-------------------------------");
                dTO.Interests = interests;
                clusters.Add(dTO);
            }
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("-----------------------------------");
            Console.WriteLine("-----------------------------------");
            var result = _kMeans.Clustering(clusters, _distance, clusterCount);

            for (int i = 0; i < objCount; i++)
            {
                Console.WriteLine("___" + result[i].Name + "___");
                for (int j = 0; j < intrstsCount; j++)
                {
                    Console.WriteLine("---" + result[i].Interests[j].Weight2 + "---");
                }

                if (i < objCount - 1 && result[i].CentroidId != result[i + 1].CentroidId)
                {
                    Console.WriteLine("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
                }
            }

            Console.ReadLine();
        }
Ejemplo n.º 9
0
        public void TestDistanceCalc()
        {
            ICalculateDistance calc = new EuclideanDistance();

            double[] pos1 = { 0.5, 1.0, 2.5 };
            double[] pos2 = { 0.1, 2.0, -2.5 };

            Assert.AreEqual(5.1146, calc.Calculate(pos1, pos2), 0.001);
        }
Ejemplo n.º 10
0
        public void EuclideanCalculateDistance_for3and4_expected5()
        {
            double[]          a      = { 10.0, 34.0 };
            double[]          b      = { 13.0, 38.0 };
            EuclideanDistance metric = new EuclideanDistance();
            double            result = metric.CalculateDistance(a, b);

            Assert.AreEqual(5.0, result);
        }
        public void TwoSimilarReviewersShouldHaveOneLikeReview()
        {
            var r1 = ReviewerBuilder.BuildOneReviewMax();
            var r2 = ReviewerBuilder.BuildOneReviewMin();

            euclideanDistance = new EuclideanDistance(r1, r2);

            Assert.IsNotEmpty(euclideanDistance.FindSharedItems());
        }
 public TrainModel(FeatureExtractionType eType, int EuclideanCentroidPointIndex, ClassifierType cType)
 {
     this.cType = cType;
     Trained    = false;
     if (eType == FeatureExtractionType.EuclideanDistance)
     {
         featureExtraction = new EuclideanDistance(EuclideanCentroidPointIndex);
     }
 }
Ejemplo n.º 13
0
        public void DifferentDimensionException()
        {
            EuclideanDistance distance = new EuclideanDistance();
            Vector            v1       = new Vector(new double[] { 1, 2, 3 });
            Vector            v2       = new Vector(new double[] { 1, 2, 3, 4 });

            Assert.Throws <ArgumentException>(() => distance.Measure(v1, v2));
            Assert.Throws <ArgumentException>(() => distance.Measure(v2, v1));
        }
 public TrainModel(FeatureExtractionType eType, ClassifierType cType)
 {
     this.cType = cType;
     Trained    = false;
     if (eType == FeatureExtractionType.EuclideanDistance)
     {
         featureExtraction = new EuclideanDistance(14);
     }
 }
Ejemplo n.º 15
0
        public void Initialize()
        {
            // Composition root (for unit tests)
            // Compose objects here using Dependency Injection
            IDistanceMetric metric   = new EuclideanDistance();
            PointsDistance  distance = new PointsDistance(metric);

            this.cut = new ShootingRange(distance);
        }
Ejemplo n.º 16
0
        public void TestClustering()
        {
            var hclust   = new HierarchicalClustering();
            var vals     = TestUtils.ReadMatrix("Examples/clustering_array_copy_error.txt.gz");
            var data     = new FloatMatrixIndexer(vals);
            var distance = new EuclideanDistance();

            hclust.TreeClusterKmeans(data, MatrixAccess.Columns, distance, HierarchicalClusterLinkage.Average, false,
                                     false, 1, 300, 1, 10,
                                     (i) => { });
        }
Ejemplo n.º 17
0
        public override float[] PredictStrength(BaseVector x)
        {
            double[]  projectedTest = MatrixUtils.VectorTimesMatrix(x, projection);
            float[]   distances     = new float[ngroups];
            IDistance distance      = new EuclideanDistance();

            for (int j = 0; j < ngroups; j++)
            {
                distances[j] = -(float)distance.Get(projectedTest, projectedGroupMeans[j]);
            }
            return(distances);
        }
        public EuclideanDistanceTests()
        {
            Range range = new Range(lowerLimit, upperLimit);

            this.dimensionList = new List <Dimension>(EuclideanDistanceTests.dimensionsCount);
            for (int i = 0; i < EuclideanDistanceTests.dimensionsCount; i++)
            {
                ((List <Dimension>) this.dimensionList).Add(new Dimension(range));
            }

            this.euclideanDistance1 = new EuclideanDistance(this.dimensionList);
        }
Ejemplo n.º 19
0
        public void Distance()
        {
            EuclideanDistance distance = new EuclideanDistance();

            Vector v1 = new Vector(new double[] { 4, 3, 2 });
            Vector v2 = new Vector(new double[] { 2, 3, 4 });

            Assert.AreEqual(Math.Sqrt(8), distance.Measure(v1, v2));
            Assert.AreEqual(distance.Measure(v2, v1), distance.Measure(v1, v2));

            Assert.AreEqual(0, distance.Measure(v1, v1));
            Assert.AreEqual(0, distance.Measure(v2, v2));
        }
Ejemplo n.º 20
0
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        double sigma = 1.0;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real  = Load.load_numbers("../data/fm_test_real.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test  = new RealFeatures(testdata_real);

        EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

        CauchyKernel kernel = new CauchyKernel(feats_train, feats_train, sigma, distance);

        double[,] km_train = kernel.get_kernel_matrix();

        kernel.init(feats_train, feats_test);
        double[,] km_test = kernel.get_kernel_matrix();


        //  Parse and Display km_train
        Console.Write("km_train:\n");
        int numRows = km_train.GetLength(0);
        int numCols = km_train.GetLength(1);

        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                Console.Write(km_train[i, j] + " ");
            }
            Console.Write("\n");
        }

        //  Parse and Display km_test
        Console.Write("\nkm_test:\n");
        numRows = km_test.GetLength(0);
        numCols = km_test.GetLength(1);

        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                Console.Write(km_test[i, j] + " ");
            }
            Console.Write("\n");
        }

        modshogun.exit_shogun();
    }
Ejemplo n.º 21
0
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        double width = 1.7;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real  = Load.load_numbers("../data/fm_test_real.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test  = new RealFeatures(testdata_real);

        EuclideanDistance distance = new EuclideanDistance();

        DistanceKernel kernel = new DistanceKernel(feats_train, feats_test, width, distance);

        double[,] dm_train = distance.get_distance_matrix();
        distance.init(feats_train, feats_test);
        double[,] dm_test = distance.get_distance_matrix();

        //  Parse and Display km_train
        Console.Write("dm_train:\n");
        int numRows = dm_train.GetLength(0);
        int numCols = dm_train.GetLength(1);

        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                Console.Write(dm_train[i, j] + " ");
            }
            Console.Write("\n");
        }

        //  Parse and Display km_test
        Console.Write("\ndm_test:\n");
        numRows = dm_test.GetLength(0);
        numCols = dm_test.GetLength(1);

        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                Console.Write(dm_test[i, j] + " ");
            }
            Console.Write("\n");
        }


        modshogun.exit_shogun();
    }
Ejemplo n.º 22
0
        public void TestRun()
        {
            var anneal = new DiscreteAnnealSubclass(1000, 400, 1);

            while (!anneal.Done)
            {
                anneal.Iteration();
            }

            ICalculateDistance dist = new EuclideanDistance();

            Assert.AreEqual(1000, anneal.K);
            Assert.AreEqual(0, dist.Calculate(anneal.Best, DiscreteAnnealSubclass.Ideal), AIFH.DefaultPrecision);
            Assert.AreEqual(0, anneal.BestScore, AIFH.DefaultPrecision);
        }
Ejemplo n.º 23
0
        private void btnProcessData_Click(object sender, EventArgs e)
        {
            IDistance eucledeanDistance = new EuclideanDistance();

            BackgroundWorker backgroundWorker = new BackgroundWorker();

            backgroundWorker.WorkerReportsProgress = true;
            backgroundWorker.DoWork += (o, eventArgs) =>
            {
                for (int k = (int)start.Value; k <= (int)end.Value; k++)
                {
                    List <double[]> distanceResult = new List <double[]>();

                    _kMeans = new KMeans(k, eucledeanDistance);
                    Centroid[] centroids = _kMeans.Run(_trainingSet.ToArray());

                    double result = 0;
                    foreach (double[] point in _trainingSet)
                    {
                        double minValue = Double.MaxValue;
                        foreach (Centroid centroid in centroids)
                        {
                            double distance = eucledeanDistance.Run(point, centroid.Array);
                            if (distance < minValue)
                            {
                                minValue = distance;
                            }
                        }
                        result += minValue;
                    }
                    result /= _trainingSet.Count;
                    _kmeansPointList.Add(new DPoint(k, result));

                    double progressPercent = (100 * k) / (int)end.Value;
                    ((BackgroundWorker)o).ReportProgress((int)progressPercent, new UserState {
                        Distortion = result, Index = k
                    });
                }
            };
            backgroundWorker.ProgressChanged += (o, eventArgsProgressChanged) =>
            {
                chart1.DataBind();
                progressBar1.Value = eventArgsProgressChanged.ProgressPercentage;
                UserState temp = eventArgsProgressChanged.UserState as UserState;
                listBox1.Items.Add(String.Format("K={0}, Dist: {1}", temp.Index, Math.Round(temp.Distortion, 2)));
            };
            backgroundWorker.RunWorkerAsync();
        }
Ejemplo n.º 24
0
        public void TestGeneralDistanceMatrix()
        {
            var distance       = new EuclideanDistance();
            var distanceMatrix = new GenericDistanceMatrix(new FloatMatrixIndexer(new float[, ] {
                { 0, 0 }, { 1, 0 }, { 3, 0 }
            }), distance);

            Assert.AreEqual(0, distanceMatrix[0, 0]);
            Assert.AreEqual(0, distanceMatrix[2, 2]);
            Assert.AreEqual(distanceMatrix[1, 2], distanceMatrix[2, 1]);
            Assert.AreEqual(1, distanceMatrix[1, 0]);
            Assert.AreEqual(2, distanceMatrix[1, 2]);

            distanceMatrix[0, 1] = -1;
            Assert.AreEqual(-1, distanceMatrix[0, 1]);
        }
	public static void Main() {
		modshogun.init_shogun_with_defaults();
		int merges = 3;

		double[,] fm_train = Load.load_numbers("../data/fm_train_real.dat");

		RealFeatures feats_train = new RealFeatures(fm_train);
		EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

		Hierarchical hierarchical = new Hierarchical(merges, distance);
		hierarchical.train();

		double[] out_distance = hierarchical.get_merge_distances();
		int[,] out_cluster = hierarchical.get_cluster_pairs();

	}
Ejemplo n.º 26
0
        private double[,] CreateDimenstionMatrix(List <Place> places)
        {
            int placesCount = places.Count;

            double[,] dimenstionMatrix = new double[placesCount, placesCount];

            for (int i = 0; i < placesCount; i++)
            {
                for (int j = 0; j < placesCount; j++)
                {
                    dimenstionMatrix[i, j] = EuclideanDistance.FindEuclideanDistance(places.ElementAt(i), places.ElementAt(j));
                }
            }

            return(dimenstionMatrix);
        }
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        int merges = 3;

        double[,] fm_train = Load.load_numbers("../data/fm_train_real.dat");

        RealFeatures      feats_train = new RealFeatures(fm_train);
        EuclideanDistance distance    = new EuclideanDistance(feats_train, feats_train);

        Hierarchical hierarchical = new Hierarchical(merges, distance);

        hierarchical.train();

        double[] out_distance = hierarchical.get_merge_distances();
        int[,] out_cluster = hierarchical.get_cluster_pairs();
    }
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        double sigma = 1.0;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real = Load.load_numbers("../data/fm_test_real.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test = new RealFeatures(testdata_real);

        EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

        CircularKernel kernel = new CircularKernel(feats_train, feats_train, sigma, distance);

        double[,] km_train = kernel.get_kernel_matrix();

        kernel.init(feats_train, feats_test);
        double[,] km_test=kernel.get_kernel_matrix();

        //  Parse and Display km_train
        Console.Write("km_train:\n");
        int numRows = km_train.GetLength(0);
        int numCols = km_train.GetLength(1);

        for(int i = 0; i < numRows; i++){
            for(int j = 0; j < numCols; j++){
                Console.Write(km_train[i,j] +" ");
            }
            Console.Write("\n");
        }

        //  Parse and Display km_test
        Console.Write("\nkm_test:\n");
        numRows = km_test.GetLength(0);
        numCols = km_test.GetLength(1);

        for(int i = 0; i < numRows; i++){
            for(int j = 0; j < numCols; j++){
                Console.Write(km_test[i,j] +" ");
            }
            Console.Write("\n");
        }

        modshogun.exit_shogun();
    }
Ejemplo n.º 29
0
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        double width = 1.7;

        double[,] traindata_real = Load.load_numbers("../data/fm_train_real.dat");
        double[,] testdata_real = Load.load_numbers("../data/fm_test_real.dat");

        RealFeatures feats_train = new RealFeatures(traindata_real);
        RealFeatures feats_test = new RealFeatures(testdata_real);

        EuclideanDistance distance = new EuclideanDistance();

        DistanceKernel kernel = new DistanceKernel(feats_train, feats_test, width, distance);

        double[,] dm_train = distance.get_distance_matrix();
        distance.init(feats_train, feats_test);
        double[,] dm_test = distance.get_distance_matrix();

        //  Parse and Display km_train
        Console.Write("dm_train:\n");
        int numRows = dm_train.GetLength(0);
        int numCols = dm_train.GetLength(1);

        for(int i = 0; i < numRows; i++){
            for(int j = 0; j < numCols; j++){
                Console.Write(dm_train[i,j] +" ");
            }
            Console.Write("\n");
        }

        //  Parse and Display km_test
        Console.Write("\ndm_test:\n");
        numRows = dm_test.GetLength(0);
        numCols = dm_test.GetLength(1);

        for(int i = 0; i < numRows; i++){
            for(int j = 0; j < numCols; j++){
                Console.Write(dm_test[i,j] +" ");
            }
            Console.Write("\n");
        }

        modshogun.exit_shogun();
    }
	public static void Main() {
		modshogun.init_shogun_with_defaults();
		int k = 3;
		// already tried init_random(17)
		Math.init_random(17);

		double[,] fm_train = Load.load_numbers("../data/fm_train_real.dat");

		RealFeatures feats_train = new RealFeatures(fm_train);
		EuclideanDistance distance = new EuclideanDistance(feats_train, feats_train);

		KMeans kmeans = new KMeans(k, distance);
		kmeans.train();

		double[,] out_centers = kmeans.get_cluster_centers();
		kmeans.get_radiuses();

	}
Ejemplo n.º 31
0
        public float GetPathLength()
        {
            if (Path.Length == 0)
            {
                return(0f);
            }
            var euclideanDistance = new EuclideanDistance();
            var length            = 0f;
            var previousWaypoint  = Path[0];

            for (var i = 1; i < Path.Length; i++)
            {
                var waypoint = Path[i];
                length          += euclideanDistance.GetDistance(previousWaypoint, waypoint);
                previousWaypoint = waypoint;
            }
            return(length);
        }
Ejemplo n.º 32
0
        static void Main()
        {
            Console.WriteLine("Biathlon");

            Point  target = ReadInitialPoint();
            double radius = 3.0;

            // Composition root (for normal program run)
            // Compose objects here using Dependency Injection
            IDistanceMetric metric   = new EuclideanDistance();
            PointsDistance  distance = new PointsDistance(metric);
            ShootingRange   sr       = new ShootingRange(distance);

            Point found = sr.SearchFirstNearest(target, radius);

            CheckHit(found);
            Console.ReadLine();
        }
Ejemplo n.º 33
0
        public void TestClusterNodeFormat()
        {
            var hclust = new HierarchicalClustering();
            var data   = new FloatMatrixIndexer(new float[, ] {
                { 1, 2, 3 }, { 2, 3, 4 }
            });
            var distance = new EuclideanDistance();
            var rowTree  = hclust.TreeCluster(data, MatrixAccess.Rows, distance, HierarchicalClusterLinkage.Maximum, false,
                                              false, 1, i => { });
            var rowTreeR = HierarchicalClusterNode.FromRFormat(new[] { -1 }, new[] { -2 }, new[] { 1.732051 });

            Assert.AreEqual(rowTreeR[0], rowTree[0]);

            var colTree = hclust.TreeCluster(data, MatrixAccess.Columns, distance, HierarchicalClusterLinkage.Maximum, false,
                                             false, 1, i => { });
            var colTreeR = HierarchicalClusterNode.FromRFormat(new[] { -1, -3 }, new[] { -2, 1 }, new[] { 1.414214, 2.828428 });

            CollectionAssert.AreEqual(colTree, colTreeR);
        }
Ejemplo n.º 34
0
    public static void Main()
    {
        modshogun.init_shogun_with_defaults();
        int k = 3;

        // already tried init_random(17)
        Math.init_random(17);

        double[,] fm_train = Load.load_numbers("../data/fm_train_real.dat");

        RealFeatures      feats_train = new RealFeatures(fm_train);
        EuclideanDistance distance    = new EuclideanDistance(feats_train, feats_train);

        KMeans kmeans = new KMeans(k, distance);

        kmeans.train();

        double[,] out_centers = kmeans.get_cluster_centers();
        kmeans.get_radiuses();
    }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        public override double EvaluatePartition()
        {
            UpdatesCentroids();

            EuclideanDistance ed = new EuclideanDistance();

            ed.AttributesToCalculateProximity = Set.Attributes.Values;

            double result = 0;

            foreach (var cluster in Structuring.Clusters.Values)
            {
                foreach (var item in cluster.Elements)
                {
                    result += ed.CalculateProximity(item, cluster.Centroid);
                }
            }

            return(Math.Sqrt(result / Set.ElementsCount));
        }
Ejemplo n.º 36
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting: {0}", DateTime.Now);

            String filePath       = args[0];
            String outputFilePath = args[1];
            int    k          = Int32.Parse(args[2]);
            int    distance   = Int32.Parse(args[3]);
            int    numThreads = Int32.Parse(args[4]);

            var samples = CSVIO.Load <float>(filePath);

            Similarity sim = new EuclideanDistance();

            if (distance == 2)
            {
                sim = new PearsonSimilarity();
            }
            if (distance == 3)
            {
                sim = new CosineSimilarity();
            }

            Console.WriteLine("Using distance measure: {0} on {1} samples of dimensionality: {2}",
                              sim, samples.Count, samples[0].Length);

            Console.WriteLine("Beginning Clustering: {0}", DateTime.Now);

            var     clusters = Cluster(samples, sim, numThreads);
            Cluster root     = clusters[0];

            Console.WriteLine("Finished Clustering: {0}", DateTime.Now);

            var classifications = Classify(samples, root, k);

            CSVIO.Save <int>(outputFilePath, classifications);

            Console.WriteLine("Finished: {0}", DateTime.Now);
        }
Ejemplo n.º 37
0
        public void DataGettingTest()
        {
            DataGetter dg   = new DataGetter();
            var        data = dg.GetData("approximation1.txt", ' ');

            var one = dg.GetTrainingDataWithOneOutput("approximation1.txt", 1);

            var test = dg.GetTrainingDataWithOneOutput("approximation_test.txt", 1);

            var two = dg.GetTrainingDataWithChosenInputs("classification.txt", new bool[] { true, true, true, true });

            { Console.WriteLine("test"); }

            var        distCal = new EuclideanDistance();
            RBFNetwork network = new RBFNetwork(distCal,
                                                new GaussianRadialBasis(),
                                                new KNNWidthCalculator(distCal, 2, 1),
                                                new RandomNeuronPositioner(),
                                                2, one[0].DesiredOutput.Count, one[0].Input.Count);

            network.Train(new BackpropagationTrainingParameters(0.5, 20, 0, -1, 1, one), test);

            var output = network.ProcessInput(test[0].Input);
        }
 public void SetUp() {
     LoadData();
     myEuclideanDistance = new EuclideanDistance();
 }
 public void SetUp()
 {
     euclideanDistance = new EuclideanDistance(ReviewerBuilder.BuildReviewer1(), ReviewerBuilder.BuildReviewer2());
 }
Ejemplo n.º 40
0
        /// <summary>
        /// display a GUI and generate the WEKA based clusterer
        /// </summary>
        /// <param name="InstancesList">list of the weka instance</param>
        /// <returns>weka clusterer</returns>
        public Clusterer BuildClusterer(cParamAlgo ClusteringAlgo, cExtendedTable Input)
        {
            this.InputTable = Input;

            foreach (var item in Input)
            {
                this.ListDescriptors.Add(item.Name);
            }

            cListValuesParam Parameters = ClusteringAlgo.GetListValuesParam();

            Clusterer ClustererToReturn = null;
            Instances ListInstancesWithoutClasses = CreateInstancesWithoutClass(Input);
            #region EM
            if (ClusteringAlgo.Name == "EM")
            {
                ClustererToReturn = new EM();

                if (Parameters.ListCheckValues.Get("checkBoxAutomatedClassNum").Value)
                    ((EM)ClustererToReturn).setNumClusters(-1);
                else
                    ((EM)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);

                ((EM)ClustererToReturn).setMaxIterations((int)Parameters.ListDoubleValues.Get("numericUpDownMaxIterations").Value);
                ((EM)ClustererToReturn).setMinStdDev((double)Parameters.ListDoubleValues.Get("numericUpDownMinStdev").Value);
                ((EM)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region K Means
            else if (ClusteringAlgo.Name == "K-Means")
            {
                ClustererToReturn = new SimpleKMeans();
                ((SimpleKMeans)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);
                ((SimpleKMeans)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);

                string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;

                if (DistanceType == "Euclidean")
                {
                    EuclideanDistance ED = new EuclideanDistance();
                    ED.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
                    ((SimpleKMeans)ClustererToReturn).setDistanceFunction(ED);
                }
                else if (DistanceType == "Manhattan")
                {
                    ManhattanDistance MD = new ManhattanDistance();
                    MD.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
                    ((SimpleKMeans)ClustererToReturn).setDistanceFunction(MD);
                }
                else return null;
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            //#region K Means++
            //else if (ClusteringAlgo.Name == "K-Means++")
            //{
            //    ClustererToReturn = new SimpleKMeans();
            //    ((SimpleKMeans)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);
            //    ((SimpleKMeans)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);

            //    string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;

            //    if (DistanceType == "Euclidean")
            //    {
            //        EuclideanDistance ED = new EuclideanDistance();
            //        ED.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
            //        ((SimpleKMeans)ClustererToReturn).setDistanceFunction(ED);
            //    }
            //    else if (DistanceType == "Manhattan")
            //    {
            //        ManhattanDistance MD = new ManhattanDistance();
            //        MD.setDontNormalize(!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value);
            //        ((SimpleKMeans)ClustererToReturn).setDistanceFunction(MD);
            //    }
            //    else return null;
            //    ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
            //    this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            //}
            //#endregion

            #region hierarchical
            else if (ClusteringAlgo.Name == "Hierarchical")
            {
                ClustererToReturn = new weka.clusterers.HierarchicalClusterer();
                string OptionDistance = " -N " + (int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value;

                string DistanceType = (string)Parameters.ListTextValues.Get("comboBoxDistance").Value;
                OptionDistance += " -A \"weka.core.";
                switch (DistanceType)
                {
                    case "Euclidean":
                        OptionDistance += "EuclideanDistance";
                        break;
                    case "Manhattan":
                        OptionDistance += "ManhattanDistance";
                        break;
                    case "Chebyshev":
                        OptionDistance += "ChebyshevDistance";
                        break;
                    default:
                        break;
                }

                if (!(bool)Parameters.ListCheckValues.Get("checkBoxNormalize").Value)
                    OptionDistance += " -D";
                OptionDistance += " -R ";

                OptionDistance += "first-last\"";
                string WekaOption = "-L " + (string)Parameters.ListTextValues.Get("comboBoxLinkType").Value + OptionDistance;
                ((HierarchicalClusterer)ClustererToReturn).setOptions(weka.core.Utils.splitOptions(WekaOption));

                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region Farthest First
            else if (ClusteringAlgo.Name == "FarthestFirst")
            {
                ClustererToReturn = new weka.clusterers.FarthestFirst();

                ((FarthestFirst)ClustererToReturn).setNumClusters((int)Parameters.ListDoubleValues.Get("numericUpDownNumClasses").Value);
                ((FarthestFirst)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);
                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region CobWeb
            else if (ClusteringAlgo.Name == "CobWeb")
            {
                ClustererToReturn = new weka.clusterers.Cobweb();

                ((Cobweb)ClustererToReturn).setSeed((int)Parameters.ListDoubleValues.Get("numericUpDownSeedNumber").Value);
                ((Cobweb)ClustererToReturn).setAcuity((double)Parameters.ListDoubleValues.Get("numericUpDownAcuity").Value);
                ((Cobweb)ClustererToReturn).setCutoff((double)Parameters.ListDoubleValues.Get("numericUpDownCutOff").Value);
                ClustererToReturn.buildClusterer(ListInstancesWithoutClasses);

                this.NumberOfClusters = ClustererToReturn.numberOfClusters();
            }
            #endregion
            #region Manual
            else if (ClusteringAlgo.Name == "Manual")
            {
                string DescriptorName = (string)Parameters.ListTextValues.Get("comboBoxForDescriptorManualClustering").Value;

                //  this.Classes = new double[ListInstancesWithoutClasses.numInstances()];

                for (int IdxPt = 0; IdxPt < this.Classes.Count / 2; IdxPt++)
                {
                    this.Classes[IdxPt] = 2;
                }
                this.NumberOfClusters = 2;
                //    break;

                //int IdxDesc = -1;
                //foreach (string item in this.ListDescriptors)
                //{
                //    IdxDesc++;
                //    if (item == DescriptorName) break;
                //}

                //int Idx=0;

                //foreach (Instance item in ListInstancesWithoutClasses)
                //{
                //    this.Classes.Add(((int)item.value(IdxDesc)) % cGlobalInfo.ListCellularPhenotypes.Count);
                //}

                //// re - ordonner les valeurs du discripteur afin que les classes se suivent sans laisser de classe vide !!
                //this.NumberOfClusters =  cGlobalInfo.ListCellularPhenotypes.Count;
            }
            #endregion

            else
            {
                System.Windows.Forms.MessageBox.Show("Clustering method not implemented !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            return ClustererToReturn;
        }
 public void ReviewersThatHaveTheSameTasteShouldHaveAPerfectScore()
 {
     var r1 = ReviewerBuilder.BuildReviewer1();
     euclideanDistance = new EuclideanDistance(r1, r1);
     Assert.AreEqual(1.0, euclideanDistance.Score());
 }
 public void ReviewersThatHaveTheSameTasteShouldHaveAllSimilarItems()
 {
     var r1 = ReviewerBuilder.BuildReviewer1();
     euclideanDistance = new EuclideanDistance(r1, r1);
     Assert.AreEqual(6, euclideanDistance.FindSharedItems().Count);
 }
Ejemplo n.º 43
0
        public double GetSimilarity(string str1, string str2, string type)
        {
            IStringMetric stringMetric;

            switch (type)
            {
            case AlgorithmTypes.BlockDistance:
                stringMetric = new BlockDistance();
                break;

            case AlgorithmTypes.ChapmanLengthDeviation:
                stringMetric = new ChapmanLengthDeviation();
                break;

            case AlgorithmTypes.ChapmanMeanLength:
                stringMetric = new ChapmanMeanLength();
                break;

            case AlgorithmTypes.CosineSimilarity:
                stringMetric = new CosineSimilarity();
                break;

            case AlgorithmTypes.DiceSimilarity:
                stringMetric = new DiceSimilarity();
                break;

            case AlgorithmTypes.EuclideanDistance:
                stringMetric = new EuclideanDistance();
                break;

            case AlgorithmTypes.JaccardSimilarity:
                stringMetric = new JaccardSimilarity();
                break;

            case AlgorithmTypes.Jaro:
                stringMetric = new Jaro();
                break;

            case AlgorithmTypes.JaroWinkler:
                stringMetric = new JaroWinkler();
                break;

            case AlgorithmTypes.Levenstein:
                stringMetric = new Levenstein();
                break;

            case AlgorithmTypes.MatchingCoefficient:
                stringMetric = new MatchingCoefficient();
                break;

            case AlgorithmTypes.MongeElkan:
                stringMetric = new MongeElkan();
                break;

            case AlgorithmTypes.NeedlemanWunch:
                stringMetric = new NeedlemanWunch();
                break;

            case AlgorithmTypes.OverlapCoefficient:
                stringMetric = new OverlapCoefficient();
                break;

            case AlgorithmTypes.QGramsDistance:
                stringMetric = new QGramsDistance();
                break;

            case AlgorithmTypes.SmithWaterman:
                stringMetric = new SmithWaterman();
                break;

            case AlgorithmTypes.SmithWatermanGotoh:
                stringMetric = new SmithWatermanGotoh();
                break;

            case AlgorithmTypes.SmithWatermanGotohWindowedAffine:
                stringMetric = new SmithWatermanGotohWindowedAffine();
                break;

            default:
                stringMetric = new SmithWatermanGotoh();
                break;
            }

            var similarity = stringMetric.GetSimilarity(str1.Trim(), str2.Trim());

            return(similarity);
        }
Ejemplo n.º 44
0
 //Constructor
 /// <summary>
 /// Creates initialized instance
 /// </summary>
 /// <param name="sourceNeuron">Source neuron</param>
 /// <param name="targetNeuron">Target neuron</param>
 /// <param name="weight">Synapse weight</param>
 public BaseSynapse(INeuron sourceNeuron,
                    INeuron targetNeuron,
                    double weight
                    )
 {
     //Neurons to be connected
     SourceNeuron = sourceNeuron;
     TargetNeuron = targetNeuron;
     //Euclidean distance
     Distance = EuclideanDistance.Compute(SourceNeuron.Placement.ReservoirCoordinates, TargetNeuron.Placement.ReservoirCoordinates);
     //Weight sign and signal range conversion rules
     if (SourceNeuron.Role == CommonEnums.NeuronRole.Input)
     {
         //Source is input neuron
         if (TargetNeuron.OutputType == CommonEnums.NeuronSignalType.Spike)
         {
             //Target is spiking
             //Ensure positive weight
             Weight = Math.Abs(weight);
             //Convert signal to <0,1>
             _add = -SourceNeuron.OutputRange.Min;
             _div = SourceNeuron.OutputRange.Span;
         }
         else
         {
             //Target is also analog
             //Weight is unchanged
             Weight = weight;
             //No signal conversion
             _add = 0;
             _div = 1;
         }
     }
     else
     {
         //Source is reservoir neuron
         if (SourceNeuron.OutputType == CommonEnums.NeuronSignalType.Spike)
         {
             //Source reservoir neuron is spiking
             if (TargetNeuron.OutputType == CommonEnums.NeuronSignalType.Spike)
             {
                 //Target is also spiking
                 //Weight dependent on source neuron role
                 Weight = Math.Abs(weight) * ((SourceNeuron.Role == CommonEnums.NeuronRole.Excitatory) ? 1 : -1);
                 //No signal conversion
                 _add = 0;
                 _div = 1;
             }
             else
             {
                 //Target is analog
                 //Weight is unchanged
                 Weight = weight;
                 //Convert signal to target neuron range
                 _add = (TargetNeuron.OutputRange.Min - SourceNeuron.OutputRange.Min);
                 _div = (SourceNeuron.OutputRange.Span / TargetNeuron.OutputRange.Span);
             }
         }
         else
         {
             //Source reservoir neuron is analog
             if (TargetNeuron.OutputType == CommonEnums.NeuronSignalType.Spike)
             {
                 //Target is spiking
                 //Weight dependent on source neuron role
                 Weight = Math.Abs(weight) * ((SourceNeuron.Role == CommonEnums.NeuronRole.Excitatory) ? 1 : -1);
                 //Convert signal to <0,1>
                 _add = -SourceNeuron.OutputRange.Min;
                 _div = SourceNeuron.OutputRange.Span;
             }
             else
             {
                 //Target is also analog
                 //Weight is unchanged
                 Weight = weight;
                 //No signal conversion
                 _add = 0;
                 _div = 1;
             }
         }
     }
     //Set Delay to 0 as default. It can be changed later by SetDelay method.
     Delay = 0;
     //Efficacy statistics
     EfficacyStat = new BasicStat(false);
     return;
 }
Ejemplo n.º 45
0
        public static double ApproximatelyEquals(this string firstWord, string secondWord, SimMetricType simMetricType = SimMetricType.Levenstein)
        {
            switch (simMetricType)
            {
            case SimMetricType.BlockDistance:
                var sim2 = new BlockDistance();
                return(sim2.GetSimilarity(firstWord, secondWord));

            case SimMetricType.ChapmanLengthDeviation:
                var sim3 = new ChapmanLengthDeviation();
                return(sim3.GetSimilarity(firstWord, secondWord));

            case SimMetricType.CosineSimilarity:
                var sim4 = new CosineSimilarity();
                return(sim4.GetSimilarity(firstWord, secondWord));

            case SimMetricType.DiceSimilarity:
                var sim5 = new DiceSimilarity();
                return(sim5.GetSimilarity(firstWord, secondWord));

            case SimMetricType.EuclideanDistance:
                var sim6 = new EuclideanDistance();
                return(sim6.GetSimilarity(firstWord, secondWord));

            case SimMetricType.JaccardSimilarity:
                var sim7 = new JaccardSimilarity();
                return(sim7.GetSimilarity(firstWord, secondWord));

            case SimMetricType.Jaro:
                var sim8 = new Jaro();
                return(sim8.GetSimilarity(firstWord, secondWord));

            case SimMetricType.JaroWinkler:
                var sim9 = new JaroWinkler();
                return(sim9.GetSimilarity(firstWord, secondWord));

            case SimMetricType.MatchingCoefficient:
                var sim10 = new MatchingCoefficient();
                return(sim10.GetSimilarity(firstWord, secondWord));

            case SimMetricType.MongeElkan:
                var sim11 = new MongeElkan();
                return(sim11.GetSimilarity(firstWord, secondWord));

            case SimMetricType.NeedlemanWunch:
                var sim12 = new NeedlemanWunch();
                return(sim12.GetSimilarity(firstWord, secondWord));

            case SimMetricType.OverlapCoefficient:
                var sim13 = new OverlapCoefficient();
                return(sim13.GetSimilarity(firstWord, secondWord));

            case SimMetricType.QGramsDistance:
                var sim14 = new QGramsDistance();
                return(sim14.GetSimilarity(firstWord, secondWord));

            case SimMetricType.SmithWaterman:
                var sim15 = new SmithWaterman();
                return(sim15.GetSimilarity(firstWord, secondWord));

            case SimMetricType.SmithWatermanGotoh:
                var sim16 = new SmithWatermanGotoh();
                return(sim16.GetSimilarity(firstWord, secondWord));

            case SimMetricType.SmithWatermanGotohWindowedAffine:
                var sim17 = new SmithWatermanGotohWindowedAffine();
                return(sim17.GetSimilarity(firstWord, secondWord));

            case SimMetricType.ChapmanMeanLength:
                var sim18 = new ChapmanMeanLength();
                return(sim18.GetSimilarity(firstWord, secondWord));

            default:
                var sim1 = new Levenstein();
                return(sim1.GetSimilarity(firstWord, secondWord));
            }
        }