提交 e96f06da authored 作者: Brandon T. Willard's avatar Brandon T. Willard

Apply pyupgrade to theano.sandbox

上级 2b658090
import logging import logging
from six import integer_types
import theano.tensor import theano.tensor
from theano import tensor from theano import tensor
from theano.gof import Apply, Op, local_optimizer from theano.gof import Apply, Op, local_optimizer
...@@ -84,7 +82,7 @@ def remove_hint_nodes(node): ...@@ -84,7 +82,7 @@ def remove_hint_nodes(node):
return node.inputs return node.inputs
class HintsFeature(object): class HintsFeature:
""" """
FunctionGraph Feature to track matrix properties. FunctionGraph Feature to track matrix properties.
...@@ -120,7 +118,7 @@ class HintsFeature(object): ...@@ -120,7 +118,7 @@ class HintsFeature(object):
""" """
def add_hint(self, r, k, v): def add_hint(self, r, k, v):
logger.debug("adding hint; %s, %s, %s" % (r, k, v)) logger.debug("adding hint; {}, {}, {}".format(r, k, v))
self.hints[r][k] = v self.hints[r][k] = v
def ensure_init_r(self, r): def ensure_init_r(self, r):
...@@ -378,7 +376,7 @@ def spectral_radius_bound(X, log2_exponent): ...@@ -378,7 +376,7 @@ def spectral_radius_bound(X, log2_exponent):
""" """
if X.type.ndim != 2: if X.type.ndim != 2:
raise TypeError("spectral_radius_bound requires a matrix argument", X) raise TypeError("spectral_radius_bound requires a matrix argument", X)
if not isinstance(log2_exponent, integer_types): if not isinstance(log2_exponent, int):
raise TypeError( raise TypeError(
"spectral_radius_bound requires an integer exponent", log2_exponent "spectral_radius_bound requires an integer exponent", log2_exponent
) )
......
...@@ -20,7 +20,7 @@ class Minimal(gof.Op): ...@@ -20,7 +20,7 @@ class Minimal(gof.Op):
# - If they do not, then you should not use them in # - If they do not, then you should not use them in
# __eq__ and __hash__ # __eq__ and __hash__
super(Minimal, self).__init__() super().__init__()
def make_node(self, *args): def make_node(self, *args):
# HERE `args` must be THEANO VARIABLES # HERE `args` must be THEANO VARIABLES
......
...@@ -22,7 +22,7 @@ class MultinomialFromUniform(Op): ...@@ -22,7 +22,7 @@ class MultinomialFromUniform(Op):
self.odtype = odtype self.odtype = odtype
def __str__(self): def __str__(self):
return "%s{%s}" % (self.__class__.__name__, self.odtype) return "{}{{{}}}".format(self.__class__.__name__, self.odtype)
def __setstate__(self, dct): def __setstate__(self, dct):
self.__dict__.update(dct) self.__dict__.update(dct)
...@@ -230,7 +230,7 @@ class ChoiceFromUniform(MultinomialFromUniform): ...@@ -230,7 +230,7 @@ class ChoiceFromUniform(MultinomialFromUniform):
def __init__(self, odtype, replace=False, *args, **kwargs): def __init__(self, odtype, replace=False, *args, **kwargs):
self.replace = replace self.replace = replace
super(ChoiceFromUniform, self).__init__(odtype=odtype, *args, **kwargs) super().__init__(odtype=odtype, *args, **kwargs)
def __setstate__(self, state): def __setstate__(self, state):
self.__dict__.update(state) self.__dict__.update(state)
...@@ -442,4 +442,4 @@ class MultinomialWOReplacementFromUniform(ChoiceFromUniform): ...@@ -442,4 +442,4 @@ class MultinomialWOReplacementFromUniform(ChoiceFromUniform):
DeprecationWarning, DeprecationWarning,
stacklevel=2, stacklevel=2,
) )
super(MultinomialWOReplacementFromUniform, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
...@@ -16,7 +16,6 @@ P. L'Ecuyer and R. Simard and E. Jack Chen and W. David Kelton, An Object-Orient ...@@ -16,7 +16,6 @@ P. L'Ecuyer and R. Simard and E. Jack Chen and W. David Kelton, An Object-Orient
import warnings import warnings
import numpy as np import numpy as np
from six import integer_types, string_types
import theano import theano
from theano import Apply, Op, Variable, config, function, gradient, shared, tensor from theano import Apply, Op, Variable, config, function, gradient, shared, tensor
...@@ -348,7 +347,7 @@ class mrg_uniform_base(Op): ...@@ -348,7 +347,7 @@ class mrg_uniform_base(Op):
s = "inplace" s = "inplace"
else: else:
s = "no_inplace" s = "no_inplace"
return self.__class__.__name__ + "{%s,%s}" % (self.output_type, s) return self.__class__.__name__ + "{{{},{}}}".format(self.output_type, s)
def grad(self, inputs, ograd): def grad(self, inputs, ograd):
return [ return [
...@@ -532,7 +531,7 @@ class mrg_uniform(mrg_uniform_base): ...@@ -532,7 +531,7 @@ class mrg_uniform(mrg_uniform_base):
assert isinstance(node.inputs[0].type, TensorType) assert isinstance(node.inputs[0].type, TensorType)
if self.output_type.dtype == "float16": if self.output_type.dtype == "float16":
# C code is not tested, fall back to Python # C code is not tested, fall back to Python
super(mrg_uniform, self).c_code(node, name, inp, out, sub) super().c_code(node, name, inp, out, sub)
return """ return """
//////// <code generated by mrg_uniform> //////// <code generated by mrg_uniform>
npy_int64 odims_i; npy_int64 odims_i;
...@@ -672,9 +671,7 @@ def guess_n_streams(size, warn=False): ...@@ -672,9 +671,7 @@ def guess_n_streams(size, warn=False):
# TODO: a smart way of choosing the number of streams, see #612. # TODO: a smart way of choosing the number of streams, see #612.
# Note that this code was moved out of `MRG_RandomStreams` so that it can # Note that this code was moved out of `MRG_RandomStreams` so that it can
# be easily accessed from tests, where we want to disable the warning. # be easily accessed from tests, where we want to disable the warning.
if isinstance(size, (tuple, list)) and all( if isinstance(size, (tuple, list)) and all([isinstance(i, int) for i in size]):
[isinstance(i, integer_types) for i in size]
):
# We can make a guess. # We can make a guess.
r = 1 r = 1
for s in size: for s in size:
...@@ -704,7 +701,7 @@ def guess_n_streams(size, warn=False): ...@@ -704,7 +701,7 @@ def guess_n_streams(size, warn=False):
return 60 * 256 return 60 * 256
class MRG_RandomStreams(object): class MRG_RandomStreams:
""" """
Module component with similar interface to numpy.random Module component with similar interface to numpy.random
(numpy.random.RandomState). (numpy.random.RandomState).
...@@ -730,7 +727,7 @@ class MRG_RandomStreams(object): ...@@ -730,7 +727,7 @@ class MRG_RandomStreams(object):
# by this RandomStreams. # by this RandomStreams.
self.state_updates = [] self.state_updates = []
super(MRG_RandomStreams, self).__init__() super().__init__()
# Needed to reset the streams. # Needed to reset the streams.
self.default_instance_seed = seed self.default_instance_seed = seed
...@@ -739,7 +736,7 @@ class MRG_RandomStreams(object): ...@@ -739,7 +736,7 @@ class MRG_RandomStreams(object):
def set_rstate(self, seed): def set_rstate(self, seed):
# TODO : need description for method, parameter # TODO : need description for method, parameter
if isinstance(seed, integer_types): if isinstance(seed, int):
if seed == 0: if seed == 0:
raise ValueError("seed should not be 0", seed) raise ValueError("seed should not be 0", seed)
elif seed >= M2: elif seed >= M2:
...@@ -810,7 +807,7 @@ class MRG_RandomStreams(object): ...@@ -810,7 +807,7 @@ class MRG_RandomStreams(object):
and they are spaced by 2**72 samples. and they are spaced by 2**72 samples.
""" """
assert isinstance(dtype, string_types) assert isinstance(dtype, str)
assert n_streams < 2 ** 72 assert n_streams < 2 ** 72
assert n_streams > 0 assert n_streams > 0
rval = np.zeros((n_streams, 6), dtype="int32") rval = np.zeros((n_streams, 6), dtype="int32")
...@@ -896,12 +893,8 @@ class MRG_RandomStreams(object): ...@@ -896,12 +893,8 @@ class MRG_RandomStreams(object):
if isinstance(size, tuple): if isinstance(size, tuple):
msg = "size must be a tuple of int or a Theano variable" msg = "size must be a tuple of int or a Theano variable"
assert all( assert all([isinstance(i, (np.integer, int, Variable)) for i in size]), msg
[isinstance(i, (np.integer, integer_types, Variable)) for i in size] if any([isinstance(i, (np.integer, int)) and i <= 0 for i in size]):
), msg
if any(
[isinstance(i, (np.integer, integer_types)) and i <= 0 for i in size]
):
raise ValueError( raise ValueError(
"The specified size contains a dimension with value <= 0", size "The specified size contains a dimension with value <= 0", size
) )
...@@ -994,7 +987,7 @@ class MRG_RandomStreams(object): ...@@ -994,7 +987,7 @@ class MRG_RandomStreams(object):
pvals = as_tensor_variable(pvals) pvals = as_tensor_variable(pvals)
pvals = undefined_grad(pvals) pvals = undefined_grad(pvals)
if size is not None: if size is not None:
if any([isinstance(i, integer_types) and i <= 0 for i in size]): if any([isinstance(i, int) and i <= 0 for i in size]):
raise ValueError( raise ValueError(
"The specified size contains a dimension with value <= 0", size "The specified size contains a dimension with value <= 0", size
) )
...@@ -1017,7 +1010,7 @@ class MRG_RandomStreams(object): ...@@ -1017,7 +1010,7 @@ class MRG_RandomStreams(object):
return op(pvals, unis, n_samples) return op(pvals, unis, n_samples)
else: else:
raise NotImplementedError( raise NotImplementedError(
("MRG_RandomStreams.multinomial only" " implemented for pvals.ndim = 2") "MRG_RandomStreams.multinomial only" " implemented for pvals.ndim = 2"
) )
def choice( def choice(
...@@ -1326,7 +1319,7 @@ def _check_size(size): ...@@ -1326,7 +1319,7 @@ def _check_size(size):
raise ValueError( raise ValueError(
"Theano variable must have 1 dimension to be a valid size.", size "Theano variable must have 1 dimension to be a valid size.", size
) )
elif isinstance(size, (np.integer, integer_types)): elif isinstance(size, (np.integer, int)):
return tensor.constant([size], ndim=1) return tensor.constant([size], ndim=1)
elif not isinstance(size, (tuple, list)): elif not isinstance(size, (tuple, list)):
raise ValueError("Size must be a int, tuple, list or Theano variable.", size) raise ValueError("Size must be a int, tuple, list or Theano variable.", size)
...@@ -1336,7 +1329,7 @@ def _check_size(size): ...@@ -1336,7 +1329,7 @@ def _check_size(size):
if isinstance(i, theano.Variable): if isinstance(i, theano.Variable):
if i.ndim != 0: if i.ndim != 0:
raise ValueError("Non-scalar Theano variable in size", size, i) raise ValueError("Non-scalar Theano variable in size", size, i)
elif isinstance(i, (np.integer, integer_types)): elif isinstance(i, (np.integer, int)):
if i <= 0: if i <= 0:
raise ValueError( raise ValueError(
"Non-positive dimensions not allowed in size.", size, i "Non-positive dimensions not allowed in size.", size, i
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论