Example #1
0
    def __init__(self, input, n_in, n_out):
        """ Initialize the parameters of the logistic regression

        :type input: my_theano.tensor.TensorType
        :param input: symbolic variable that describes the input of the
                      architecture (one minibatch)

        :type n_in: int
        :param n_in: number of input units, the dimension of the space in
                     which the datapoints lie

        :type n_out: int
        :param n_out: number of output units, the dimension of the space in
                      which the labels lie

        """
        # start-snippet-1
        # initialize with 0 the weights W as a matrix of shape (n_in, n_out)
        self.W = my_theano.shared(
            value=numpy.zeros(
                (n_in, n_out),
                dtype=my_theano.config.floatX
            ),
            name='W',
            borrow=True
        )
        # initialize the biases b as a vector of n_out 0s
        self.b = my_theano.shared(
            value=numpy.zeros(
                (n_out,),
                dtype=my_theano.config.floatX
            ),
            name='b',
            borrow=True
        )

        # symbolic expression for computing the matrix of class-membership
        # probabilities
        # Where:
        # W is a matrix where column-k represent the separation hyperplane for
        # class-k
        # x is a matrix where row-j  represents input training sample-j
        # b is a vector where element-k represent the free parameter of
        # hyperplane-k
        self.p_y_given_x = T.nnet.softmax(T.dot(input, self.W) + self.b)

        # symbolic description of how to compute prediction as class whose
        # probability is maximal
        self.y_pred = T.argmax(self.p_y_given_x, axis=1)
        # end-snippet-1

        # parameters of the model
        self.params = [self.W, self.b]

        # keep track of model input
        self.input = input
Example #2
0
    def weights_init_func(self, rng, n_inputs, n_outputs, shape=None):
        if shape is None:
            shape = (n_inputs, n_outputs)
        w_values = np.asarray(rng.uniform(
            low=-np.sqrt(6. / (n_inputs + n_outputs)),
            high=np.sqrt(6. / (n_inputs + n_outputs)),
            size=shape),
                              dtype=my_theano.config.floatX)

        w_values *= 4

        w = my_theano.shared(value=w_values, name='W', borrow=True)
        return w
Example #3
0
    def shared_dataset(data_xy, borrow=True):
        """ Function that loads the dataset into shared variables

        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).
        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
        variable) would lead to a large decrease in performance.
        """
        data_x, data_y = data_xy
        shared_x = my_theano.shared(numpy.asarray(data_x,
                                                  dtype=my_theano.config.floatX),
                                    borrow=borrow)
        shared_y = my_theano.shared(numpy.asarray(data_y,
                                                  dtype=my_theano.config.floatX),
                                    borrow=borrow)
        # When storing data on the GPU it has to be stored as floats
        # therefore we will store the labels as ``floatX`` as well
        # (``shared_y`` does exactly that). But during our computations
        # we need them as ints (we use labels as index, and if they are
        # floats it doesn't make sense) therefore instead of returning
        # ``shared_y`` we will have to cast it to int. This little hack
        # lets ous get around this issue
        return shared_x, T.cast(shared_y, 'int32')
Example #4
0
    def weights_init_func(self, rng, n_inputs, n_outputs, shape=None):
        """
        :param rng: passed random state to generate random values
        :param n_inputs: number of inputs
        """
        if shape is None:
            shape = (n_inputs, n_outputs)
        w_values = np.asarray(rng.uniform(
            low=-np.sqrt(6. / (n_inputs + n_outputs)),
            high=np.sqrt(6. / (n_inputs + n_outputs)),
            size=shape),
                              dtype=my_theano.config.floatX)

        w = my_theano.shared(value=w_values, name='W', borrow=True)
        return w
Example #5
0
    def weights_init_func(self, rng, n_inputs, n_outputs, shape=None):
        if shape is None:
            shape = (n_inputs, n_outputs)
        w_values = np.asarray(
            rng.uniform(
                low=-np.sqrt(6. / (n_inputs + n_outputs)),
                high=np.sqrt(6. / (n_inputs + n_outputs)),
                size=shape
            ),
            dtype=my_theano.config.floatX
        )

        w_values *= 4

        w = my_theano.shared(value=w_values, name='W', borrow=True)
        return w
Example #6
0
    def weights_init_func(self, rng, n_inputs, n_outputs, shape=None):
        """
        :param rng: passed random state to generate random values
        :param n_inputs: number of inputs
        """
        if shape is None:
            shape = (n_inputs, n_outputs)
        w_values = np.asarray(
            rng.uniform(
                low=-np.sqrt(6. / (n_inputs + n_outputs)),
                high=np.sqrt(6. / (n_inputs + n_outputs)),
                size=shape
            ),
            dtype=my_theano.config.floatX
        )

        w = my_theano.shared(value=w_values, name='W', borrow=True)
        return w
Example #7
0
File: mlp.py Project: yxiaohan/nn
    def __init__(self, rng, input, n_in, n_out, W=None, b=None,
                 activation=T.tanh):
        """
        Typical hidden layer of a MLP: units are fully-connected and have
        sigmoidal activation function. Weight matrix W is of shape (n_in,n_out)
        and the bias vector b is of shape (n_out,).

        NOTE : The nonlinearity used here is tanh

        Hidden unit activation is given by: tanh(dot(input,W) + b)

        :type rng: numpy.random.RandomState
        :param rng: a random number generator used to initialize weights

        :type input: my_theano.tensor.dmatrix
        :param input: a symbolic tensor of shape (n_examples, n_in)

        :type n_in: int
        :param n_in: dimensionality of input

        :type n_out: int
        :param n_out: number of hidden units

        :type activation: my_theano.Op or function
        :param activation: Non linearity to be applied in the hidden
                           layer
        """
        self.input = input
        # end-snippet-1

        # `W` is initialized with `W_values` which is uniformely sampled
        # from sqrt(-6./(n_in+n_hidden)) and sqrt(6./(n_in+n_hidden))
        # for tanh activation function
        # the output of uniform if converted using asarray to dtype
        # my_theano.config.floatX so that the code is runable on GPU
        # Note : optimal initialization of weights is dependent on the
        #        activation function used (among other things).
        #        For example, results presented in [Xavier10] suggest that you
        #        should use 4 times larger initial weights for sigmoid
        #        compared to tanh
        #        We have no info for other function, so we use the same as
        #        tanh.
        if W is None:
            W_values = numpy.asarray(
                rng.uniform(
                    low=-numpy.sqrt(6. / (n_in + n_out)),
                    high=numpy.sqrt(6. / (n_in + n_out)),
                    size=(n_in, n_out)
                ),
                dtype=my_theano.config.floatX
            )
            if activation == my_theano.tensor.nnet.sigmoid:
                W_values *= 4

            W = my_theano.shared(value=W_values, name='W', borrow=True)

        if b is None:
            b_values = numpy.zeros((n_out,), dtype=my_theano.config.floatX)
            b = my_theano.shared(value=b_values, name='b', borrow=True)

        self.W = W
        self.b = b

        lin_output = T.dot(input, self.W) + self.b
        self.output = (
            lin_output if activation is None
            else activation(lin_output)
        )
        # parameters of the model
        self.params = [self.W, self.b]
Example #8
0
from my_theano import function, config, shared, sandbox
import my_theano.sandbox.cuda.basic_ops
import my_theano.tensor as T
import numpy
import time

vlen = 10 * 30 * 768  # 10 x #cores x # threads per core
iters = 1000

rng = numpy.random.RandomState(22)
x = shared(numpy.asarray(rng.rand(vlen), 'float32'))
f = function([], T.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in range(iters):
    r = f()
t1 = time.time()
print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
print("Numpy result is %s" % (numpy.asarray(r),))
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
    print('Used the cpu')
else:
    print('Used the gpu')