[英]Does Python random.seed() and numpy.random.seed() implementations differ one from another?
在實現 CLT(中心極限定理)時,我正在試驗數據分布的差異,比較兩種方法:一種使用純 Python,另一種使用 Numpy。
這是我的代碼:
from numpy.random import seed
from numpy.random import randint
from numpy import mean
import matplotlib.pyplot as plt
import random
# [With Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos and calculate the mean
# of each sample, at once.
seed(1)
means = [mean(randint(60, 90, 50)) for _i in range(1000)]
# [Without Numpy]
#
# Generate 1000 samples of 50 men, from 60 to 90 Kilos.
# Calculate the mean of each sample, storing on a separated list.
random.seed(1)
samples = list()
for i in range(0, 1000):
samples.append([random.randint(60, 90) for n in range(50)])
means_without_numpy = [sum(s) / len(s) for s in samples]
# Plot distributions of sample means, side by side.
plt.subplot(1, 2, 1)
plt.title("Numpy")
plt.hist(means)
plt.subplot(1, 2, 2)
plt.title("Pure Python")
plt.hist(means_without_numpy)
plt.show()
print(f"The mean of means: {mean(means)}")
print(f"The mean of means (without numpy): {mean(means_without_numpy)}")
此代碼在關閉它們后生成以下直方圖和一條消息:
$ python3 clt_comparisson.py
The mean of means: 74.54001999999998
The mean of means (without numpy): 74.94394
我的問題是:
random
和numpy
)提供隨機數據的方式的影響?1
作為種子,它們是否應該生成相同的隨機數據集,因為它們具有相同的種子值? numpy
and python's random
use different algorithms, which I think is quite expected for a mathematics package written in C and fortran. 具有相同種子的相同算法將產生相同的值
>>> import random
>>> random.seed(12345678)
>>> import numpy.random
>>> numpy.random.seed(12345678)
>>> random.randint(0, 100000)
94406
>>> numpy.random.randint(0, 100000)
67251
(不一樣)
即使在很大的范圍內,兩種實現之間的分布也會略有不同,因為您不會期望它們之間的隨機性質量完全相等。 如果您在同一個程序中創建第二個數據集而不更改種子,它會有所不同,就像具有不同種子的數據集一樣。
人們不會在加密設置中提供自己的種子,但在科學方面,如果您希望 model 可重現,它會很有用。 在這種情況下,將您的代碼從numpy.random.RandState
與一些眾所周知的 32 integer 結合起來,這樣您就不必擔心程序范圍內的numpy.random.seed()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.