Problems? Is your data what you think it is? PerlMonks

### Comment on

 Need Help??

Indeed, there were a number of other parameters that could be tweaked, and by doing so, I was able to get better results than that.

However, in the end, it turns out there are some special properties of your problem that allow much simpler and more effective solutions. Namely, the fact that your data points are one-dimensional. (I'm assuming they are.)

It means, for example, that (1 3),(2 4) is never an optimal clustering. Neither is (1 2),(1 2).

From these, we can define the following constraints on clusters:

1. clusters are simply segments within the ordered data set.
2. all repetitions of a number must be kept together.

In the following solution, I'm using variance as a measure of the "coherence" or "binding strength" or whatever you want to call it within each cluster. You could use other measures; I wouldn't be surprised if variance doesn't necessarily give the best results. I've seen discussions of clustering that talk about maximizing variance between clusters, in addition to minimizing it within clusters. I have my doubts that that would help in a simple one-dimensional problem like this one.

I've used Statistics::Lite for a variance function; but you could easily substitute any other module of your preference.

```
use Statistics::Lite;
use strict;
use warnings;

my @d =
# I assume the order as given in the OP is not important:
sort { \$a <=> \$b }
( 12, 14, 16, 18, 18, 20, 20, 20, 20, 20, 20, 20, 22, 24, 24, 24, 24,
+30, 30, 30, 32, 35, 35, 35, 35, 35, 35, 35, 36, 40, 42, 46, 48, 48, 5
+0, 50, 50, 50, 54, 54, 55, 56, 56, 58, 58, 60, 60, 60, 60, 63, 64, 67
+, 67, 68, 70, 70, 76, 80, 86, 86, 86, 90, 90, 99, 100, 100, 100, 100,
+ 104, 105, 128, 150, 150, 154, 169, 190, 200, 200, 200, 250, 280, 291
+, 291, 300, 325, 325, 330, 450, 460, 550, 566, 600, 700, 750, 770, 95
+0, 1226, 1250, 2000, 15, 22, 24 );

my %count;
\$count{\$_}++ for @d;

my @e = sort { \$a <=> \$b } keys %count;

# an individual is an array of arrays of nums.
# each element of the (top-level) array represents a cluster.
# the order of all the numbers, if you were to concat all the arrays,
# is strictly numeric ascending.
# in a 1-d space only, it never makes sense to cluster the
# numbers (1,2,3,4) as (1,3), (2,4).
# the only mutation possible is shifting a number off the
# beggining of one array and pushing it onto the previous array.
# (and the other way).

sub random_bipartition
{
my( \$min_size, \$ar ) = @_;
my \$sel = @\$ar - (2*\$min_size);
my \$p = \$min_size + int rand( \$sel );
\$p > \$#{\$ar}
? ( [ @{\$ar} ], [ ] )
: ( [ @{\$ar}[0 .. \$p] ], [ @{\$ar}[\$p+1 .. \$#{\$ar}] ] )
}

sub Ind::new_randomized
{
my \$nc = shift;
my \$n = \$nc <= 2 ? 1 : \$nc <= 4 ? 2 : \$nc <= 8 ? 3 : 4; # 16 max

my @a = ( \@e );
@a = map { random_bipartition( 1<<\$n, \$_ ) } @a while \$n--; # deep
+ magic :-)

my \$i = 0;
while ( @a > \$nc )
{
unshift @{\$a[\$i+1]}, @{\$a[\$i]};
splice @a, \$i, 1;
\$i++;
}

\@a
}

sub Ind::clone
{
my \$ind = shift;
[ map { [@\$_] } @\$ind ]
}

sub Ind::as_string
{
my \$ind = shift;
my \$varsum;
my \$s;
for my \$cl ( @\$ind )
{
my \$var = 0;
if ( @\$cl )
{
my @d;
push @d, (\$_) x \$count{\$_} for @\$cl;
\$var = int( Statistics::Lite::variance(@d)||0 );
\$varsum += \$var;
}
\$s .= "\$var ( @\$cl )\n";
}
\$s .= "Total variance: \$varsum\n";
\$s
}

sub Ind::fitness
{
my \$ind = shift;
my \$sum = 0;
my \$empty = 0;
for my \$cl ( @\$ind )
{
if ( @\$cl )
{
my @d;
push @d, (\$_) x \$count{\$_} for @\$cl;
\$sum += (Statistics::Lite::variance(@d)||0);
}
else
{
\$empty++;
}
}

# harshly penalize individuals with the wrong number (too few) of
+clusters:
\$sum *= ( 1 + \$empty / 10 );

1_000_000 - \$sum # convert to Larger Is Better
}

sub Ind::mutate
{
my( \$ind, \$n ) = @_;
\$n ||= 1;
my \$lo = int rand( @\$ind - 1);
if ( int rand 2 )
{
# up
my(\$to,\$from) = ( \$ind->[\$lo+1], \$ind->[\$lo] );
unshift @\$to, pop @\$from
while \$n-- && @\$from
}
else
{
# down
my(\$to,\$from) = ( \$ind->[\$lo], \$ind->[\$lo+1] );
push @\$to, shift @\$from
while \$n-- && @\$from
}
\$ind
}

# this clones an element of @pop
sub clone { [ \$_[0]->[0], Ind::clone(\$_[0]->[1]) ] }

sub do_run
{
my \$n_clusters = shift;

my @pop =
sort { \$b->[0] <=> \$a->[0] }
map { [ Ind::fitness(\$_), \$_ ] }
map { Ind::new_randomized(\$n_clusters) }
1 .. 60;

for my \$gen ( 1 .. 200 )
{
# kill the bottom 30:
splice @pop, @pop-30, 30;

# make 10 new ones:
push @pop,
map { [ Ind::fitness(\$_), \$_ ] }
map { Ind::new_randomized(\$n_clusters) }
1 .. 10;

# clone the top 20:
push @pop, map clone(\$_), @pop[0 .. 19];

# mutate the top 20:
for my \$e ( @pop[0 .. 19] )
{
Ind::mutate( \$e->[1], 1 + int rand 4 );
\$e->[0] = Ind::fitness( \$e->[1] );
}

# sort by fitness again:
@pop = sort { \$b->[0] <=> \$a->[0] } @pop;
}

\$pop[0][1] # best individual
}

for my \$nc ( 2 .. 8 )
{
print "\n\$nc Clusters:\n";
my \$winner = do_run( \$nc );
print Ind::as_string( \$winner ), "\n";
}
We're building the house of the future together.

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

• Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
• Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
• Read Where should I post X? if you're not absolutely sure you're posting in the right place.
• Posts may use any of the Perl Monks Approved HTML tags:
a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
• You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
 For: Use: & & < < > > [ [ ] ]
• Link using PerlMonks shortcuts! What shortcuts can I use for linking?

Create A New User
Chatterbox?
and a log crumbles through the grate...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (10)
As of 2017-07-25 15:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
I came, I saw, I ...

Results (374 votes). Check out past polls.