如何将Matlab随机生成器状态恢复到numpy?

huangapple go评论63阅读模式
英文:

How to restore matlab random generator state into numpy?

问题

你可以使用以下代码将Mersenne Twister的状态导入到NumPy,以便在保存后生成相同的随机数:

import numpy as np

# 加载之前保存的状态
loaded_state = np.random.RandomState(seed)

# 设置状态的内部状态
loaded_state.set_state(s.State)

# 现在你可以使用loaded_state生成与之前相同的随机数

这样,你可以确保NumPy生成与Matlab中相同的随机数,包括状态被修改后的情况。

英文:

I can save the state of matlab random generator with the following code

seed = 10;
rng(seed, 'twister');
%... random functions that don't need to be reproduced%

s = rng;
s.Type
s.Seed
s.State
save('rand_state.mat', 's');

%... random functions that need to be reproduced%

How would you import the state of the Mersenne Twister into numpy so that it generates the same random numbers after it was saved?

Just using np.random.RandomState(seed) does not take into account that the state of the twister was modified by the subsequent random calls before it was saved.

答案1

得分: 1

np.random.RandomState有一个名为set_state()的函数,它接受输入state = ('MT19937', keys, pos)

唯一需要注意的是Matlab将pos保存为State的最后一个元素,其余部分是set_state所期望的keys

rng = np.random.RandomState(s['Seed'])
rng.set_state("MT19937", s['State'], s['State'][-1])

我学到的一点是Matlab和Python在将[0,1)范围内的随机数转换为整数或正态变量时使用了不同的转换方式。因此,如果需要在Python中复制这个过程,就需要编写自定义函数来处理整数和正态变量。

英文:

np.random.RandomState has a function set_state() that takes the input state = ('MT19937', keys, pos)

The only gotcha is that matlab saves pos as the last element of State. The rest are the keys that set_state expects.

rng = np.random.RandomState(s['Seed'])
rng.set_state("MT19937", s['State'], s['State'][-1])

I learned the hard way that that matlab and python use different transformations to convert random draws from [0,1) into integers or normal variates. So one will have to write custom functions for ints and normals in matlab, if that needs to be replicated in python.

huangapple
  • 本文由 发表于 2023年4月13日 21:06:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定