Files
ailearning/docs/da/126.md
2020-10-19 21:08:55 +08:00

71 lines
1.9 KiB
Markdown
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Theano 随机数流变量
In [1]:
```py
import theano
import theano.tensor as T
import numpy as np
```
```py
Using gpu device 1: Tesla C2075 (CNMeM is disabled)
```
`Theano` 的随机数变量由 `theano.sandbox.rng_mrg` 中的 `MRG_RandomStreams` 实现(`sandbox` 表示是实验代码):
In [2]:
```py
from theano.sandbox.rng_mrg import MRG_RandomStreams
```
新建一个 `MRG_RandomStreams(seed=12345, use_cuda=None)` 实例:
In [3]:
```py
srng = MRG_RandomStreams()
```
它支持以下方法:
* `normal(size, avg=0.0, std=1.0, ndim=None, dtype=None, nstreams=None)`
* 产生指定形状的、服从正态分布 $N(avg, std)$ 的随机数变量,默认为标准正态分布
* `uniform(size, low=0.0, high=1.0, ndim=None, dtype=None, nstreams=None)`
* 产生指定形状的、服从均匀分布 $U(low, high)$ 的随机数变量,默认为 0-1 之间的均匀分布
* `binomial(size=None, n=1, p=0.5, ndim=None, dtype='int64', nstreams=None)`
* 产生指定形状的、服从二项分布 $B(n,p)$ 的随机数变量
* `multinomial(size=None, n=1, pvals=None, ndim=None, dtype='int64', nstreams=None)`
* 产生指定形状的、服从多项分布的随机数变量
与 np.random.random 不同,它产生的是随机数变量,而不是随机数数组,因此可以将 `size` 作为参数传给它:
In [4]:
```py
rand_size = T.vector(dtype="int64")
rand_normal = srng.normal(rand_size.shape)
rand_uniform = srng.uniform(rand_size.shape)
rand_binomial = srng.binomial(rand_size.shape)
f_rand = theano.function(inputs = [rand_size],
outputs = [rand_normal, rand_uniform, rand_binomial])
print f_rand(range(5))[0]
print f_rand(range(5))[1]
print f_rand(range(5))[2]
```
```py
[ 0.10108768 -1.64354193 0.71042836 -0.77760422 0.06291872]
[ 0.23193923 0.71880513 0.03122572 0.97318739 0.99260223]
[0 1 0 1 1]
```