numpyrandompermutationgaussianautocorrelation

print multiple random permutations


I am trying to do multiple permutations. From code:

# generate random Gaussian values
from numpy.random import seed
from numpy.random import randn
# seed random number generator
seed(1)
# generate some Gaussian values
values = randn(100)
print(values)

But now I would like to generate, for example, 20 permutations (of values). With code:

import numpy as np
import random
from itertools import permutations
result = np.random.permutation(values)
print(result)

I can only observe one permutation (or "manually" get others). I wish I had many permutations (20 or more) and so automatically calculate the Durbin-Watson statistic for each permutation (from values).

from statsmodels.stats.stattools import durbin_watson
sm.stats.durbin_watson(np.random.permutation(values))

How can I do?


Solution

  • To get 20 permutations out of some collection, intialize the itertools.permutations iterator and then use next() to take the first twenty:

    import numpy as np
    import itertools as it
    
    x = np.random.random(100)  # 100 random floats
    p = it.permutations(x)  # an iterator which produces permutations (DON'T TRY TO CALCULATE ALL OF THEM)
    first_twenty_permutations = [next(p) for _ in range(20)]
    

    Of course, these won't be random permutations (i.e., they are calculated in an organized manner, try with it.permutations("abcdef") and you'll see what I mean). If you need random permutations, you can use np.random.permutation much in the same way:

    [np.random.permutation(x) for _ in range(20)]
    

    To then calculate the Durbin Watson statistic:

    permutations = np.array([np.random.permutation(x) for _ in range(20)])
    np.apply_along_axis(durbin_watson, axis=1, arr=permutations)