Skip to content
This repository has been archived by the owner on Nov 19, 2020. It is now read-only.

ClusterCollection doesn't implement IEnumerable properly (runtime error) #325

Closed
pengowray opened this issue Oct 18, 2016 · 3 comments
Closed

Comments

@pengowray
Copy link

Can ClusterCollection be fixed so IEnumerable works as expected?

When you have a cluster collection, e.g.
var clusters = new KMeans(3).Learn(observations);

and you want to iterate through them like this:

foreach (var cluster in clusters) { 
    // ... 
}

You receive the following error:

 Exception: System.InvalidCastException: Unable to cast object of type 'SZArrayEnumerator' to type 'System.Collections.Generic.IEnumerator`1[Accord.MachineLearning.KMeansClusterCollection+KMeansCluster]'.

Instead you need to use an old school for loop:

for (int i = 0; i < clusters.Count; i++) {
     var cluster = clusters[i];
     // ...
}

Can this be fixed?


Test code:

using Accord.MachineLearning;
using System;

// ...

double[][] observations =
{
    new double[] { -5, -2, -1 },
    new double[] { -5, -5, -6 },
    new double[] {  2,  1,  1 },
    new double[] {  1,  1,  2 },
    new double[] {  1,  2,  2 },
    new double[] {  3,  1,  2 },
    new double[] { 11,  5,  4 },
    new double[] { 15,  5,  6 },
    new double[] { 10,  5,  6 },
};

KMeans kmeans = new KMeans(3);
var clusters = kmeans.Learn(observations);

// OK
for (int i = 0; i < clusters.Count; i++) {
    var cluster = clusters[i];
    Console.WriteLine("Cluster {0}: {1:0.00}%", cluster.Index, cluster.Proportion);
}

// ERROR
foreach (var cluster in clusters) {
    Console.WriteLine("Cluster {0}: {1:0.00}%", cluster.Index, cluster.Proportion);
}
@cesarsouza
Copy link
Member

Thanks for opening the issue! I have just committed a fix to the development branch.

@pengowray
Copy link
Author

Excellent! Thanks for the fast response.

@cesarsouza
Copy link
Member

Integrated in release 3.4.0.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants