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

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

@pengowray

Description

@pengowray

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);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions