提交 cc55e67c authored 作者: Iban Harlouchet's avatar Iban Harlouchet

flake8 for tensor/raw_random.py

上级 930ef0c4
"""Define random number Type (`RandomStateType`) and Op (`RandomFunction`).""" """Define random number Type (`RandomStateType`) and Op (`RandomFunction`)."""
from __future__ import print_function from __future__ import print_function
__docformat__ = "restructuredtext en"
import sys import sys
from copy import copy from copy import copy
...@@ -15,6 +15,8 @@ from theano import gof ...@@ -15,6 +15,8 @@ from theano import gof
from six import string_types from six import string_types
from theano.compile import optdb from theano.compile import optdb
__docformat__ = "restructuredtext en"
class RandomStateType(gof.Type): class RandomStateType(gof.Type):
"""A Type wrapper for numpy.random.RandomState """A Type wrapper for numpy.random.RandomState
...@@ -85,13 +87,13 @@ class RandomStateType(gof.Type): ...@@ -85,13 +87,13 @@ class RandomStateType(gof.Type):
# Register RandomStateType's C code for ViewOp. # Register RandomStateType's C code for ViewOp.
theano.compile.register_view_op_c_code( theano.compile.register_view_op_c_code(
RandomStateType, RandomStateType,
""" """
Py_XDECREF(%(oname)s); Py_XDECREF(%(oname)s);
%(oname)s = %(iname)s; %(oname)s = %(iname)s;
Py_XINCREF(%(oname)s); Py_XINCREF(%(oname)s);
""", """,
1) 1)
random_state_type = RandomStateType() random_state_type = RandomStateType()
...@@ -135,9 +137,8 @@ class RandomFunction(gof.Op): ...@@ -135,9 +137,8 @@ class RandomFunction(gof.Op):
and self.ndim_added == other.ndim_added and self.ndim_added == other.ndim_added
def __hash__(self): def __hash__(self):
return hash(type(self)) ^ hash(self.fn) \ return (hash(type(self)) ^ hash(self.fn) ^ hash(self.outtype) ^
^ hash(self.outtype) \ hash(self.inplace) ^ hash(self.ndim_added))
^ hash(self.inplace) ^ hash(self.ndim_added)
def __getstate__(self): def __getstate__(self):
return self.state return self.state
...@@ -233,7 +234,6 @@ class RandomFunction(gof.Op): ...@@ -233,7 +234,6 @@ class RandomFunction(gof.Op):
# copy of r if self.inplace is False # copy of r if self.inplace is False
r, shape, args = inputs[0], inputs[1], inputs[2:] r, shape, args = inputs[0], inputs[1], inputs[2:]
assert type(r) == numpy.random.RandomState, (type(r), r) assert type(r) == numpy.random.RandomState, (type(r), r)
r_orig = r
# If shape == [], that means no shape is enforced, and numpy is # If shape == [], that means no shape is enforced, and numpy is
# trusted to draw the appropriate number of samples, numpy uses # trusted to draw the appropriate number of samples, numpy uses
...@@ -245,16 +245,16 @@ class RandomFunction(gof.Op): ...@@ -245,16 +245,16 @@ class RandomFunction(gof.Op):
shape = tuple(shape) shape = tuple(shape)
if (shape is not None and if (shape is not None and
self.outtype.ndim != len(shape) + self.ndim_added): self.outtype.ndim != len(shape) + self.ndim_added):
raise ValueError('Shape mismatch: self.outtype.ndim (%i) !=' raise ValueError('Shape mismatch: self.outtype.ndim (%i) !='
' len(shape) (%i) + self.ndim_added (%i)' ' len(shape) (%i) + self.ndim_added (%i)'
% (self.outtype.ndim, len(shape), self.ndim_added)) % (self.outtype.ndim, len(shape), self.ndim_added))
if not self.inplace: if not self.inplace:
r = copy(r) r = copy(r)
rout[0] = r rout[0] = r
rval = self.fn(r, *(args + [shape])) rval = self.fn(r, *(args + [shape]))
if not isinstance(rval, numpy.ndarray) \ if (not isinstance(rval, numpy.ndarray) or
or str(rval.dtype) != node.outputs[1].type.dtype: str(rval.dtype) != node.outputs[1].type.dtype):
rval = theano._asarray(rval, dtype=node.outputs[1].type.dtype) rval = theano._asarray(rval, dtype=node.outputs[1].type.dtype)
# When shape is None, numpy has a tendency to unexpectedly # When shape is None, numpy has a tendency to unexpectedly
...@@ -288,7 +288,7 @@ class RandomFunction(gof.Op): ...@@ -288,7 +288,7 @@ class RandomFunction(gof.Op):
def grad(self, inputs, outputs): def grad(self, inputs, outputs):
return [theano.gradient.grad_undefined(self, k, inp, return [theano.gradient.grad_undefined(self, k, inp,
'No gradient defined through raw random numbers op') 'No gradient defined through raw random numbers op')
for k, inp in enumerate(inputs)] for k, inp in enumerate(inputs)]
def R_op(self, inputs, eval_points): def R_op(self, inputs, eval_points):
...@@ -325,8 +325,8 @@ def _infer_ndim_bcast(ndim, shape, *args): ...@@ -325,8 +325,8 @@ def _infer_ndim_bcast(ndim, shape, *args):
else: else:
if shape_ndim != ndim: if shape_ndim != ndim:
raise ValueError('ndim should be equal to len(shape), but\n', raise ValueError('ndim should be equal to len(shape), but\n',
'ndim = %s, len(shape) = %s, shape = %s' 'ndim = %s, len(shape) = %s, shape = %s'
% (ndim, shape_ndim, shape)) % (ndim, shape_ndim, shape))
bcast = [] bcast = []
pre_v_shape = [] pre_v_shape = []
...@@ -353,7 +353,8 @@ def _infer_ndim_bcast(ndim, shape, *args): ...@@ -353,7 +353,8 @@ def _infer_ndim_bcast(ndim, shape, *args):
break break
else: else:
if n_a_i == 0: if n_a_i == 0:
raise ValueError(('Auto-shape of -1 must overlap' raise ValueError((
'Auto-shape of -1 must overlap'
'with the shape of one of the broadcastable' 'with the shape of one of the broadcastable'
'inputs')) 'inputs'))
else: else:
...@@ -373,7 +374,7 @@ def _infer_ndim_bcast(ndim, shape, *args): ...@@ -373,7 +374,7 @@ def _infer_ndim_bcast(ndim, shape, *args):
# but we need to know ndim # but we need to know ndim
if not args: if not args:
raise TypeError(('_infer_ndim_bcast cannot infer shape without' raise TypeError(('_infer_ndim_bcast cannot infer shape without'
' either shape or args')) ' either shape or args'))
template = reduce(lambda a, b: a + b, args) template = reduce(lambda a, b: a + b, args)
v_shape = template.shape v_shape = template.shape
bcast = template.broadcastable bcast = template.broadcastable
...@@ -463,7 +464,7 @@ def uniform(random_state, size=None, low=0.0, high=1.0, ndim=None, dtype=None): ...@@ -463,7 +464,7 @@ def uniform(random_state, size=None, low=0.0, high=1.0, ndim=None, dtype=None):
dtype = tensor.scal.upcast(theano.config.floatX, low.dtype, high.dtype) dtype = tensor.scal.upcast(theano.config.floatX, low.dtype, high.dtype)
ndim, size, bcast = _infer_ndim_bcast(ndim, size, low, high) ndim, size, bcast = _infer_ndim_bcast(ndim, size, low, high)
op = RandomFunction('uniform', op = RandomFunction('uniform',
tensor.TensorType(dtype=dtype, broadcastable=bcast)) tensor.TensorType(dtype=dtype, broadcastable=bcast))
return op(random_state, size, low, high) return op(random_state, size, low, high)
...@@ -487,7 +488,7 @@ def normal(random_state, size=None, avg=0.0, std=1.0, ndim=None, dtype=None): ...@@ -487,7 +488,7 @@ def normal(random_state, size=None, avg=0.0, std=1.0, ndim=None, dtype=None):
dtype = tensor.scal.upcast(theano.config.floatX, avg.dtype, std.dtype) dtype = tensor.scal.upcast(theano.config.floatX, avg.dtype, std.dtype)
ndim, size, bcast = _infer_ndim_bcast(ndim, size, avg, std) ndim, size, bcast = _infer_ndim_bcast(ndim, size, avg, std)
op = RandomFunction('normal', op = RandomFunction('normal',
tensor.TensorType(dtype=dtype, broadcastable=bcast)) tensor.TensorType(dtype=dtype, broadcastable=bcast))
return op(random_state, size, avg, std) return op(random_state, size, avg, std)
...@@ -517,7 +518,8 @@ def binomial(random_state, size=None, n=1, p=0.5, ndim=None, ...@@ -517,7 +518,8 @@ def binomial(random_state, size=None, n=1, p=0.5, ndim=None,
# p=numpy.asarray([.1, .2, .3], dtype='float64')) # p=numpy.asarray([.1, .2, .3], dtype='float64'))
n = tensor.cast(n, 'int32') n = tensor.cast(n, 'int32')
op = RandomFunction('binomial', op = RandomFunction('binomial',
tensor.TensorType(dtype=dtype, broadcastable=(False,) * ndim)) tensor.TensorType(dtype=dtype,
broadcastable=(False,) * ndim))
return op(random_state, size, n, p) return op(random_state, size, n, p)
...@@ -583,7 +585,7 @@ def random_integers(random_state, size=None, low=0, high=1, ndim=None, ...@@ -583,7 +585,7 @@ def random_integers(random_state, size=None, low=0, high=1, ndim=None,
high = tensor.as_tensor_variable(high) high = tensor.as_tensor_variable(high)
ndim, size, bcast = _infer_ndim_bcast(ndim, size, low, high) ndim, size, bcast = _infer_ndim_bcast(ndim, size, low, high)
op = RandomFunction(random_integers_helper, op = RandomFunction(random_integers_helper,
tensor.TensorType(dtype=dtype, broadcastable=bcast)) tensor.TensorType(dtype=dtype, broadcastable=bcast))
return op(random_state, size, low, high) return op(random_state, size, low, high)
...@@ -719,8 +721,9 @@ def permutation(random_state, size=None, n=1, ndim=None, dtype='int64'): ...@@ -719,8 +721,9 @@ def permutation(random_state, size=None, n=1, ndim=None, dtype='int64'):
ndim, size, bcast = _infer_ndim_bcast(ndim, size) ndim, size, bcast = _infer_ndim_bcast(ndim, size)
# print "NDIM", ndim, size # print "NDIM", ndim, size
op = RandomFunction(permutation_helper, op = RandomFunction(permutation_helper,
tensor.TensorType(dtype=dtype, broadcastable=bcast + (False,)), tensor.TensorType(dtype=dtype,
ndim_added=1) broadcastable=bcast + (False,)),
ndim_added=1)
return op(random_state, size, n) return op(random_state, size, n)
...@@ -738,14 +741,11 @@ def multinomial_helper(random_state, n, pvals, size): ...@@ -738,14 +741,11 @@ def multinomial_helper(random_state, n, pvals, size):
ndim = len(size) ndim = len(size)
else: else:
ndim = max(n.ndim, pvals.ndim - 1) ndim = max(n.ndim, pvals.ndim - 1)
out_ndim = ndim + 1
# broadcast n to ndim dimensions and pvals to ndim+1 # broadcast n to ndim dimensions and pvals to ndim+1
if n.ndim > ndim: if n.ndim > ndim:
raise ValueError( raise ValueError('n.ndim (%i) should not be larger than len(size) (%i)'
'n.ndim (%i) should not be larger than len(size) (%i)' % (n.ndim, ndim), n, size)
% (n.ndim, ndim),
n, size)
if n.ndim < ndim: if n.ndim < ndim:
n = n.reshape((1,) * (ndim - n.ndim) + n.shape) n = n.reshape((1,) * (ndim - n.ndim) + n.shape)
...@@ -788,7 +788,7 @@ def multinomial_helper(random_state, n, pvals, size): ...@@ -788,7 +788,7 @@ def multinomial_helper(random_state, n, pvals, size):
# because mtrand.pyx has a ValueError that will trigger if # because mtrand.pyx has a ValueError that will trigger if
# sum(pvals[:-1]) > 1.0 # sum(pvals[:-1]) > 1.0
pvi = pvi * (1.0 - 5e-5) pvi = pvi * (1.0 - 5e-5)
#pvi = pvi * .9 # pvi = pvi * .9
pisum = numpy.sum(pvi) pisum = numpy.sum(pvi)
elif pvi[-1] < 5e-5: # will this even work? elif pvi[-1] < 5e-5: # will this even work?
pvi = pvi * (1.0 - 5e-5) pvi = pvi * (1.0 - 5e-5)
...@@ -859,8 +859,9 @@ def multinomial(random_state, size=None, n=1, pvals=[0.5, 0.5], ...@@ -859,8 +859,9 @@ def multinomial(random_state, size=None, n=1, pvals=[0.5, 0.5],
ndim, size, bcast = _infer_ndim_bcast(ndim, size, n, tmp) ndim, size, bcast = _infer_ndim_bcast(ndim, size, n, tmp)
bcast = bcast + (pvals.type.broadcastable[-1],) bcast = bcast + (pvals.type.broadcastable[-1],)
op = RandomFunction(multinomial_helper, op = RandomFunction(multinomial_helper,
tensor.TensorType(dtype=dtype, broadcastable=bcast), tensor.TensorType(dtype=dtype,
ndim_added=1) broadcastable=bcast),
ndim_added=1)
return op(random_state, size, n, pvals) return op(random_state, size, n, pvals)
......
...@@ -67,7 +67,6 @@ whitelist_flake8 = [ ...@@ -67,7 +67,6 @@ whitelist_flake8 = [
"tensor/nlinalg.py", "tensor/nlinalg.py",
"tensor/blas_c.py", "tensor/blas_c.py",
"tensor/elemwise_cgen.py", "tensor/elemwise_cgen.py",
"tensor/raw_random.py",
"tensor/blas_scipy.py", "tensor/blas_scipy.py",
"tensor/tests/test_subtensor.py", "tensor/tests/test_subtensor.py",
"tensor/tests/test_utils.py", "tensor/tests/test_utils.py",
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论