提交 8085810d authored 作者: James Bergstra's avatar James Bergstra

adding tensor_random.py

上级 f32478a3
import unittest
from tensor_random import *
import compile
def Uniform(s, n):
return NumpyGenerator(s, n, numpy.random.RandomState.uniform)
class T_Random(unittest.TestCase):
def test0(self):
rng = Uniform(12345, 2)
r0 = rng((2,3))
r1 = rng((2,3))
f0 = compile.function([], [r0])
f1 = compile.function([], [r1])
v0 = f0()
self.failUnless(v0.shape == (2,3))
self.failUnless(str(v0[0,0]).startswith('0.929616'))
self.failUnless(str(v0[1,2]).startswith('0.595544'))
v1 = f1()
self.failUnless(numpy.all(v0 == v1))
v1 = f1()
self.failUnless(numpy.all(v0 != v1))
def test1(self):
rng = RandomState(12345)
f0 = compile.function([], [rng.uniform((3,))])
f1 = compile.function([], [rng.uniform((3,))])
v0, v1 = f0(), f1()
self.failUnless(v0.shape == (3,))
self.failUnless(numpy.all(v0 != v1))
def test2(self):
x = tensor.ivector()
f0 = compile.function([x], [Uniform(123, 1)(x)])
f1 = compile.function([x], [Uniform(123, 1)(x)])
v0, v1 = f0([3]), f1([7])
self.failUnless(v0.shape == (3,))
self.failUnless(numpy.all(v0 == v1[:3]))
def test3(self):
rng = RandomState(12345)
template = tensor.fmatrix()
f0 = compile.function([template], [rng.uniform_like(template)])
v0 = f0(numpy.zeros((2,3)))
self.failUnless(str(v0[1,2]).startswith('0.595544'))
def test4(self):
rng = RandomState(123455)
template = tensor.fmatrix()
f0 = compile.function([template],
[rng.gen_like(('beta',{'a':0.5,'b':0.65}), template)])
v0 = f0(numpy.zeros((2,3)))
self.failUnless(v0.shape == (2,3))
self.failUnless(str(v0[0,0]).startswith('0.013259'))
self.failUnless(str(v0[1,2]).startswith('0.753368'))
if __name__ == '__main__':
unittest.main()
import gof
import tensor
import numpy
import functools
def fn_from_dist(dist):
if callable(dist):
return dist
if isinstance(dist, str):
return getattr(numpy.random.RandomState, dist)
name, kwargs = dist
fn = getattr(numpy.random.RandomState, name)
fn = functools.partial(fn, **kwargs)
return fn
class RandomState(object):
def __init__(self, seed):
self.seed = seed
def uniform(self, shape, ndim=None):
return self.gen('uniform', shape, ndim)
def uniform_like(self, x):
return self.gen_like('uniform', x)
def gen(self, dist, shape=(), ndim=None):
self.seed += 1
fn = fn_from_dist(dist)
if isinstance(shape, tuple):
return NumpyGenerator(self.seed-1, len(shape),fn) (shape)
return NumpyGenerator(self.seed - 1, ndim, fn)(shape)
def gen_like(self, dist, x):
self.seed += 1
fn = fn_from_dist(dist)
return NumpyGenerator(self.seed-1, x.type.ndim, fn)(tensor.shape(x))
class NumpyGenerator(gof.op.Op):
destroy_map = {0: [0]}
def __init__(self, seed, ndim, fn, **kwargs):
gof.op.Op.__init__(self, **kwargs)
self.seed = seed
self.ndim = ndim
self.fn = fn
def make_node(self, _shape):
#TODO: check for constant shape, and guess the broadcastable bits
shape = tensor.convert_to_int64(_shape)
if shape.type.ndim != 1:
raise TypeError('shape argument was not converted to 1-d tensor', _shape)
inputs = [gof.Value(gof.type.generic, numpy.random.RandomState(self.seed)), shape]
outputs = [gof.Result(tensor.Tensor(dtype='float64', broadcastable =
[False]*self.ndim))]
return gof.Apply(op = self, inputs = inputs, outputs = outputs)
def grad(self, inputs, grad_outputs):
return [None]
def perform(self, node, input_storage, output_storage):
rng = input_storage[0]
shape = input_storage[1]
if self.ndim != len(shape):
raise ValueError('shape argument %s had the wrong length (!=%i)' %
(shape, self.ndim) )
output_storage[0][0] = self.fn(rng, size=shape)
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论