Given
List<double> x1 = new List<double> { -0.2718, -0.2240, -0.1275, -0.0810, 0.0349, -0.5067, 0.0094, -0.4404, -0.1212 };
List<double> x2 = new List<double> { 0.0330, -0.6463, 0.1226, -0.3304, 0.4764, -0.4159, 0.4209, -0.4070, -0.2090 };
How can I make as double[][] X at runtime(programatically).
I mean to say if the output I get if I run
double[][] X = { new double[]
{ -0.2718, -0.2240, -0.1275, -0.0810, 0.0349, -0.5067, 0.0094, -0.4404, -0.1212 },
new double[] { 0.0330, -0.6463, 0.1226, -0.3304, 0.4764, -0.4159, 0.4209, -0.4070, -0.2090 } };
Using C#3.0
Thanks
double[][] X = new[] { x1.ToArray(), x2.ToArray() };
double[][] X = new double[][] { x1.ToArray(), x2.ToArray() };
Related
Good afternoon! I'm trying to sew up two meshes. I do this as follows: first I convert the sprite into a mesh, then I duplicate the resulting mesh, shift it along the "z" axis, invert it, and then sew it up. But I faced such a problem: he sews rectangular meshes well, but in circular meshes there are some defects on the sides. So, how can you sew up these sides? (Materials and code)
public class ConvertSpriteInMesh : MonoBehaviour
{
public Sprite sprite;
private MeshDraft meshDraft = new MeshDraft();
private Mesh mesh;
void Start()
{
GetComponent<MeshFilter>().mesh = SpriteToMesh(sprite);
SewingUp();
}
/// <summary>
/// Sewing up nets
/// </summary>
private void SewingUp()
{
mesh = GetComponent<MeshFilter>().mesh;
meshDraft = new MeshDraft(mesh);
int leftVertical = mesh.vertices.Length / 2; // getting the beginning of the left vertical of the mesh
int index = mesh.vertices.Length;
for (int i = 0; i < leftVertical - 1; i++)
{
meshDraft.AddQuad(mesh.vertices[i], mesh.vertices[i+1], mesh.vertices[i + leftVertical + 1],mesh.vertices[i+leftVertical],
index);
index += 4;
}
GetComponent<MeshFilter>().mesh = meshDraft.ToMesh(); // assign the resulting mesh
}
/// <summary>
/// Convert Sprite to Mesh
/// </summary>
/// <param name="_sprite"></param>
/// <returns></returns>
private Mesh SpriteToMesh(Sprite _sprite)
{
// declaring variables
Mesh mesh = new Mesh();
Vector3[] _verticles;
int[] _triangle;
// assigning values
_verticles = Array.ConvertAll(_sprite.vertices, i => (Vector3)i);
_triangle = Array.ConvertAll(_sprite.triangles, i => (int)i);
// changing the size of the array
Array.Resize(ref _verticles, _verticles.Length * 2);
Array.Resize(ref _triangle, _triangle.Length * 2);
// adding another side
for (int i = 0; i < _verticles.Length / 2; i++)
{
_verticles[_verticles.Length / 2 + i] = new Vector3(_verticles[i].x, _verticles[i].y, 0.5f);
}
for (int i = 0; i < _triangle.Length / 2; i++)
{
_triangle[_triangle.Length / 2 + i] = _triangle[i] + (_verticles.Length / 2);
}
// invert the second side
for(int i = _triangle.Length / 2; i < _triangle.Length; i += 3) {
var temp = _triangle[i];
_triangle[i] = _triangle[i + 1];
_triangle[i + 1] = temp;
}
// assigning the mesh
mesh.vertices = _verticles;
mesh.triangles = _triangle;
mesh.RecalculateBounds();
mesh.RecalculateNormals();
return mesh;
}
}
public partial class MeshDraft {
public string name = "";
public List<Vector3> vertices = new List<Vector3>();
public List<int> triangles = new List<int>();
public List<Vector3> normals = new List<Vector3>();
public List<Vector4> tangents = new List<Vector4>();
public List<Vector2> uv = new List<Vector2>();
public List<Vector2> uv2 = new List<Vector2>();
public List<Vector2> uv3 = new List<Vector2>();
public List<Vector2> uv4 = new List<Vector2>();
public List<Color> colors = new List<Color>();
public MeshDraft(Mesh mesh) {
name = mesh.name;
vertices.AddRange(mesh.vertices);
triangles.AddRange(mesh.triangles);
normals.AddRange(mesh.normals);
tangents.AddRange(mesh.tangents);
uv.AddRange(mesh.uv);
uv2.AddRange(mesh.uv2);
uv3.AddRange(mesh.uv3);
uv4.AddRange(mesh.uv4);
colors.AddRange(mesh.colors);
}
public void AddQuad(Vector3 v0, Vector3 v1, Vector3 v2, Vector3 v3, int index, Color color = default(Color)) {
vertices.Add(v0);
vertices.Add(v1);
vertices.Add(v2);
vertices.Add(v3);
Vector3 normal0 = Vector3.Cross(v2 - v1, v3 - v1).normalized;
Vector3 normal1 = Vector3.Cross(v1 - v0, v2 - v0).normalized;
normals.Add(normal0);
normals.Add(normal0);
normals.Add(normal1);
normals.Add(normal1);
colors.Add(color);
colors.Add(color);
colors.Add(color);
colors.Add(color);
triangles.Add(index);
triangles.Add(index + 1);
triangles.Add(index + 2);
triangles.Add(index);
triangles.Add(index + 2);
triangles.Add(index + 3);
}
public Mesh ToMesh() {
var mesh = new Mesh { name = name };
mesh.SetVertices(vertices);
mesh.SetTriangles(triangles, 0);
mesh.SetNormals(normals);
mesh.SetTangents(tangents);
mesh.SetUVs(0, uv);
mesh.SetUVs(1, uv2);
mesh.SetUVs(2, uv3);
mesh.SetUVs(3, uv4);
mesh.SetColors(colors);
return mesh;
}
Successful stitching (screen)
Bad stitching (screen)
I was given an answer on another forum, who is interested, I will leave a link here - https://www.cyberforum.ru/unity/thread2823987.html
This is a c# script for unity that is supposed to (onClick) and (onRelease) store the X and Y position of the cursor as floats, assign those to an array of [2], calculate the magnitude between the two points...
And here's where I'm stuck
I need to save those values into a list or array that I can print ToString() for debugging, as well as make those individual coordinates still accessible to the program.
Ideally I want to store values formatted like this:
listOfSavedCoordinates
{
[0] {{X1 , Y1}, {X2 , Y2} , {Magnitude}}
}
And to be able to access them by referencing the index of the list, then the jagged array's indexes.
Here's my who script so far:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClickDrag : MonoBehaviour
{
public class Coordinate
{
public static float X { get => Input.mousePosition.x; }
public static float Y { get => Input.mousePosition.y; }
public static float[] XY1 { get; set; }
public static float[] XY2 { get; set; }
public static float XY3 { get; set; }
}
public class Action
{
public static float[] XY1 { get; set; }
public static float[] XY2 { get; set; }
public static float[] Magnitude { get; set; }
}
[HideInInspector] public float X1;
[HideInInspector] public float Y1;
[HideInInspector] public float X2;
[HideInInspector] public float Y2;
public static float Magnitude;
//The list I want to save my coordinates and magnitudes to
List<float[,]> listOfSavedCoordinates = new List<float[,]>();
public static float CalculateMagnitude(float X2, float X1, float Y2, float Y1)
{//calculates the distance between 2 X,Y points. Called in OnRelease()
float Xsqr = (X2 - X1) * (X2 - X1);
float Ysqr = (Y2 - Y1) * (Y2 - Y1);
float XYsqr = Xsqr + Ysqr;
float magnitude = Mathf.Sqrt(XYsqr);
return magnitude;
}
private void SaveCoordsAndMag(float X1, float Y1, float X2, float Y2, float M)
{//saves action coordinates and magnitude to a list. Called in OnRelease()
Action.XY1 = new float[2] { X1, Y1 };
Action.XY2 = new float[2] { X2, Y2 };
Action.Magnitude = new float[1] { M } ;
listOfSavedCoordinates.Add(new float[3, 1] { { Action.XY1 }, { Action.XY2 }, { Action.Magnitude } });
//STACKOVERFLOW: This is the method I want to use to save the elements to my list.
//the problem is that adding the arrays requires an array initializer even though the values are already arrays,
//so initializing them makes the array expect a float.
//Please help thank you
}
// Use this for initialization
void Start()
{
Debug.Log("Game Start!");
Debug.Log("Click and drag the mouse to create vectors");
Debug.Log("Press M to show previous vectors");
}
// Update is called once per frame
void Update()
{
//Inputs
bool onClick = Input.GetKeyDown(KeyCode.Mouse0);
bool onDrag = Input.GetKey(KeyCode.Mouse0);
bool onRelease = Input.GetKeyUp(KeyCode.Mouse0);
if (onClick == true)
{//Coordinates for the start point
X1 = Coordinate.X;
Y1 = Coordinate.Y;
Debug.Log("Action Start!");
Debug.Log(X1 + " , " + Y1);
}
if (onDrag == true)
{//Coordinates of the current mouse position
float X3 = Coordinate.X;
float Y3 = Coordinate.Y;
Debug.Log("Action Charging! " + X3 + " , " + Y3);
}
if (onRelease == true)
{//Coordinates of the final point
X2 = Coordinate.X;
Y2 = Coordinate.Y;
Debug.Log("Action Released!");
Debug.Log(X2 + " , " + Y2);
Magnitude = CalculateMagnitude(X2, X1, Y2, Y1);
Debug.Log("The magnitude is " + Magnitude);
SaveCoordsAndMag(X1, Y1, X2, Y2, Magnitude);
Debug.LogWarning(listOfSavedCoordinates.Count + " Actions Saved.");
}
if (Input.GetKeyDown(KeyCode.M) == true)
{
int xy1 = 0;
int xy2 = 1;
int mag = 2;
listOfSavedCoordinates.ToArray();
Debug.LogWarning(
listOfSavedCoordinates[xy1].ToString()
+ ','
+ listOfSavedCoordinates[xy2].ToString()
+ " ---> "
+ listOfSavedCoordinates[mag].ToString()
);
xy1 = xy1 + 3;
xy2 = xy1 + 1;
mag = xy2 + 1;
//STACKOVERFLOW: This is how I'd like to log my list's elements.
}
}
}
I figured out my issue. I needed to give my Action class's float array variables their index reference to get an actual value.
listOfSavedCoordinates.Add(new float[3,2] { { Action.XY1[0], Action.XY1[1] }, { Action.XY2[0], Action.XY2[1] }, { Action.Magnitude[0], listOfSavedCoordinates.Count } });
You should be doing something like this:
List<Coordinate> lstCoords = new List<Coordinate>();
// long handing this for understanding
Coordinate coord = new Coordinate();
// assign strongly typed vars in object to values here
coord.X1 = X1;
coord.X2 = X2;
coord.Y1 = Y1;
coord.Y2 = Y2;
// add the object to the list
lstCoords.Add(coord);
Then accessing each item would be something like this:
foreach (Coordinate coord in lstCoords)
{
console.writeline( coord.X1, coord.X2, coord.y1, coord.y2);
}
You can also search for a specific coordinate in the list, too.
But really, you want to use an list of objects vs trying to store data without strongly typed names.
I would suggest you to try this:
public class ClickDrag : MonoBehaviour
{
List<Coordinates> coordinatesList;
Vector2 startPos;
// Use this for initialization
void Start()
{
coordinatesList = new List<Coordinates>();
// Some other code
}
void Update()
{
if(Input.GetMouseButtonDown(0))
{
startPos = Input.mousePosition;
}
else if(Input.GetMouseButtonUp(0))
{
// Here create the new coordinates
Coordinates newCoordinates = new Coordinates(startPos, Input.mousePosition);
coordinatesList.Add(newCoordinates);
}
// Note here you don't need "== true", cause the method will already give you a boolean
if(Input.GetKeyDown(KeyCode.M))
{
DebugList();
}
}
private DebugList()
{
Debug.Log("listOfSavedCoordinates: ");
for(int i=0; i<coordinatesList.Count; i++)
Debug.Log("["+i+"] " + coordinatesList[i].PrintCoordinates());
}
}
public class Coordinates
{
private Vector2 startPos;
private Vector2 endPos;
private float magnitude;
public Coordinates(Vector2 startPos, Vector2 endPos)
{
this.startPos = startPos;
this.endPos = endPos;
magnitude = Vector2.Distance(startPos, endPos);
}
public PrintCoordinates()
{
return ("{" + startPos + "}, {" + endPos + "}, " + magnitude);
}
}
Are there any examples of pedestrian modelling in repast simphony? I am novice in repast and was trying to model a simple pedestrian movement simulation. Any pointers to useful resources/ examples?
Andrew Crook's blog GIS and Agent-Based Modeling (http://www.gisagents.org/) has lots of interesting links to pedestrian models. I think there are even some specific to Repast.
Repast isn't the best for open libraries, but I've had some luck searching GitHub. Here's a basic ped agent I built once, you'll have to build a context with a scheduler class to call the pedestrians:
context:
public class RoadBuilder extends DefaultContext<Object> implements ContextBuilder<Object> {
context.setId("driving1");
ContinuousSpaceFactory spaceFactory =
ContinuousSpaceFactoryFinder.createContinuousSpaceFactory(null);
ContinuousSpace<Object> space =
spaceFactory.createContinuousSpace("space",context, new SimpleCartesianAdder<Object>(),
new StrictBorders(), roadL, worldW);
clock = RunEnvironment.getInstance().getCurrentSchedule();
flowSource = new Scheduler();
context.add(flowSource);
return context;
}
the scheduler:
public class Scheduler {
static ArrayList<Ped> allPeds;
#ScheduledMethod(start = 1, interval = 1, priority = 1)
public void doStuff() {
Ped addedPed = addPed(1);
allPeds.add(addedPed);
for (Ped a : allPeds) {
a.calc();}
for (Ped b : allPeds) {
b.walk();}
public Ped addPed(int direction) {
Context<Object> context = ContextUtils.getContext(this);
ContinuousSpace<Object> space = (ContinuousSpace<Object>) context.getProjection("space");
Ped newPed = new Ped(space,direction);
context.add(newPed);
space.moveTo(newPed,xPlacement,yPlacement);
newPed.myLoc = space.getLocation(newPed);
return(newPed);
}
The pedestrians - This is based on a "generalized force model" (source: Simulating Dynamical Features of Escape Panic - Helbing, Farkas, and Vicsek - https://arxiv.org/pdf/cond-mat/0009448.pdf)
and here's the pedestrian class
public class Ped {
private ContinuousSpace<Object> space;
private List<Double> forcesX, forcesY;
private NdPoint endPt;
private Random rnd = new Random();
private int age;
private double endPtDist, endPtTheta, critGap;
private double side = RoadBuilder.sidewalk;
private double wS, etaS, wV, etaV, sigR; //errors
private double m, horiz, A, B, k, r; //interactive force constants (accT is also)
public NdPoint myLoc, destination;
public double[] v, dv, newV;
public double xTime, accT, maxV, xLoc, yLoc;
public int dir; // dir = 1 walks up, -1 walks down
public void calc() {
myLoc = space.getLocation(this);
dv = accel(myLoc,dir,destination);
newV = sumV(v,dv);
newV = limitV(newV);
}
public void walk() {
v = newV;
move(myLoc,v);
}
public double[] accel(NdPoint location, int direct, NdPoint endPt) {
forcesX = new ArrayList<Double>();
forcesY = new ArrayList<Double>();
double xF, yF;
double[] acc;
xF = yF = 0;
//calculate heading to endpoint
endPtDist = space.getDistance(location, endPt);
double endPtDelX = endPt.getX()-location.getX();
endPtTheta = FastMath.asin((double)direct*endPtDelX/endPtDist);
if (direct == -1) {
endPtTheta += Math.PI;}
//calculate motive force
Double motFx = (maxV*Math.sin(endPtTheta) - v[0])/accT;
Double motFy = (maxV*Math.cos(endPtTheta) - v[1])/accT;
forcesX.add(motFx);
forcesY.add(motFy);
//calculate interactive forces
//TODO: write code to make a threshold for interaction instead of the arbitrary horizon
for (Ped a : Scheduler.allPeds) {
if (a != this) {
NdPoint otherLoc = space.getLocation(a);
double otherY = otherLoc.getY();
double visible = Math.signum((double)dir*(otherY-yLoc));
if (visible == 1) { //peds only affected by those in front of them
double absDist = space.getDistance(location, otherLoc);
if (absDist < horiz) {
double delX = location.getX()-otherLoc.getX();
double delY = location.getY()-otherLoc.getY();
double delXabs = Math.abs(delX);
double signFx = Math.signum(delX);
double signFy = Math.signum(delY);
double theta = FastMath.asin(delXabs/absDist);
double rij = r + a.r;
Double interFx = signFx*A*Math.exp((rij-absDist)/B)*Math.sin(theta)/m;
Double interFy = signFy*A*Math.exp((rij-absDist)/B)*Math.cos(theta)/m;
forcesX.add(interFx);
forcesY.add(interFy);}}}}
//sum all forces
for (Double b : forcesX) {
xF += b;}
for (Double c : forcesY) {
yF += c;}
acc = new double[] {xF, yF};
return acc;
}
public void move(NdPoint loc, double[] displacement) {
double[] zero = new double[] {0,0};
double yl = loc.getY();
if (displacement != zero) {
space.moveByDisplacement(this,displacement);
myLoc = space.getLocation(this);}
}
public double[] limitV(double[] input) {
double totalV, norm;
if (this.dir == 1) {
if (input[1] < 0) {
input[1] = 0;}}
else {
if (input[1] > 0) {
input[1] = 0;}}
totalV = Math.sqrt(input[0]*input[0] + input[1]*input[1]);
if (totalV > maxV) {
norm = maxV/totalV;
input[0] = input[0]*norm;
input[1] = input[1]*norm;}
return input;
}
public double[] sumV(double[] a, double[] b) {
double[] c = new double[2];
for (int i = 0; i < 2; i++) {
c[i] = a[i] + b[i];}
return c;
}
public Ped(ContinuousSpace<Object> contextSpace, int direction) {
space = contextSpace;
maxV = rnd.nextGaussian() * UserPanel.pedVsd + UserPanel.pedVavg;
dir = direction; // 1 moves up, -1 moves down
v = new double[] {0,(double)dir*.5*maxV};
age = 0;
//3-circle variables - from Helbing, et al (2000) [r from Rouphail et al 1998]
accT = 0.5/UserPanel.tStep; //acceleration time
m = 80; //avg ped mass in kg
horiz = 5/RoadBuilder.spaceScale; //distance at which peds affect each other
A = 2000*UserPanel.tStep*UserPanel.tStep/RoadBuilder.spaceScale; //ped interaction constant (kg*space units/time units^2)
B = 0.08/RoadBuilder.spaceScale; //ped distance interaction constant (space units)
k = 120000*UserPanel.tStep*UserPanel.tStep; //wall force constant
r = 0.275/RoadBuilder.spaceScale; //ped radius (space units)
}
}
How to add values to DataPoint which to be plotted in case I do not know number of possible entries?
DataPoint[] db = new DataPoint[]{
new DataPoint(5,4),
new DataPoint(2,4),
new DataPoint(4,4),
new DataPoint(9,0),
new DataPoint(0,3)} ;
PointsGraphSeries<DataPoint> series = new PointsGraphSeries<DataPoint>(db) ;
Make a call to this method before you add DataPoint array to LineGraphSeries.
private void generateDataForGraph() {
int size = Amount.size();
values = new DataPoint[size];
for (int i=0; i<size; i++) {
Integer xi = Integer.parseInt(Dates.get(i));
Integer yi = Integer.parseInt(Amount.get(i));
DataPoint v = new DataPoint(xi, yi);
values[i] = v;
}
series = new LineGraphSeries<DataPoint>(values);
graph2.addSeries(series);
}
I have a test program that does not give consistent results for Accord.Net K-Means.
I am enclosing a reproducible test program that can be run in Visual Studio 2013.
The program is a console application and to reproduce the results you need to reference:
Accord.MachineLearning
Accord.Statistics,
from the Accord.Net 2.15 library.
When I run the program several times I get different results each time. The program uses the classic Fisher Iris dataset. The dataset has 150 rows, and I split the data into 120 rows of training data and 30 rows of testing data.
When I run the program I might get 26 out of 30 classified correctly. Running it again may produce 2 out of 30 correct.
For example:
Number correct: 2 out of 30
FScore: NaN
Precision: 0
True Positives: 0
False Positives: 9
True Negatives: 9
False Negatives: 12
Accuracy: 0.3
Standard Error: 0.107268513868515
Variance: 0.0115065340675597
I am wondering if I am correctly using Accord.Net. Any help will be greatly appreciated.
My program is:
using System;
using System.IO;
using System.Net;
using Accord.MachineLearning;
using Accord.Statistics.Analysis;
namespace K_Keans {
#region K_Means
public static class K_Means {
private static KMeans kmeans;
#region DowloadIrisData
private static void DowloadIrisData(out double[][] predictors, out int[] targets) {
using (var fileDownloader = new WebClient()) {
// http://www.math.uah.edu/stat/data/Fisher.html
// The dataset gives Ronald Fisher's measurements of type, petal width (PW), petal length (PL),
// sepal width (SW), and sepal length (SL) for a sample of 150 irises, measured in millimeters.
// Type 0 is Setosa; type 1 is Verginica; and type 2 is Versicolor.
const string webLocation = #"http://www.math.uah.edu/stat/data/Fisher.csv";
const string fileName = #"c:\Temp\iris.csv";
fileDownloader.DownloadFile(webLocation, fileName);
var s = File.ReadAllText(fileName);
var sarray = s.Split('\n');
var nrows = sarray.Length - 2;
var ncols = sarray[0].Split(',').Length;
predictors = new double[nrows][];
targets = new int[nrows];
for (var j=1; j<=nrows; j++) {
predictors[j-1] = new double[ncols-1];
var line = sarray[j].Split(',');
for (var k = 1; k < ncols; k++) {
targets[j-1] = Convert.ToInt32(line[0]);
predictors[j-1][k-1] = Convert.ToDouble(line[k]);
}
}
}
}
#endregion
#region IrisData
public static void IrisData(out double[][] trainingData, out int[] expectedTrainingTargets,
out double[][] testingData, out int[] expectedTestingTargets) {
double[][] predictors;
int[] targets;
DowloadIrisData(out predictors, out targets);
var nRows = predictors.Length;
var nCols = predictors[0].Length;
var nRowsTesting = Convert.ToInt32(0.2*nRows);
var nRowsTraining = nRows - nRowsTesting;
trainingData = new double[nRowsTraining][];
expectedTrainingTargets = new int[nRowsTraining];
for (var k = 0; k < nRowsTraining; k++) {
trainingData[k] = new double[nCols];
Array.Copy(predictors[k], trainingData[k], nCols);
expectedTrainingTargets[k] = targets[k];
}
testingData = new double[nRowsTesting][];
expectedTestingTargets = new int[nRowsTesting];
for (var k = 0; k < nRowsTesting; k++) {
testingData[k] = new double[nCols];
Array.Copy(predictors[nRows-nRowsTesting+k], testingData[k], nCols);
expectedTestingTargets[k] = targets[nRows-nRowsTesting+k];
}
}
#endregion
#region Train
public static void Train(double[][] trainingData, out int[] predicted) {
kmeans = new KMeans(3) {
Tolerance = 1e-5,
ComputeInformation = true
};
predicted = kmeans.Compute(trainingData);
}
#endregion
#region Test
public static void Test(double[][] testingData, out int[] predicted) {
var nRowsTesting = testingData.Length;
predicted = new int[nRowsTesting];
for (var k = 0; k < nRowsTesting; k++) {
predicted[k] = kmeans.Clusters.Nearest(testingData[k]);
}
}
#endregion
}
#endregion
class Program {
static void Main(string[] args) {
double[][] trainingData, testingData;
int[] expectedTrainingTargets, expectedTestingTargets;
K_Means.IrisData(out trainingData, out expectedTrainingTargets, out testingData, out expectedTestingTargets);
int[] predictedTrainingTargets;
K_Means.Train(trainingData, out predictedTrainingTargets);
int[] predictedTestingTargets;
K_Means.Test(testingData, out predictedTestingTargets);
var confusionMatrix = new ConfusionMatrix(predictedTestingTargets, expectedTestingTargets);
var nCorrect = 0;
var nRows = expectedTestingTargets.Length;
for (var k=0; k<nRows; k++) {
if (predictedTestingTargets[k] == expectedTestingTargets[k]) { nCorrect++; }
}
Console.WriteLine(" Number correct: {0} out of {1}", nCorrect, nRows);
Console.WriteLine(" FScore: {0}", confusionMatrix.FScore);
Console.WriteLine(" Precision: {0}", confusionMatrix.Precision);
Console.WriteLine(" True Positives: {0}", confusionMatrix.TruePositives);
Console.WriteLine("False Positives: {0}", confusionMatrix.FalsePositives);
Console.WriteLine(" True Negatives: {0}", confusionMatrix.TrueNegatives);
Console.WriteLine("False Negatives: {0}", confusionMatrix.FalseNegatives);
Console.WriteLine(" Accuracy: {0}", confusionMatrix.Accuracy);
Console.WriteLine(" Standard Error: {0}", confusionMatrix.StandardError);
Console.WriteLine(" Variance: {0}", confusionMatrix.Variance);
Console.WriteLine(" ");
Console.WriteLine("Hit enter to exit.");
Console.ReadKey();
}
}
}
K-means is not a classification algorithm.
But it is a randomized algorithm, so it's not surprise you get different results every time.
Now since it is randomized the labels used by k-means are random, too.
So 2 out of 30 correct may be the same as 28 out of 30 correct (just the labels shuffled).
Run it again, and it may yield the same clusters, but with the "labels" all mixed up. (In fact, it doesn't know about iris species. It labels objects 0,1,2; not "iris setosa")