python随机种子seed的作用(强化学习常用到)_汀、的博客-CSDN博客先上代码import mathimport gymfrom gym import spaces, loggerfrom gym.utils import seedingimport numpy as npclass CartPoleEnv(gym.Env): def __init__(self): super().__init__() self.seed() def seed(self, seed=None): #sehttps://blog.csdn.net/sinat_39620217/article/details/123482020?spm=1001.2014.3001.5501
首先导入库:
# 导入模块
import random
import numpy as np
import tensorflow as tf
import torch
import time
下面先展示python内置random函数、numpy中的random函数、tensorflow及pytorch中常见的seed使用方式(注:pytorch仅以CPU为例):
seed = 1
random.seed(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
torch.manual_seed(seed)
list = [1,2,3,4,5,6,7,8,9]
a = random.sample(list,5)
b = np.random.randn(5)
c = tf.random.normal([5])
d = torch.randn(5)
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
print('python内置输出:',a)
print('*' * 60)
print('numpy输出:',b)
print('*' * 60)
print('tensorflow输出:',c)
print('*' * 60)
print('pytorch输出',d)
# 第一次运行输出:
2021-01-17 17:51:36
python内置输出: [3, 2, 9, 1, 4]
************************************************************
numpy输出: [ 1.62434536 -0.61175641 -0.52817175 -1.07296862 0.86540763]
************************************************************
tensorflow输出: tf.Tensor([-1.1012203 1.5457517 0.383644 -0.87965786 -1.2246722 ], shape=(5,), dtype=float32)
************************************************************
pytorch输出 tensor([ 0.6614, 0.2669, 0.0617, 0.6213, -0.4519])
# 第二次运行输出:
2021-01-17 17:52:10
python内置输出: [3, 2, 9, 1, 4]
************************************************************
numpy输出: [ 1.62434536 -0.61175641 -0.52817175 -1.07296862 0.86540763]
************************************************************
tensorflow输出: tf.Tensor([-1.1012203 1.5457517 0.383644 -0.87965786 -1.2246722 ], shape=(5,), dtype=float32)
************************************************************
pytorch输出 tensor([ 0.6614, 0.2669, 0.0617, 0.6213, -0.4519])
|