development

동일한 임의의 numpy 배열을 일관되게 생성

big-blog 2020. 9. 17. 08:24
반응형

동일한 임의의 numpy 배열을 일관되게 생성


다른 개발자가 -1,0 또는 1의 값으로 np 배열 (100,2000)을 반환하는 코드 조각을 완료하기를 기다리고 있습니다.

그 동안 나는 개발 및 테스트를 앞당길 수 있도록 동일한 특성의 배열을 무작위로 만들고 싶습니다. 문제는 무작위로 생성 된이 배열이 매번 동일하기를 원하므로 프로세스를 다시 실행할 때마다 값을 계속 변경하는 배열에 대해 테스트하지 않습니다.

이렇게 내 배열을 만들 수 있지만 매번 동일하게 만들 수있는 방법이 있습니다. 나는 물건을 피클하고 피클을 풀 수 있지만 다른 방법이 있는지 궁금합니다.

r = np.random.randint(3, size=(100, 2000)) - 1

난수 생성기에 고정 값을 지정하기 만하면됩니다. 예 :

numpy.random.seed(42)

이렇게하면 항상 동일한 난수 시퀀스를 얻을 수 있습니다.


numpy.random.RandomState()선택한 시드로 자신의 인스턴스를 만듭니다 . numpy.random.seed()자신의 RandomState인스턴스 를 전달할 수없는 유연하지 않은 라이브러리를 해결 하는 경우를 제외하고는 사용하지 마십시오 .

[~]
|1> from numpy.random import RandomState

[~]
|2> prng = RandomState(1234567890)

[~]
|3> prng.randint(-1, 2, size=10)
array([ 1,  1, -1,  0,  0, -1,  1,  0, -1, -1])

[~]
|4> prng2 = RandomState(1234567890)

[~]
|5> prng2.randint(-1, 2, size=10)
array([ 1,  1, -1,  0,  0, -1,  1,  0, -1, -1])

임의 상태에 의존하는 다른 함수를 사용하는 경우 전체 시드를 설정할 수는 없지만 대신 임의의 숫자 목록을 생성하고 시드를 함수의 매개 변수로 설정하는 함수를 만들어야합니다. 이것은 코드의 다른 임의 생성기를 방해하지 않습니다.

# Random states
def get_states(random_state, low, high, size):
    rs = np.random.RandomState(random_state)
    states = rs.randint(low=low, high=high, size=size)
    return states

# Call function
states = get_states(random_state=42, low=2, high=28347, size=25)

랜덤 생성기의 시드가 무엇인지, 코드에서 언제 / 어떻게 설정되는지 이해하는 것이 중요합니다 (시드의 수학적 의미에 대한 좋은 설명은 여기 에서 확인 하십시오 ).

이를 위해 다음을 수행하여 시드를 설정해야합니다.

random_state = np.random.RandomState(seed=your_favorite_seed_value)

It is then important to generate the random numbers from random_state and not from np.random. I.e. you should do:

random_state.randint(...)

instead of

np.random.randint(...) 

which will create a new instance of RandomState() and basically use your computer internal clock to set the seed.


I just want to clarify something in regard to @Robert Kern answer just in case that is not clear. Even if you do use the RandomState you would have to initialize it every time you call a numpy random method like in Robert's example otherwise you'll get the following results.

Python 3.6.9 |Anaconda, Inc.| (default, Jul 30 2019, 19:07:31) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> prng = np.random.RandomState(2019)
>>> prng.randint(-1, 2, size=10)
array([-1,  1,  0, -1,  1,  1, -1,  0, -1,  1])
>>> prng.randint(-1, 2, size=10)
array([-1, -1, -1,  0, -1, -1,  1,  0, -1, -1])
>>> prng.randint(-1, 2, size=10)
array([ 0, -1, -1,  0,  1,  1, -1,  1, -1,  1])
>>> prng.randint(-1, 2, size=10)
array([ 1,  1,  0,  0,  0, -1,  1,  1,  0, -1])

참고URL : https://stackoverflow.com/questions/5836335/consistently-create-same-random-numpy-array

반응형