[SciPy-user] About Genetic Algorithms

Robert Kern robert.kern at gmail.com
Wed May 23 14:58:16 EDT 2007


Gabriel Gellner wrote:
> I think I have ported the GA module to numpy, though as I am not a
> regular user of GA algorithms I have only made sure that my changes
> work with the included example.
> 
> Before I figure out how to make a multi-file patch with subversion, I
> have some general questions to make sure I did everything correctly:
> 
> The major stumbling block was that ga used
> import scipy.stats as rv
> extensively, these functions seem to have been gutted in the new
> scipy.
> 
> Firstly stats.choice() is a function that is used extensively (to
> uniformly sample from a given sequence) which I failed to find the
> equivalent in numpy or scipy. Instead I wrote:
> 
> def choice(seq):
>     hi = len(seq) - 1
>     rindex = numpy.random.random_integers(0, hi)
>     # this will raise an exception if len(seq) == 0, which seems
>     # correct to me
>     return seq[rindex] 
> 
> Does this make sense? I looked at the old code in scipy, and it seemed
> a mess (and more general) so I didn't spend much time on it. If the
> above is incorrect, or if there is a better port, please tell me, I
> will fix/port as needed.

randint(0, len(seq)) is clearer, but yes, that's fine.

> Another problem was that modern numpy doesn't let you change the
> random number algorithm, there is no easy way around this (would there
> be and reason to port the 3 other algorithms from old scipy to the
> modern pyrex version? I could try if this is a good thing to do).
> Instead I just ignore the alg argument to galg.

It would be nice, but not really important. Just remove the alg argument.

> Also it uses lines like:
> used_seed = rv.initial_seed()
> 
> which I have changed to
> used_seed = numpy.random.get_state()[2]
> 
> But I find it hard to tell if this correct, the documentation is
> sparse (if no one can tell me quickly I will just check that the seeds
> agree . . . any tips would be helpful mind you). 

It isn't correct. If you are dealing with controlled random number streams, you
need to instantiate a numpy.random.RandomState() instance yourself and call its
methods instead of relying on the global instance and the functions in
numpy.random. For this case, just grab the whole state with get_state() and
store that. It's not a seed, per se, but resetting the state with set_state()
will perform the same purpose that rv.initial_seed() was stored.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco



More information about the SciPy-User mailing list