AI-Genetic
view release on metacpan or search on metacpan
for my $i (1 .. $gens) {
$self->sortPopulation;
$strSub->($self);
$self->{GENERATION}++;
$self->{SORTED} = 0;
last if $self->{TERM}->($self);
# my @f = $self->getFittest(10);
# for my $f (@f) {
# print STDERR " Fitness = ", $f->score, "..\n";
# print STDERR " Genes are: @{$f->genes}.\n";
# }
}
}
# sub sortIndividuals():
# This method takes as input an anon list of individuals, and returns
# another anon list of the same individuals but sorted in decreasing
sub sortPopulation {
my $self = shift;
return if $self->{SORTED};
$self->{PEOPLE} = $self->sortIndividuals($self->{PEOPLE});
$self->{SORTED} = 1;
}
# sub getFittest():
# This method returns the fittest individuals.
sub getFittest {
my ($self, $N) = @_;
$N ||= 1;
$N = 1 if $N < 1;
$N = @{$self->{PEOPLE}} if $N > @{$self->{PEOPLE}};
$self->sortPopulation;
my @r = @{$self->{PEOPLE}}[0 .. $N-1];
-fitness => \&fitnessFunc,
-type => 'bitvector',
-population => 500,
-crossover => 0.9,
-mutation => 0.01,
-terminate => \&terminateFunc,
);
$ga->init(10);
$ga->evolve('rouletteTwoPoint', 100);
print "Best score = ", $ga->getFittest->score, ".\n";
sub fitnessFunc {
my $genes = shift;
my $fitness;
# assign a number to $fitness based on the @$genes
# ...
return $fitness;
}
sub terminateFunc {
my $ga = shift;
# terminate if reached some threshold.
return 1 if $ga->getFittest->score > $THRESHOLD;
return 0;
}
=head1 DESCRIPTION
This module implements a Genetic Algorithm (GA) in pure Perl.
Other Perl modules that achieve the same thing (perhaps better,
perhaps worse) do exist. Please check CPAN. I mainly wrote this
module to satisfy my own needs, and to learn something about GAs
along the way.
The subroutine corresponding to the named strategy is called with one argument,
the AI::Genetic object. This subroutine is expected to alter the object itself.
=item o
If a termination subroutine is given, it is executed and the return value is
checked. Evolution terminates if this sub returns a true value.
=back
=item I<$ga>-E<gt>B<getFittest>(?I<N>?)
This returns the I<N> fittest individuals. If not specified,
I<N> defaults to 1. As a side effect, it sorts the population by
fitness score. The actual AI::Genetic::Individual objects are returned.
You can use the C<genes()> and C<score()> methods to get the genes and the
scores of the individuals. Please check L<AI::Genetic::Individual> for details.
=item I<$ga>-E<gt>B<sortPopulation>
This method sorts the population according to fitness function. The results
are cached for speed.
function will not be called, and the cached result is returned).
To help speed up your run times, you should pay special attention
to the design of your fitness function since this will be called once
for each unique individual in each generation. If you can shave off a
few clock cycles here and there, then it will be greatly magnified in
the total run time.
=head1 BUGS
I have tested this module quite a bit, and even used it to solve a
work-related problem successfully. But, if you think you found a bug
then please let me know, and I promise to look at it.
Also, if you have any requests, comments or suggestions, then feel
free to email me.
=head1 INSTALLATION
Either the usual:
Genetic/OpSelection.pm view on Meta::CPAN
my %s;
while ($num > keys %s) {
my $i = int rand @$pop;
$s{$i} = 1;
}
return map $pop->[$_], keys %s;
}
# sub topN():
# fittest N individuals.
# arguments are anon list of pop, and N (def = 1).
# return anon list of top N individuals.
sub topN {
my ($pop, $N) = @_;
$N ||= 1;
# hmm .. are inputs already sorted?
return [(sort {$b->score <=> $a->score}
Genetic/OpSelection.pm view on Meta::CPAN
=item B<rouletteUnique>(?I<N>?)
This method selects I<N> unique individuals. I<N> defaults to 2. Any individual
can be selected only once per call to this method.
=back
=item Tournament
Here, I<N> individuals are randomly selected, and the fittest one of
them is returned. The following method is defined:
=over
=item B<tournament>(?I<N>?)
I<N> defaults to 2. Note that only one individual is returned per call to this
method.
=back
Genetic/OpSelection.pm view on Meta::CPAN
The following method is defined:
=over
=item B<random>(?I<N>?)
I<N> defaults to 1.
=back
=item Fittest
Here, the fittest I<N> individuals of the whole population are returned.
The following method is defined:
=over
=item B<topN>(?I<N>?)
I<N> defaults to 1.
=back
Changes
Genetic.pm
Makefile.PL
MANIFEST
README
test.pl
-fitness => \&fitnessFunc,
-type => 'bitvector',
-population => 500,
-crossover => 0.9,
-mutation => 0.01,
-terminate => \&terminateFunc,
);
$ga->init(10);
$ga->evolve('rouletteTwoPoint', 100);
print "Best score = ", $ga->getFittest->score, ".\n";
sub fitnessFunc {
my $genes = shift;
my $fitness;
# assign a number to $fitness based on the @$genes
# ...
return $fitness;
}
sub terminateFunc {
my $ga = shift;
# terminate if reached some threshold.
return 1 if $ga->getFittest->score > $THRESHOLD;
return 0;
}
DESCRIPTION
This module implements a Genetic Algorithm (GA) in pure Perl. Other Perl
modules that achieve the same thing (perhaps better, perhaps worse) do
exist. Please check CPAN. I mainly wrote this module to satisfy my own
needs, and to learn something about GAs along the way.
PLEASE NOTE: As of v0.02, AI::Genetic has been re-written from scratch
fitnesses.
o The subroutine corresponding to the named strategy is called
with one argument, the AI::Genetic object. This subroutine is
expected to alter the object itself.
o If a termination subroutine is given, it is executed and the
return value is checked. Evolution terminates if this sub
returns a true value.
*$ga*->getFittest(?*N*?)
This returns the *N* fittest individuals. If not specified, *N*
defaults to 1. As a side effect, it sorts the population by fitness
score. The actual AI::Genetic::Individual objects are returned. You
can use the "genes()" and "score()" methods to get the genes and the
scores of the individuals. Please check the AI::Genetic::Individual
manpage for details.
*$ga*->sortPopulation
This method sorts the population according to fitness function. The
results are cached for speed.
same individual more than once, then the fitness function will not be
called, and the cached result is returned).
To help speed up your run times, you should pay special attention to the
design of your fitness function since this will be called once for each
unique individual in each generation. If you can shave off a few clock
cycles here and there, then it will be greatly magnified in the total
run time.
BUGS
I have tested this module quite a bit, and even used it to solve a
work-related problem successfully. But, if you think you found a bug
then please let me know, and I promise to look at it.
Also, if you have any requests, comments or suggestions, then feel free
to email me.
INSTALLATION
Either the usual:
perl Makefile.PL
# Before `make install' is performed this script should be runnable with
# `make test'. After `make install' it should work as `perl test.pl'
#########################
# change 'tests => 1' to 'tests => last_test_to_print';
use Test;
BEGIN { plan tests => 1 };
use AI::Genetic;
ok(1); # If we made it this far, we're ok.
#########################
# Insert your test code below, the Test module is use()ed here so read
# its man page ( perldoc Test ) for help writing this test script.
( run in 0.304 second using v1.01-cache-2.11-cpan-3cd7ad12f66 )