提交 5f08407d authored 作者: Pascal Lamblin's avatar Pascal Lamblin

Whitespace

上级 f5ed1817
...@@ -945,4 +945,3 @@ class Test_aliasing_rules(unittest.TestCase): ...@@ -945,4 +945,3 @@ class Test_aliasing_rules(unittest.TestCase):
if __name__ == '__main__': if __name__ == '__main__':
theano.config.mode = 'FAST_COMPILE' theano.config.mode = 'FAST_COMPILE'
Test_pfunc().test_default_scalar_container() Test_pfunc().test_default_scalar_container()
...@@ -42,7 +42,7 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -42,7 +42,7 @@ class Test_SharedVariable(unittest.TestCase):
# generic can hold anything even when strict=True # generic can hold anything even when strict=True
u = shared('asdf', strict=False) u = shared('asdf', strict=False)
v = shared('asdf', strict=True) v = shared('asdf', strict=True)
u.set_value(88) u.set_value(88)
v.set_value(88) v.set_value(88)
...@@ -102,7 +102,7 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -102,7 +102,7 @@ class Test_SharedVariable(unittest.TestCase):
assert numpy.all(u.get_value() == [3,4]) assert numpy.all(u.get_value() == [3,4])
# check that assignments of nonsense fail # check that assignments of nonsense fail
try: try:
u.set_value('adsf') u.set_value('adsf')
assert 0 assert 0
except ValueError: except ValueError:
...@@ -124,7 +124,7 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -124,7 +124,7 @@ class Test_SharedVariable(unittest.TestCase):
b = shared(numpy.int32(7), strict=True) b = shared(numpy.int32(7), strict=True)
assert b.type == theano.tensor.iscalar assert b.type == theano.tensor.iscalar
self.failUnlessRaises(TypeError, f, b, 8.23) self.failUnlessRaises(TypeError, f, b, 8.23)
b = shared(numpy.int16(7), strict=True) b = shared(numpy.int16(7), strict=True)
assert b.type == theano.tensor.wscalar assert b.type == theano.tensor.wscalar
self.failUnlessRaises(TypeError, f, b, 8.23) self.failUnlessRaises(TypeError, f, b, 8.23)
...@@ -235,7 +235,7 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -235,7 +235,7 @@ class Test_SharedVariable(unittest.TestCase):
assert b.type == theano.tensor.dscalar assert b.type == theano.tensor.dscalar
f(b,8) f(b,8)
assert b.get_value()==8 assert b.get_value()==8
b = shared(numpy.float32(7.234), allow_downcast=True) b = shared(numpy.float32(7.234), allow_downcast=True)
assert b.type == theano.tensor.fscalar assert b.type == theano.tensor.fscalar
f(b,8) f(b,8)
...@@ -307,6 +307,3 @@ class Test_SharedVariable(unittest.TestCase): ...@@ -307,6 +307,3 @@ class Test_SharedVariable(unittest.TestCase):
c = shared(numpy.zeros((5,5), dtype='float32'), allow_downcast=True) c = shared(numpy.zeros((5,5), dtype='float32'), allow_downcast=True)
self.failUnlessRaises(TypeError, f, b, numpy.random.rand(5,5)) self.failUnlessRaises(TypeError, f, b, numpy.random.rand(5,5))
...@@ -133,7 +133,7 @@ if 0: ...@@ -133,7 +133,7 @@ if 0:
dmatrix4 = tensor.TensorType("float32", (False, False, False, False)) dmatrix4 = tensor.TensorType("float32", (False, False, False, False))
b = dmatrix4() b = dmatrix4()
f = pfunc([b], [a(b)], mode=mode_with_gpu) f = pfunc([b], [a(b)], mode=mode_with_gpu)
bval = numpy.arange(0,d0*d1).reshape(1,1,d0,d1) bval = numpy.arange(0,d0*d1).reshape(1,1,d0,d1)
r = f(bval)[0] r = f(bval)[0]
# print bval, bval.shape, border # print bval, bval.shape, border
...@@ -143,7 +143,7 @@ if 0: ...@@ -143,7 +143,7 @@ if 0:
def test_downsample(): def test_downsample():
import random import random
shps = [ (1, 1, 1, 12), shps = [ (1, 1, 1, 12),
(1, 1, 2, 2), (1, 1, 2, 2),
(1, 1, 1, 1), (1, 1, 1, 1),
(1,1,4,4), (1,1,4,4),
(1, 1, 10, 11), (1, 1, 10, 11),
...@@ -181,7 +181,7 @@ def test_downsample(): ...@@ -181,7 +181,7 @@ def test_downsample():
assert any([isinstance(node.op, tcn.blas.GpuDownsampleFactorMax) for node in assert any([isinstance(node.op, tcn.blas.GpuDownsampleFactorMax) for node in
f.maker.env.toposort()]) f.maker.env.toposort()])
assert numpy.allclose(f(),f2()) assert numpy.allclose(f(),f2())
g = pfunc([], tensor.grad(ds_op(tensor.as_tensor_variable(a)).sum(),a), mode=mode_with_gpu) g = pfunc([], tensor.grad(ds_op(tensor.as_tensor_variable(a)).sum(),a), mode=mode_with_gpu)
g2 = pfunc([], tensor.grad(ds_op(tensor.as_tensor_variable(a)).sum(),a), mode=mode_without_gpu) g2 = pfunc([], tensor.grad(ds_op(tensor.as_tensor_variable(a)).sum(),a), mode=mode_without_gpu)
assert any([isinstance(node.op, tcn.blas.GpuDownsampleFactorMaxGrad) assert any([isinstance(node.op, tcn.blas.GpuDownsampleFactorMaxGrad)
...@@ -190,6 +190,3 @@ def test_downsample(): ...@@ -190,6 +190,3 @@ def test_downsample():
#We already check that the gpu version return the same value as the gpu version #We already check that the gpu version return the same value as the gpu version
#for GpuDownsampleFactorMaxGrad. So no need to call verify_grad here. #for GpuDownsampleFactorMaxGrad. So no need to call verify_grad here.
...@@ -13,7 +13,7 @@ from theano.gof.python25 import any ...@@ -13,7 +13,7 @@ from theano.gof.python25 import any
def gen_data(): def gen_data():
# generate the dataset # generate the dataset
train_set=(numpy.asarray(numpy.random.rand(10000,784),dtype='float32'), train_set=(numpy.asarray(numpy.random.rand(10000,784),dtype='float32'),
numpy.asarray(numpy.random.rand(10000)*10,dtype='int64')) numpy.asarray(numpy.random.rand(10000)*10,dtype='int64'))
valid_set=(numpy.asarray(numpy.random.rand(10000,784),dtype='float32'), valid_set=(numpy.asarray(numpy.random.rand(10000,784),dtype='float32'),
...@@ -22,11 +22,11 @@ def gen_data(): ...@@ -22,11 +22,11 @@ def gen_data():
numpy.asarray(numpy.random.rand(10000)*10,dtype='int64')) numpy.asarray(numpy.random.rand(10000)*10,dtype='int64'))
def shared_dataset(data_xy): def shared_dataset(data_xy):
""" Function that loads the dataset into shared variables """ Function that loads the dataset into shared variables
The reason we store our dataset in shared variables is to allow The reason we store our dataset in shared variables is to allow
Theano to copy it into the GPU memory (when code is run on GPU). Theano to copy it into the GPU memory (when code is run on GPU).
Since copying data into the GPU is slow, copying a minibatch everytime Since copying data into the GPU is slow, copying a minibatch everytime
is needed (the default behaviour if the data is not in a shared is needed (the default behaviour if the data is not in a shared
variable) would lead to a large decrease in performance. variable) would lead to a large decrease in performance.
""" """
data_x, data_y = data_xy data_x, data_y = data_xy
...@@ -35,8 +35,8 @@ def gen_data(): ...@@ -35,8 +35,8 @@ def gen_data():
# When storing data on the GPU it has to be stored as floats # When storing data on the GPU it has to be stored as floats
# therefore we will store the labels as ``floatX`` as well # therefore we will store the labels as ``floatX`` as well
# (``shared_y`` does exactly that). But during our computations # (``shared_y`` does exactly that). But during our computations
# we need them as ints (we use labels as index, and if they are # we need them as ints (we use labels as index, and if they are
# floats it doesn't make sense) therefore instead of returning # floats it doesn't make sense) therefore instead of returning
# ``shared_y`` we will have to cast it to int. This little hack # ``shared_y`` we will have to cast it to int. This little hack
# lets ous get around this issue # lets ous get around this issue
return shared_x, T.cast(shared_y, 'int32') return shared_x, T.cast(shared_y, 'int32')
...@@ -51,10 +51,10 @@ def gen_data(): ...@@ -51,10 +51,10 @@ def gen_data():
class LogisticRegression(object): class LogisticRegression(object):
"""Multi-class Logistic Regression Class """Multi-class Logistic Regression Class
The logistic regression is fully described by a weight matrix :math:`W` The logistic regression is fully described by a weight matrix :math:`W`
and bias vector :math:`b`. Classification is done by projecting data and bias vector :math:`b`. Classification is done by projecting data
points onto a set of hyperplanes, the distance to which is used to points onto a set of hyperplanes, the distance to which is used to
determine a class membership probability. determine a class membership probability.
""" """
...@@ -64,27 +64,27 @@ class LogisticRegression(object): ...@@ -64,27 +64,27 @@ class LogisticRegression(object):
""" Initialize the parameters of the logistic regression """ Initialize the parameters of the logistic regression
:type input: theano.tensor.TensorType :type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the :param input: symbolic variable that describes the input of the
architecture (one minibatch) architecture (one minibatch)
:type n_in: int :type n_in: int
:param n_in: number of input units, the dimension of the space in :param n_in: number of input units, the dimension of the space in
which the datapoints lie which the datapoints lie
:type n_out: int :type n_out: int
:param n_out: number of output units, the dimension of the space in :param n_out: number of output units, the dimension of the space in
which the labels lie which the labels lie
""" """
# initialize with 0 the weights W as a matrix of shape (n_in, n_out) # initialize with 0 the weights W as a matrix of shape (n_in, n_out)
self.W = theano.shared(value=numpy.zeros((n_in,n_out), dtype = theano.config.floatX), self.W = theano.shared(value=numpy.zeros((n_in,n_out), dtype = theano.config.floatX),
name=name_prefix+'W') name=name_prefix+'W')
# compute vector of class-membership probabilities in symbolic form # compute vector of class-membership probabilities in symbolic form
self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W)) self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W))
# compute prediction as class whose probability is maximal in # compute prediction as class whose probability is maximal in
# symbolic form # symbolic form
self.y_pred=T.argmax(self.p_y_given_x, axis=1) self.y_pred=T.argmax(self.p_y_given_x, axis=1)
...@@ -114,7 +114,7 @@ class LogisticRegression(object): ...@@ -114,7 +114,7 @@ class LogisticRegression(object):
""" """
# y.shape[0] is (symbolically) the number of rows in y, i.e., number of examples (call it n) in the minibatch # y.shape[0] is (symbolically) the number of rows in y, i.e., number of examples (call it n) in the minibatch
# T.arange(y.shape[0]) is a symbolic vector which will contain [0,1,2,... n-1] # T.arange(y.shape[0]) is a symbolic vector which will contain [0,1,2,... n-1]
# T.log(self.p_y_given_x) is a matrix of Log-Probabilities (call it LP) with one row per example and one column per class # T.log(self.p_y_given_x) is a matrix of Log-Probabilities (call it LP) with one row per example and one column per class
# LP[T.arange(y.shape[0]),y] is a vector v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ..., LP[n-1,y[n-1]]] # LP[T.arange(y.shape[0]),y] is a vector v containing [LP[0,y[0]], LP[1,y[1]], LP[2,y[2]], ..., LP[n-1,y[n-1]]]
# and T.mean(LP[T.arange(y.shape[0]),y]) is the mean (across minibatch examples) of the elements in v, # and T.mean(LP[T.arange(y.shape[0]),y]) is the mean (across minibatch examples) of the elements in v,
# i.e., the mean log-likelihood across the minibatch. # i.e., the mean log-likelihood across the minibatch.
...@@ -129,7 +129,7 @@ class HiddenLayer(object): ...@@ -129,7 +129,7 @@ class HiddenLayer(object):
and the bias vector b is of shape (n_out,). and the bias vector b is of shape (n_out,).
NOTE : The nonlinearity used here is tanh NOTE : The nonlinearity used here is tanh
Hidden unit activation is given by: tanh(dot(input,W) + b) Hidden unit activation is given by: tanh(dot(input,W) + b)
:type rng: numpy.random.RandomState :type rng: numpy.random.RandomState
...@@ -145,14 +145,14 @@ class HiddenLayer(object): ...@@ -145,14 +145,14 @@ class HiddenLayer(object):
:param n_out: number of hidden units :param n_out: number of hidden units
:type activation: theano.Op or function :type activation: theano.Op or function
:param activation: Non linearity to be applied in the hidden :param activation: Non linearity to be applied in the hidden
layer layer
""" """
self.input = input self.input = input
# `W` is initialized with `W_values` which is uniformely sampled # `W` is initialized with `W_values` which is uniformely sampled
# from -6./sqrt(n_in+n_hidden) and 6./sqrt(n_in+n_hidden) # from -6./sqrt(n_in+n_hidden) and 6./sqrt(n_in+n_hidden)
# the output of uniform if converted using asarray to dtype # the output of uniform if converted using asarray to dtype
# theano.config.floatX so that the code is runable on GPU # theano.config.floatX so that the code is runable on GPU
W_values = numpy.asarray( rng.uniform( \ W_values = numpy.asarray( rng.uniform( \
low = -numpy.sqrt(6./(n_in+n_out)), \ low = -numpy.sqrt(6./(n_in+n_out)), \
...@@ -168,12 +168,12 @@ class HiddenLayer(object): ...@@ -168,12 +168,12 @@ class HiddenLayer(object):
class MLP(object): class MLP(object):
"""Multi-Layer Perceptron Class """Multi-Layer Perceptron Class
A multilayer perceptron is a feedforward artificial neural network model A multilayer perceptron is a feedforward artificial neural network model
that has one layer or more of hidden units and nonlinear activations. that has one layer or more of hidden units and nonlinear activations.
Intermidiate layers usually have as activation function thanh or the Intermidiate layers usually have as activation function thanh or the
sigmoid function (defined here by a ``SigmoidalLayer`` class) while the sigmoid function (defined here by a ``SigmoidalLayer`` class) while the
top layer is a softamx layer (defined here by a ``LogisticRegression`` top layer is a softamx layer (defined here by a ``LogisticRegression``
class). class).
""" """
...@@ -185,39 +185,39 @@ class MLP(object): ...@@ -185,39 +185,39 @@ class MLP(object):
:param rng: a random number generator used to initialize weights :param rng: a random number generator used to initialize weights
:type input: theano.tensor.TensorType :type input: theano.tensor.TensorType
:param input: symbolic variable that describes the input of the :param input: symbolic variable that describes the input of the
architecture (one minibatch) architecture (one minibatch)
:type n_in: int :type n_in: int
:param n_in: number of input units, the dimension of the space in :param n_in: number of input units, the dimension of the space in
which the datapoints lie which the datapoints lie
:type n_hidden: int :type n_hidden: int
:param n_hidden: number of hidden units :param n_hidden: number of hidden units
:type n_out: int :type n_out: int
:param n_out: number of output units, the dimension of the space in :param n_out: number of output units, the dimension of the space in
which the labels lie which the labels lie
""" """
# Since we are dealing with a one hidden layer MLP, this will # Since we are dealing with a one hidden layer MLP, this will
# translate into a TanhLayer connected to the LogisticRegression # translate into a TanhLayer connected to the LogisticRegression
# layer; this can be replaced by a SigmoidalLayer, or a layer # layer; this can be replaced by a SigmoidalLayer, or a layer
# implementing any other nonlinearity # implementing any other nonlinearity
self.hiddenLayer = HiddenLayer(rng = rng, input = input, self.hiddenLayer = HiddenLayer(rng = rng, input = input,
n_in = n_in, n_out = n_hidden, n_in = n_in, n_out = n_hidden,
activation = T.tanh, name_prefix='hid_') activation = T.tanh, name_prefix='hid_')
# The logistic regression layer gets as input the hidden units # The logistic regression layer gets as input the hidden units
# of the hidden layer # of the hidden layer
self.logRegressionLayer = LogisticRegression( self.logRegressionLayer = LogisticRegression(
input = self.hiddenLayer.output, input = self.hiddenLayer.output,
n_in = n_hidden, n_in = n_hidden,
n_out = n_out, name_prefix='log_') n_out = n_out, name_prefix='log_')
# negative log likelihood of the MLP is given by the negative # negative log likelihood of the MLP is given by the negative
# log likelihood of the output of the model, computed in the # log likelihood of the output of the model, computed in the
# logistic regression layer # logistic regression layer
self.negative_log_likelihood = self.logRegressionLayer.negative_log_likelihood self.negative_log_likelihood = self.logRegressionLayer.negative_log_likelihood
...@@ -228,20 +228,20 @@ class MLP(object): ...@@ -228,20 +228,20 @@ class MLP(object):
def test_mlp(): def test_mlp():
""" """
Demonstrate stochastic gradient descent optimization for a multilayer Demonstrate stochastic gradient descent optimization for a multilayer
perceptron perceptron
This is demonstrated on MNIST. This is demonstrated on MNIST.
:type learning_rate: float :type learning_rate: float
:param learning_rate: learning rate used (factor for the stochastic :param learning_rate: learning rate used (factor for the stochastic
gradient gradient
:type n_epochs: int :type n_epochs: int
:param n_epochs: maximal number of epochs to run the optimizer :param n_epochs: maximal number of epochs to run the optimizer
:type dataset: string :type dataset: string
:param dataset: the path of the MNIST dataset file from :param dataset: the path of the MNIST dataset file from
http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz
...@@ -263,13 +263,13 @@ def test_mlp(): ...@@ -263,13 +263,13 @@ def test_mlp():
###################### ######################
# BUILD ACTUAL MODEL # # BUILD ACTUAL MODEL #
###################### ######################
print '... building the model' print '... building the model'
# allocate symbolic variables for the data # allocate symbolic variables for the data
index = T.lscalar() # index to a [mini]batch index = T.lscalar() # index to a [mini]batch
x = T.matrix('x') # the data is presented as rasterized images x = T.matrix('x') # the data is presented as rasterized images
y = T.ivector('y') # the labels are presented as 1D vector of y = T.ivector('y') # the labels are presented as 1D vector of
# [int] labels # [int] labels
rng = numpy.random.RandomState(1234) rng = numpy.random.RandomState(1234)
...@@ -277,7 +277,7 @@ def test_mlp(): ...@@ -277,7 +277,7 @@ def test_mlp():
# construct the MLP class # construct the MLP class
classifier = MLP( rng = rng, input=x, n_in=28*28, n_hidden = 500, n_out=10) classifier = MLP( rng = rng, input=x, n_in=28*28, n_hidden = 500, n_out=10)
# the cost we minimize during training is the negative log likelihood of # the cost we minimize during training is the negative log likelihood of
# the model. # the model.
# We take the mean of the cost over each minibatch. # We take the mean of the cost over each minibatch.
cost = classifier.negative_log_likelihood(y).mean() cost = classifier.negative_log_likelihood(y).mean()
...@@ -312,11 +312,10 @@ def test_mlp(): ...@@ -312,11 +312,10 @@ def test_mlp():
givens={ givens={
x:train_set_x[index*batch_size:(index+1)*batch_size], x:train_set_x[index*batch_size:(index+1)*batch_size],
y:train_set_y[index*batch_size:(index+1)*batch_size]}) y:train_set_y[index*batch_size:(index+1)*batch_size]})
print print
for i in train_model.maker.env.toposort(): print i for i in train_model.maker.env.toposort(): print i
assert not any( [isinstance(i.op,T.nnet.CrossentropySoftmax1HotWithBiasDx) for i in train_model.maker.env.toposort()]) assert not any( [isinstance(i.op,T.nnet.CrossentropySoftmax1HotWithBiasDx) for i in train_model.maker.env.toposort()])
if __name__ == '__main__': if __name__ == '__main__':
test_mlp() test_mlp()
...@@ -61,7 +61,7 @@ class multiple_outputs_numeric_grad: ...@@ -61,7 +61,7 @@ class multiple_outputs_numeric_grad:
# something else ( a random state ? ) with which we shouldn't really # something else ( a random state ? ) with which we shouldn't really
# mess up # mess up
if not ndarray_mask: if not ndarray_mask:
ndarray_mask = [True for x in pt ] ndarray_mask = [True for x in pt ]
dtype_eps = multiple_outputs_numeric_grad.type_eps['float64'] dtype_eps = multiple_outputs_numeric_grad.type_eps['float64']
...@@ -70,7 +70,7 @@ class multiple_outputs_numeric_grad: ...@@ -70,7 +70,7 @@ class multiple_outputs_numeric_grad:
pt[i] = numpy.array(p) pt[i] = numpy.array(p)
_eps = multiple_outputs_numeric_grad.type_eps[str(pt[i].dtype)] _eps = multiple_outputs_numeric_grad.type_eps[str(pt[i].dtype)]
if _eps > dtype_eps: if _eps > dtype_eps:
dtype_eps = _eps dtype_eps = _eps
# Compute clean output: # Compute clean output:
...@@ -1050,7 +1050,7 @@ class T_Scan(unittest.TestCase): ...@@ -1050,7 +1050,7 @@ class T_Scan(unittest.TestCase):
f1 = theano.tensor.dscalar('f1') f1 = theano.tensor.dscalar('f1')
def scanStep(prev, seq, f1): def scanStep(prev, seq, f1):
return prev + f1 * seq return prev + f1 * seq
scanned, _ = theano.scan(fn = scanStep, \ scanned, _ = theano.scan(fn = scanStep, \
sequences = [seq], \ sequences = [seq], \
...@@ -1074,8 +1074,8 @@ class T_Scan(unittest.TestCase): ...@@ -1074,8 +1074,8 @@ class T_Scan(unittest.TestCase):
inpt = theano.tensor.matrix('inpt') inpt = theano.tensor.matrix('inpt')
def one_step(x_t, h_tm1, W): def one_step(x_t, h_tm1, W):
expr = T.dot(h_tm1, W) + x_t expr = T.dot(h_tm1, W) + x_t
return expr return expr
expr, _ = theano.scan( expr, _ = theano.scan(
fn=one_step, fn=one_step,
...@@ -1114,7 +1114,7 @@ class T_Scan(unittest.TestCase): ...@@ -1114,7 +1114,7 @@ class T_Scan(unittest.TestCase):
floatX = theano.config.floatX floatX = theano.config.floatX
def one_step( h_tm1): def one_step( h_tm1):
return h_tm1 + numpy.asarray(1., dtype=floatX) return h_tm1 + numpy.asarray(1., dtype=floatX)
h, _ = theano.scan( h, _ = theano.scan(
fn=one_step, fn=one_step,
...@@ -1131,4 +1131,3 @@ class T_Scan(unittest.TestCase): ...@@ -1131,4 +1131,3 @@ class T_Scan(unittest.TestCase):
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论