public void ToByteArrayTest() { Guid id = Guid.NewGuid(); Centroid target = new Centroid { ID = id, X = 1.23, Y = 3.45 }; MemoryStream stream = new MemoryStream(); stream.Write(id.ToByteArray(), 0, 16); stream.Write(BitConverter.GetBytes(1.23), 0, sizeof(double)); stream.Write(BitConverter.GetBytes(3.45), 0, sizeof(double)); byte[] expected = stream.ToArray(); byte[] actual; actual = target.ToByteArray(); Assert.AreEqual(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { Assert.AreEqual(expected[i], actual[i]); } }
public void FromByteArrayTest() { const double Epsilon = 0.0001; Guid id = Guid.NewGuid(); MemoryStream stream = new MemoryStream(); stream.Write(id.ToByteArray(), 0, 16); stream.Write(BitConverter.GetBytes(2.53), 0, sizeof(double)); stream.Write(BitConverter.GetBytes(4.56), 0, sizeof(double)); byte[] bytes = stream.ToArray(); Centroid expected = new Centroid { ID = id, X = 2.53F, Y = 4.56F }; Centroid actual; actual = Centroid.FromByteArray(bytes); Assert.AreEqual(expected.ID, actual.ID); Assert.IsTrue(Math.Abs(expected.X - actual.X) < Epsilon); Assert.IsTrue(Math.Abs(expected.Y - actual.Y) < Epsilon); }
public void AddCentroid() { Centroid cent = PlotterUtil.Centroid(DB.GetSelectedFigList()); if (cent.IsInvalid) { return; } CadFigure pointFig = mDB.NewFigure(CadFigure.Types.POINT); pointFig.AddPoint((CadVertex)cent.Point); pointFig.EndCreate(DC); CadOpe ope = new CadOpeAddFigure(CurrentLayer.ID, pointFig.ID); HistoryMan.foward(ope); CurrentLayer.AddFigure(pointFig); string s = string.Format("({0:0.000},{1:0.000},{2:0.000})", cent.Point.X, cent.Point.Y, cent.Point.Z); ItConsole.println("Centroid:" + s); ItConsole.println("Area:" + (cent.Area / 100).ToString() + "(㎠)"); }
public static Point3d?GetCentroid(IList <Point3d> points) { Point3d?result = null; var coordinates = new List <Coordinate>(); foreach (var point in points) { var coordinate = new Coordinate() { X = point.X, Y = point.Y, Z = 0 }; coordinates.Add(coordinate); } ICoordinateSequence coordinateSequence = CoordinateArraySequenceFactory.Instance.Create(coordinates.ToArray()); var geometryF = new DwgWriter(); var polygon = geometryF.GeometryFactory.CreatePolygon(coordinateSequence.ToCoordinateArray()); var coords = Centroid.GetCentroid(polygon); if (coords != null) { result = new Point3d(coords.X, coords.Y, coords.Z); } return(result); }
/// <summary> /// Encodes the peaks into a byte array according to the input peak flags. /// </summary> /// <param name="scan">The scan with the peaks to store</param> /// <returns>A byte array with the peak data.</returns> private byte[] encodePeaks(Scan scan) { int peakCount = scan.Centroids.Count; double[] mz = new double[peakCount]; float[] all = new float[peakCount * 4]; for (int i = 0; i < scan.Centroids.Count; ++i) { Centroid peak = scan.Centroids[i]; mz[i] = peak.Mz; all[i] = (float)peak.Mz; all[i + peakCount] = (float)peak.Intensity; all[i + (peakCount * 2)] = (float)peak.Baseline; all[i + (peakCount * 3)] = (float)peak.Noise; } if (scan.DetectorType == "FTMS") { int mzBytes = peakCount * sizeof(double); int otherBytes = peakCount * 3 * sizeof(float); byte[] output = new byte[mzBytes + otherBytes]; Buffer.BlockCopy(mz, 0, output, 0, mzBytes); Buffer.BlockCopy(all, peakCount * sizeof(float), output, mzBytes, otherBytes); return(output); } else { int byteCount = peakCount * 2 * sizeof(float); byte[] output = new byte[byteCount]; Buffer.BlockCopy(all, 0, output, 0, byteCount); return(output); } }
private void btn_Centrare_Click(object sender, EventArgs e) { bool changed; do { Centroid[] centr_old = new Centroid[nr_centroizi]; Centroid[] centr_new = new Centroid[nr_centroizi]; // Thread.Sleep(1000); changed = false; RecentrareCentroizi(); centr_old = centroizi; if (centroizi_new != null) { centroizi = centroizi_new; centr_new = centroizi_new; } GruparePct(); for (int i = 0; i < nr_centroizi; i++) { if ((centr_new[i].x != centr_old[i].x) || (centr_new[i].y != centr_old[i].y)) { changed = true; break; } } } while (changed); }
/// <summary> /// Initialize empty clusters with centroid values based on their distances from each other. /// </summary> /// <param name="clusterCount">Number of clusters to initialize.</param> protected void InitEmptyKmeansClusters(uint clusterCount) { _clusters = new Dictionary <uint, Cluster>(); Centroid firstcentroid = new Centroid(PointDim); firstcentroid.FillWithRandomValues(); //first center is random _clusters.Add(firstcentroid.ID, new Cluster(_points, _distance, firstcentroid)); for (uint i = 1; i < clusterCount; i++) { Centroid centroid = new Centroid(PointDim); byte[] farthest = new byte[PointDim]; float maxDist = 0.0f; foreach (byte[] point in _points) { float dist = 0.0f; foreach (var cluster in _clusters.Values) { dist += _distance.Calculate(cluster.Centroid.Values, point); } if (dist > maxDist) { maxDist = dist; farthest = point; } } centroid.CopyValuesFrom(farthest); _clusters.Add(centroid.ID, new Cluster(_points, _distance, centroid)); } }
/// <summary> /// Creates a new CentroidPoint and fills its values with a deep copy of the values of an existing CentroidPoint. /// The ID is not copied from the existing CentroidPoint. /// </summary> /// <returns>The newly created CentroidPoint.</returns> public static Centroid CentroidOfValues(Centroid toCopy) { Centroid res = new Centroid(toCopy.Dim); res.CopyValuesFrom(toCopy.Values); return(res); }
public static List <Centroid> CentroidCalculationsForKMeans(List <DocumentVector> data, int ClusterNumber) { List <Centroid> centroidList = new List <Centroid>(); Random randomizer = new Random(); HashSet <int> indexSet = new HashSet <int>(); int index = 0; while (centroidList.Count != ClusterNumber) { index = randomizer.Next(0, data.Count + 1); if (!indexSet.Contains(index)) { indexSet.Add(index); Centroid newCentroid = new Centroid(); newCentroid.GroupedDocument = new List <DocumentVector>(); newCentroid.GroupedDocument.Add(data[index]); centroidList.Add(newCentroid); } else if (indexSet.Contains(index)) { continue; } } foreach (var doc in centroidList) { doc.CalculateMeans(); doc.GroupedDocument.Clear(); } return(centroidList); }
public static float[] CalculateProbabilityArray(Centroid oldCentroid, List <DocumentVector> vSpace) { List <DocumentVector> vSpaceCopy = new List <DocumentVector>(vSpace); float[] vector_A = oldCentroid.GroupedDocument[0].VectorSpace; float[] DistanceQuad = new float[vSpaceCopy.Count]; for (int i = 0; i < DistanceQuad.Length; i++) { DistanceQuad[i] = 0; } float SumDistanceQuad = 0; int previous_index = vSpaceCopy.IndexOf(oldCentroid.GroupedDocument[0]); for (int j = 0; j <= vSpaceCopy.Count - 1; j++) { float[] vector_B = vSpaceCopy[j].VectorSpace; for (int k = 0; k <= vSpaceCopy[j].VectorSpace.Length - 1; k++) { DistanceQuad[j] += (float)Math.Pow((vector_A[k] - vector_B[k]), 2); } SumDistanceQuad += DistanceQuad[j]; } for (int j = 0; j <= DistanceQuad.Length - 1; j++) { DistanceQuad[j] = DistanceQuad[j] / SumDistanceQuad; } return(DistanceQuad); }
/// <summary> /// This method will write a radial circle to the output KML file. Google /// Earth does not support a circle, a point is written and rotated around /// a given centroid object 360 times to make a radial circle. /// </summary> /// <param name="centre">The centroid of the radial circle</param> /// <param name="radius">The radius of the circle (in KM)</param> private static void WriteRadialCircle(Centroid centre, double radius) { // New Placemark Kml.WriteStartElement("Placemark"); Kml.WriteElementString("name", "Cluster Radius"); Kml.WriteElementString("styleUrl", "#centroid-radius"); // Setup various polgon elements Kml.WriteStartElement("Polygon"); Kml.WriteStartElement("outerBoundaryIs"); Kml.WriteStartElement("LinearRing"); Kml.WriteStartElement("coordinates"); // Get a list of Radial Locations to create the circle RadialCircle r = new RadialCircle(centre, radius); List <Coordinate> radialLocations = r.CreateRadialCircle(); // Add each coordinate to the coordinates list foreach (Coordinate coordinate in radialLocations) { Kml.WriteValue(coordinate.ToString() + Environment.NewLine); } // End the Elements Kml.WriteEndElement(); Kml.WriteEndElement(); Kml.WriteEndElement(); Kml.WriteEndElement(); Kml.WriteEndElement(); }
public string match_data(List <Centroid> collection, Centroid temp) { double distance = 0.0; double currDistance = 900000000; string centroidString = ""; //Can do a second distance check to see how far away the closest one is to resemble the idea of a "no match" for a user //Check if the centroid has values > 0 then don't check it, because the user hasn't trained on it yet - not right now foreach (Centroid c in collection) //Iterate through each centroid { distance = 0.0; //Reset distance so it doesn't continue to grow every time we check for (int i = 0; i < c.sensors.Length; i++) { distance += (Math.Pow((c.sensors[i] - temp.sensors[i]), 2)); } distance = Math.Sqrt(distance); if (distance < currDistance) //Setting the 1st centroid to the distance and then comparing it to the rest of them. Ignores ties { currDistance = distance; c.currDistance = currDistance; centroidString = c.name; } } clearCentroidDistances(collection); playWord(centroidString); //Here is where the audio function gets called. It will play after you press ok on the Matching complete messagebox. return(centroidString); }
private void ClusterWith99BlogsSomeBlogsShouldAlwayBeClusteredTogether(string[] blogsThatShouldBeClusteredTogether) { // Arrange var sut = new KMeansClustering(new PearsonCorrelationSimilarityAlgorithm()); for (var iteration = 0; iteration <= 10; iteration++) { // Act var result = sut.Cluster(this.blogs, 5, -1).ToArray(); // Assert Assert.Equal(5, result.Count()); Centroid centroidWithBlogsThatShouldBeClusteredTogether = null; foreach (var centroid in result) { if (centroid.Blogs.Any(b => b.Name == blogsThatShouldBeClusteredTogether.First())) { centroidWithBlogsThatShouldBeClusteredTogether = centroid; break; } } foreach (var blogName in blogsThatShouldBeClusteredTogether) { Assert.Contains(centroidWithBlogsThatShouldBeClusteredTogether.Blogs, b => b.Name == blogName); } } }
private void buttonDetermine_Click(object sender, EventArgs e) { Random rnd = new Random(); int f = 0; f = rnd.Next(1, listOfIris.Count - 1); //get the highest distance and set it as 2nd point double outResult = 0; int sIndex = 0; for (int i = 0; i < listOfIris.Count; i++) { double result = Centroid.CalculateDistanceIris(listOfIris[f], listOfIris[i]); if (outResult < result) { outResult = result; sIndex = i; } } //find the 3rd centroid based on the average double f3 = (listOfIris[f].PetalL + listOfIris[sIndex].PetalL) / 2; double f4 = (listOfIris[f].PetalW + listOfIris[sIndex].PetalW) / 2; double f1 = (listOfIris[f].SepalL + listOfIris[sIndex].SepalL) / 2; double f2 = (listOfIris[f].SepalW + listOfIris[sIndex].SepalW) / 2; centroid1 = new Centroid(listOfIris[f].SepalL, listOfIris[f].SepalW, listOfIris[f].PetalL, listOfIris[f].PetalW, "Setosa"); centroid2 = new Centroid(listOfIris[sIndex].SepalL, listOfIris[sIndex].SepalW, listOfIris[sIndex].PetalL, listOfIris[sIndex].PetalW, "Versicolor"); centroid3 = new Centroid(f1, f2, f3, f4, "Virginica"); buttonAutoRun.Visible = true; buttonRun.Visible = true; }
public static Tuple <int[], int[], List <Centroid> > Set(List <DocumentVector> docCollection) { Tuple <int[], int[], List <Centroid> > result; parent = new int[docCollection.Count]; rank = new int[docCollection.Count]; var centroidSet = new List <Centroid>(); for (int i = 0; i < docCollection.Count; i++) { parent[i] = i; rank[i] = 0; } Centroid newCentroid; List <DocumentVector> docCollectionCopy = new List <DocumentVector>(docCollection); for (int j = 0; j < docCollectionCopy.Count; j++) { newCentroid = new Centroid(); newCentroid.GroupedDocument = new List <DocumentVector>(); newCentroid.GroupedDocument.Add(docCollectionCopy[j]); centroidSet.Add(newCentroid); } result = new Tuple <int[], int[], List <Centroid> >(parent, rank, centroidSet); return(result); }
public static Centroid Centroid(List <CadFigure> figList) { Centroid cent = default(Centroid); cent.IsInvalid = true; foreach (CadFigure fig in figList) { Centroid t = fig.GetCentroid(); if (cent.IsInvalid) { cent = t; continue; } if (t.IsInvalid) { continue; } cent = cent.Merge(t); } return(cent); }
public Cluster(byte[][] points, IDistance distance, Centroid centroid) { _points = points; _distance = distance; PointIndices = new List <uint>(); Centroid = centroid; }
public void RecalculateCentroidsTest2() { KMeansJobData jobData = new KMeansJobData(Guid.NewGuid(), 0, null, 1, 10, DateTime.Now); KMeansJob_Accessor target = new KMeansJob_Accessor(jobData, "server"); target.InitializeStorage(); byte[] cBytes = new byte[Centroid.Size]; using (BlobStream cStream = target.Centroids.OpenRead()) { cStream.Read(cBytes, 0, cBytes.Length); } Centroid cOriginal = Centroid.FromByteArray(cBytes); target.totalPointsProcessedDataByCentroid[cOriginal.ID] = new PointsProcessedData(); target.RecalculateCentroids(); byte[] cBytesNew = new byte[Centroid.Size]; using (BlobStream cStreamNew = target.Centroids.OpenRead()) { cStreamNew.Read(cBytesNew, 0, cBytesNew.Length); } Centroid cNew = Centroid.FromByteArray(cBytesNew); Assert.AreEqual(cOriginal.ID, cNew.ID); Assert.AreEqual(cNew.X, 0); Assert.AreEqual(cNew.Y, 0); }
// Start is called before the first frame update private void Awake() { // Create the sides this.centroid = this.CreateCentroid(); this.sides = this.CreateSides(this.centroid); this.VirtualCamera.Follow = this.centroid.Object.transform; }
public static List <Centroid> CentroidCalculationsForKMeans(List <DocumentVector> data, int ClusterNumber) { List <Centroid> centroidList = new List <Centroid>(); Random randomizer = new Random(); HashSet <int> indexSet = new HashSet <int>(); int index = 0; while (centroidList.Count != ClusterNumber) { index = randomizer.Next(0, data.Count + 1); if (!indexSet.Contains(index)) { indexSet.Add(index); Centroid newCentroid = new Centroid(); newCentroid.GroupedDocument = new List <DocumentVector>(); newCentroid.GroupedDocument.Add(data[index]); newCentroid.SetCenter(data[index].OriginalVectorSpace); //last changes newCentroid.means = newCentroid.GroupedDocument.First().VectorSpace; centroidList.Add(newCentroid); } else if (indexSet.Contains(index)) { continue; } } return(centroidList); }
private void Seperation(Centroid centroid) { // filter out the cluster which has customers with identical id as that of the centroid which we want to calculate the distance with. List <Centroid> tempCentroidList = (KmeansCentroids.Where(c => c.Id != centroid.Id)).ToList(); for (int i = 0; i < tempCentroidList.Count; i++) { for (int customer = 0; customer < centroid.cluster.Count; customer++) { double sumdistance = 0; // accumulator for (int other_customer = 0; other_customer < tempCentroidList[i].cluster.Count; other_customer++) { if (tempCentroidList[i].cluster[other_customer].CustomerId < centroid.cluster[customer].CustomerId) { // if the value cant't be found in the matrix because of the a> b & b > a implementation, flip the customer and the other customer to find th distance value. sumdistance += Distance_Matrix[tempCentroidList[i].cluster[other_customer].CustomerId] [centroid.cluster[customer].CustomerId]; } else { sumdistance += Distance_Matrix[centroid.cluster[customer].CustomerId] [tempCentroidList[i].cluster[other_customer].CustomerId]; } } // add the accumulated results to the list of neighbours of the customer centroid.cluster[customer].AddNeighbhour(new Tuple <int, double>(tempCentroidList[i].Id, sumdistance)); } } }
private void do_training(Centroid c) { EEG_Logger p = new EEG_Logger(); //Creating a new object of the class and acting upon it for (int i = 0; i < 10; i++) { pBar.PerformStep(); p.Run(); Thread.Sleep(1660); //Slow down the process, so the user can see what's happening and also to pull data for a specified amount of time //1660 for 15.03 Seconds } read_CSV().read_training_records(c); pBar.Value = 0; File.Delete("outfile.csv"); this.userInfoStringParsed[this.c.position + 1] = this.c.currDistance.ToString(); this.userInfoString = ""; foreach (string s in this.userInfoStringParsed) { this.userInfoString += (s + ","); } this.userInfoString = this.userInfoString.Substring(0, this.userInfoString.Length - 1); MessageBox.Show("Training complete."); }
private void SetAverageCoordinates(Centroid centroid) { var samplePoints = SamplePoints.Where(point => point.NearsetPointId == centroid.Id).ToArray(); if (samplePoints.Length != 0) { List <double> averages = new List <double>(); for (var i = 0; i < samplePoints.First().Coordinates.Count; i++) { averages.Add(0.0); } foreach (var samplePoint in samplePoints) { for (var i = 0; i < averages.Count; i++) { averages[i] += samplePoint.Coordinates[i]; } } for (var i = 0; i < averages.Count; i++) { averages[i] /= samplePoints.Length; } MaxCentroidShift = Euclides.CalculateDistance(new SamplePoint(averages), centroid); centroid.Coordinates = averages; } }
/// <summary> /// Generate centroids from two arrays of m/z and intensity /// </summary> /// <param name="scan"></param> /// <param name="mzArray"></param> /// <param name="intensityArray"></param> public void CentroidsFromArrays(Data.Scan scan, double[] mzArray, double[] intensityArray, double[] baseline = null, double[] noise = null) { if (mzArray.Length != intensityArray.Length) { throw new Exception(" Error: MZ and Intensity Arrays of unequal length."); } scan.PeakCount = mzArray.Length; for (int i = 0; i < mzArray.Length; i++) { Centroid tempCentroid = new Centroid() { Mz = mzArray[i], Intensity = intensityArray[i], }; if (baseline != null) { tempCentroid.Baseline = baseline[i]; } if (noise != null) { tempCentroid.Noise = noise[i]; } scan.Centroids.Add(tempCentroid); } }
private static List <Centroid> generate_random_Centroids(int number_of_Clusters, List <DocumentVector> vSpace) { List <Centroid> result = new List <Centroid>(); HashSet <int> clusterIndexes = new HashSet <int>(); Random rand = new Random(); while (clusterIndexes.Count != number_of_Clusters) { for (int i = 0; i < number_of_Clusters; i++) { int index = rand.Next(0, vSpace.Count); clusterIndexes.Add(index); } } for (int j = 0; j <= clusterIndexes.Count - 1; j++) { int index = clusterIndexes.ElementAt(j); Centroid newCentroid = new Centroid(); newCentroid.GroupedDocument = new List <DocumentVector>(); newCentroid.GroupedDocument.Add(vSpace[index]); result.Add(newCentroid); } return(result); }
//Used to find the centroid this node belongs to public void AssignCentroid(List <Centroid> newCentroids) { centroid = null; double distanceToAssignedCentroid = 10000; //Loop through all centroids foreach (Centroid NewCentroid in newCentroids) { //calculate distance to new centrod double distanceToNewCentroid = Math.Sqrt(Math.Pow(NewCentroid.Xpos - xpos, 2) + Math.Pow(NewCentroid.Ypos - ypos, 2)); if (centroid == null && distanceToNewCentroid <= Globals.XmlData.Threshold) { //This node is not assigned to a centroid, assign it to one if is within the threshold centroid = NewCentroid; centroid.nodes.Add(this); //keep track of distance to assigned centroid distanceToAssignedCentroid = Math.Sqrt(Math.Pow(centroid.Xpos - xpos, 2) + Math.Pow(centroid.Ypos - ypos, 2)); } else if (centroid != null && distanceToNewCentroid <= distanceToAssignedCentroid && distanceToNewCentroid <= Globals.XmlData.Threshold) { //The new centroid is closer than the old centroid, remove this node from old and assign to new centroid.nodes.Remove(this); centroid = NewCentroid; centroid.nodes.Add(this); distanceToAssignedCentroid = Math.Sqrt(Math.Pow(centroid.Xpos - xpos, 2) + Math.Pow(centroid.Ypos - ypos, 2)); } } }
private void button1_Click(object sender, EventArgs e) { int iteration = 0; while (iteration > numericUpDownClusterNumber.Value) { List <Iris> irisC1 = new List <Iris>(); List <Iris> irisC2 = new List <Iris>(); List <Iris> irisC3 = new List <Iris>(); foreach (Iris i in listOfIris) { i.Centroid = CentroidMover.CountDistAndAssignCentroid(i, centroid1, centroid2, centroid3); if (i.Centroid == centroid1) { irisC1.Add(i); } else if (i.Centroid == centroid2) { irisC2.Add(i); } else if (i.Centroid == centroid3) { irisC3.Add(i); } } centroid1 = Centroid.HitungPosisiCentroid(irisC1); centroid2 = Centroid.HitungPosisiCentroid(irisC2); centroid3 = Centroid.HitungPosisiCentroid(irisC3); switch (iteration) { case (5): listBoxDisplay.Items.Add(CentroidMover.CalcSSE(listOfIris, centroid1, centroid2, centroid3)); continue; case (10): listBoxDisplay.Items.Add(CentroidMover.CalcSSE(listOfIris, centroid1, centroid2, centroid3)); continue; case (15): listBoxDisplay.Items.Add(CentroidMover.CalcSSE(listOfIris, centroid1, centroid2, centroid3)); continue; } iteration++; } foreach (Iris i in listOfIris) { if (centroid1 == i.Centroid) { dataGridViewDataCluster.Rows.Add(i.SepalL, i.SepalW, i.PetalL, i.PetalW, "Setosa"); } else if (centroid2 == i.Centroid) { dataGridViewDataCluster.Rows.Add(i.SepalL, i.SepalW, i.PetalL, i.PetalW, "Versicolor"); } else if (centroid3 == i.Centroid) { dataGridViewDataCluster.Rows.Add(i.SepalL, i.SepalW, i.PetalL, i.PetalW, "Virginica"); } } }
private double CalculateDistance(Blog blog, Centroid centeroid) { var pearson = new PearsonCorrelationSimilarityAlgorithm(); var similarity = pearson.CalculateSimilarity(blog.Words, centeroid.Words); return(1 - similarity); }
public static void Parse(List<ImageInfo> images, int clusters) { MinMax[] propertyRanges = GeneratePropertyMinMaxes(images); Centroid[] clusterMeans = new Centroid[clusters]; for (int i = 0; i < clusters; ++i) { //clusterMeans[i] = GenerateRandomCentroid(images); clusterMeans[i] = GenerateRandomCentroidWithinRange(propertyRanges); } int iteration = 1; while (true) { Centroid[] prevClusterMeans = new Centroid[clusters]; for (int i = 0; i < clusterMeans.Length; ++i) { prevClusterMeans[i] = new Centroid(); Centroid oldMean = prevClusterMeans[i]; clusterMeans[i].PropertyValues.CopyTo(oldMean.PropertyValues, 0); } foreach (ImageInfo image in images) { int oldCluster = image.Cluster; image.Cluster = FindIndexOfNearestClusterMean(image, clusterMeans); Debug.WriteLine("Image was {0} now {1} cluster", oldCluster, image.Cluster); } for (int i = 0; i < clusterMeans.Length; ++i) { double[] propertyMedians = CalculateClusterMean(clusterIndex: i, images: images); if (propertyMedians == null) // has no images { Debug.WriteLine("NO GAME FOR {0}", i); //clusterMeans[i] = GenerateRandomCentroid(images); clusterMeans[i] = GenerateRandomCentroidWithinRange(propertyRanges); continue; } clusterMeans[i].PropertyValues = propertyMedians; } bool pointsAreStill = true; for (int i = 0; i < clusters; ++i) { double distance = prevClusterMeans[i].DistanceTo(clusterMeans[i]); if (distance > double.Epsilon) { pointsAreStill = false; break; } } Debug.WriteLine("Iteration: {0}", iteration++); if (pointsAreStill) break; } }
public void SetUpClassificationAlgorithm() { _prevOutputWeightError = 0; Centroid.ResetNextId(); CalculateHiddenLayerOutputs(); InitOutputLayerWeights(); TotalErrors.Clear(); TotalTestErrors.Clear(); }
// Cálculo da Distância Euclidiana public double CalcularDistanciaEuclidiana(Centroid centroid, IrisData data) { double a = data.SepalLength - centroid.SepalLength; double b = data.SepalWidth - centroid.SepalWidth; double c = data.PetalLength - centroid.PetalLength; double d = data.PetalWidth - centroid.PetalWidth; return(Math.Sqrt((a * a) + (b * b) + (c * c) + (d * d))); }
public CentroidConfig(double[,] c, int nvars, int k) { this.K = k; this.NVars = nvars; C = new List<Centroid>(); for (int i = 0; i < K; i++) { var cin = new Centroid(i); for (int j = 0; j < NVars; j++) cin.Vars.Add(c[j, i]); C.Add(cin); } }
private static Centroid GenerateRandomCentroid(List<ImageInfo> images) { Centroid centroid = new Centroid(); int randomIndex = new Random(DateTime.Now.Millisecond).Next(images.Count); ImageInfo randomImage = images[randomIndex]; for (int i = 0; i < ImageInfo.PropertiesCount; ++i) { centroid.PropertyValues[i] = randomImage.GetPropertyByIndex(i); } return centroid; }
private static void AddKeyPress(int vkCode) { Debug.WriteLine("AddKeyPress at " + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString()); var kc = new KeysConverter(); var keyChar = kc.ConvertToString(vkCode).ToUpper(); var keyOut = ""; switch (keyChar) { case "1": keyOut = "ONE"; break; case "2": keyOut = "TWO"; break; case "3": keyOut = "THREE"; break; case "4": keyOut = "FOUR"; break; case "5": keyOut = "FIVE"; break; case "6": keyOut = "SIX"; break; case "7": keyOut = "SEVEN"; break; case "8": keyOut = "EIGHT"; break; case "9": keyOut = "NINE"; break; case "0": keyOut = "ZERO"; break; default: keyOut = keyChar; break; } try { //KeyCodes.ScanCode code = (KeyCodes.ScanCode)Enum.Parse(typeof(KeyCodes.ScanCode), keyOut); var query = from KeyCodes.KeyPosition k in KeyCodes.KeyPositions where k.KeyName == keyOut //(int)code select k; var c = new Centroid(); c.Point = new Point((int)query.First().X, (int)query.First().Y); c.CountUp = 1; var c1 = Form1.StartColor; var c2 = Form1.EndColor; if (Form1.RandomColors) { var rndcol = new Random(); c1 = System.Drawing.Color.FromArgb(rndcol.Next(30, 255), rndcol.Next(30, 255), rndcol.Next(30, 255)); c2 = System.Drawing.Color.FromArgb(rndcol.Next(30, 255), rndcol.Next(30, 255), rndcol.Next(30, 255)); } var converter = new ColorManagment.ColorConverter(); //create a new instance of a ColorConverter var rgb1 = new ColorRGB(RGBSpaceName.sRGB, c1.R, c1.G, c1.B); //create an RGB color c.Lab1 = converter.ToLab(rgb1); var rgb2 = new ColorRGB(RGBSpaceName.sRGB, c2.R, c2.G, c2.B); //create an RGB color c.Lab2 = converter.ToLab(rgb2); if (_centroids.Count > 0) { for (var i = _centroids.Count - 1; i > -1; i--) { Debug.WriteLine(i); if (_centroids[i].Point == c.Point) { _centroids.RemoveAt(i); break; } } } _centroids.Add(c); //DoAnimation(); } catch (Exception ex) { Debug.WriteLine("AddKeyPress: handled exception: " + ex.Message); } }
private static int FindIndexOfNearestClusterMean(ImageInfo image, Centroid[] means) { Debug.WriteLine("Image's nearest mean:"); int nearestMeanIndex = -1; double minDistance = double.MaxValue; for (int i = 0; i < means.Length; ++i) { double distanceToMean = means[i].DistanceTo(image); Debug.WriteLine("Distance to {0} = {1}", i, distanceToMean); if (distanceToMean < minDistance) { nearestMeanIndex = i; minDistance = distanceToMean; } } if (nearestMeanIndex == -1) Debugger.Break(); Debug.WriteLine("Nearest mean index: {0}", nearestMeanIndex); return nearestMeanIndex; }
private static Centroid GenerateRandomCentroidWithinRange(MinMax[] ranges) { Centroid centroid = new Centroid(); Random rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i < ImageInfo.PropertiesCount; ++i) { MinMax minMax = ranges[i]; centroid.PropertyValues[i] = rand.NextDouble() * (minMax.Max - minMax.Min) + minMax.Min; } return centroid; }