Advertisement
4ever_bored

lenet5.py

Oct 14th, 2016
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.52 KB | None | 0 0
  1. import numpy as np
  2. import theano
  3. import theano.tensor as T
  4. from theano.tensor.signal import pool
  5. from theano.tensor.nnet import conv2d, relu
  6.  
  7. from utils import eprint
  8.  
  9.  
  10. class LeNetConvPoolLayer(object):
  11.     """Pool Layer of a convolutional network """
  12.  
  13.     def __init__(self, rng, input, filter_shape, image_shape, poolsize=(2, 2)):
  14.         """
  15.        Allocate a LeNetConvPoolLayer with shared variable internal parameters.
  16.  
  17.        :type rng: numpy.random.RandomState
  18.        :param rng: a random number generator used to initialize weights
  19.  
  20.        :type input: theano.tensor.dtensor4
  21.        :param input: symbolic image tensor, of shape image_shape
  22.  
  23.        :type filter_shape: tuple or list of length 4
  24.        :param filter_shape: (number of filters, num input feature maps,
  25.                              filter height, filter width)
  26.  
  27.        :type image_shape: tuple or list of length 4
  28.        :param image_shape: (batch size, num input feature maps,
  29.                             image height, image width)
  30.  
  31.        :type poolsize: tuple or list of length 2
  32.        :param poolsize: the downsampling (pooling) factor (#rows, #cols)
  33.        """
  34.  
  35.         assert image_shape[1] == filter_shape[1]
  36.         self.input = input
  37.  
  38.         fan_in = np.prod(filter_shape[1:])
  39.  
  40.         fan_out = (filter_shape[0] * np.prod(filter_shape[2:]) //
  41.                    np.prod(poolsize))
  42.  
  43.         W_bound = np.sqrt(6. / (fan_in + fan_out))
  44.         self.W = theano.shared(
  45.             np.asarray(
  46.                 np.random.uniform(low=-W_bound, high=W_bound, size=filter_shape),
  47.                 dtype=theano.config.floatX  # @UndefinedVariable
  48.             ),
  49.             borrow=True
  50.         )
  51.  
  52.         b_values = np.zeros((filter_shape[0],), dtype=theano.config.floatX)  # @UndefinedVariable
  53.         self.b = theano.shared(value=b_values, borrow=True)
  54.  
  55.         conv_out = conv2d(
  56.             input=self.input,
  57.             filters=self.W,
  58.             filter_shape=filter_shape,
  59.             input_shape=image_shape
  60.         )
  61.  
  62.         # pool each feature map individually, using maxpooling
  63.         pooled_out = pool.pool_2d(
  64.             input=conv_out,
  65.             ds=poolsize,
  66.             ignore_border=True
  67.         )
  68.  
  69.         self.output = relu(pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
  70.  
  71.         self.params = [self.W, self.b]
  72.  
  73.         self.input = input
  74.        
  75.         self.dim0, self.dim1 = self.compute_dims(image_shape[2:],
  76.                                                  filter_shape[2:], poolsize)
  77.        
  78.         return
  79.    
  80.        
  81.     def compute_dims(self, input_shape, filter_shape, pool_size=None,
  82.                          padding='valid'):
  83.    
  84.         if padding == 'valid':
  85.             dim0 = input_shape[0] - filter_shape[0] + 1
  86.             dim1 = input_shape[1] - filter_shape[1] + 1
  87.                
  88.             if pool_size is not None:
  89.                 if dim0%pool_size[0] != 0. or dim1%pool_size[1] != 0.:
  90.                     eprint('Conv2D output dimensions not compatible with pooling size!')
  91.                     eprint('(%d, %d) -> (%d, %d)'
  92.                            %(dim0,dim1,pool_size[0], pool_size[1]))
  93.                    
  94.                 fin_dim0 = dim0/pool_size[0]
  95.                 fin_dim1 = dim1/pool_size[1]
  96.            
  97.             else:
  98.                 fin_dim0 = dim0
  99.                 fin_dim1 = dim1
  100.            
  101.         else:
  102.             fin_dim0 = input_shape[0]
  103.             fin_dim1 = input_shape[1]
  104.  
  105.         return int(fin_dim0), int(fin_dim1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement