I started here: Deep Learning tutorial


In [1]:
import theano

In [19]:
import theano.tensor as T 
# cf. https://github.com/lisa-lab/DeepLearningTutorials/blob/c4db2098e6620a0ac393f291ec4dc524375e96fd/code/logistic_sgd.py

cf. 3.2 Datasets, 3.2.1 MNIST Dataset


In [2]:
import cPickle, gzip, numpy

In [1]:
import os

In [16]:
os.getcwd()


Out[16]:
'/home/topolo/PropD/MLgrabbag'

In [5]:
os.listdir( os.getcwd() )


Out[5]:
['LogReg-sklearn.ipynb',
 'LICENSE',
 'deeplearning.pdf',
 'LaTeXandpdfs',
 'supervised-theano.ipynb',
 '.git',
 'README.md',
 '.ipynb_checkpoints',
 'Data']

In [6]:
f = gzip.open('./Data/mnist.pkl.gz')

In [7]:
train_set, valid_set, test_set = cPickle.load(f)

In [8]:
f.close()

In [10]:
type(train_set), type(valid_set), type(test_set)


Out[10]:
(tuple, tuple, tuple)

In [16]:
type(train_set[0]), type(train_set[1])


Out[16]:
(numpy.ndarray, numpy.ndarray)

In [20]:
def shared_dataset(data_xy):
    """ 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 behavior 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 = theano.shared(numpy.asarray(data_x, dtype=theano.config.floatX))
    shared_y = theano.shared(numpy.asarray(data_y, dtype=theano.config.floatX))
    # 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 ahve to cast it to int.  This little hack
    # lets us get around this issue
    
    return shared_x, T.cast(shared_y, 'int32')

In [21]:
test_set_x, test_set_y = shared_dataset(test_set)
valid_set_x, valid_set_y = shared_dataset(valid_set)
train_set_x, train_set_y = shared_dataset(train_set)

In [22]:
batch_size = 500    # size of the minibatch

# accessing the third minibatch of the training set

data  = train_set_x[2 * batch_size: 3 * batch_size]
label = train_set_y[2 * batch_size: 3 * batch_size]

In [24]:
dir(train_set_x)


Out[24]:
['T',
 '__abs__',
 '__add__',
 '__and__',
 '__array_priority__',
 '__bool__',
 '__class__',
 '__count__',
 '__delattr__',
 '__dict__',
 '__div__',
 '__divmod__',
 '__doc__',
 '__dot__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__init__',
 '__invert__',
 '__iter__',
 '__le__',
 '__lt__',
 '__mod__',
 '__module__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__nonzero__',
 '__or__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdiv__',
 '__rdivmod__',
 '__rdot__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__repr_test_value__',
 '__rfloordiv__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__rpow__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__slots__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__weakref__',
 '__xor__',
 '_is_nonzero',
 '_value_get',
 '_value_set',
 'all',
 'any',
 'arccos',
 'arccosh',
 'arcsin',
 'arcsinh',
 'arctan',
 'arctanh',
 'argmax',
 'argmin',
 'argsort',
 'astype',
 'auto_name',
 'broadcastable',
 'ceil',
 'choose',
 'clip',
 'clone',
 'compress',
 'conj',
 'conjugate',
 'container',
 'copy',
 'cos',
 'cosh',
 'cumprod',
 'cumsum',
 'deg2rad',
 'diagonal',
 'dimshuffle',
 'dot',
 'dtype',
 'eval',
 'exp',
 'exp2',
 'expm1',
 'fill',
 'flatten',
 'floor',
 'get_parents',
 'get_scalar_constant_value',
 'get_value',
 'imag',
 'index',
 'log',
 'log10',
 'log1p',
 'log2',
 'max',
 'mean',
 'min',
 'name',
 'ndim',
 'nonzero',
 'nonzero_values',
 'norm',
 'owner',
 'prod',
 'ptp',
 'rad2deg',
 'ravel',
 'real',
 'repeat',
 'reshape',
 'round',
 'set_value',
 'shape',
 'sin',
 'sinh',
 'size',
 'sort',
 'sqrt',
 'squeeze',
 'std',
 'sum',
 'swapaxes',
 'tag',
 'take',
 'tan',
 'tanh',
 'trace',
 'transfer',
 'transpose',
 'trunc',
 'type',
 'value',
 'var',
 'zero',
 'zeros_like']

GPU note

Using the GPU

THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python myscriptIwanttorunonthegpu.py

From theano's documentation, "Using the GPU", "Only computations with float32 data-type can be accelerated. Better support for float64 is expected in upcoming hardware, but float64 computations are still relatively slow (Jan 2010)." Hence floatX=float32.

I ran the script logistic_sgd.py locally, that's found in DeepLearningTutorials from lisa-lab's github


In [8]:
os.listdir("../DeepLearningTutorials/code")


Out[8]:
['imdb.py',
 'rbm.py',
 'utils.py',
 'logistic_sgd.pyc',
 'logistic_cg.py',
 'mlp.py',
 'imdb_preprocess.py',
 'dA.py',
 'SdA.py',
 'logistic_sgd.py',
 'convolutional_mlp.py',
 'cA.py',
 'test.py',
 'rnnslu.py',
 'hmc',
 'DBN.py',
 'best_model.pkl',
 'lstm.py',
 'rnnrbm.py']

In [6]:
import subprocess

In [10]:
subprocess.call(['python','../DeepLearningTutorials/code/logistic_sgd.py'])


Out[10]:
0

In [9]:
subprocess.call(['THEANO_FLAGS=device=gpu,floatX=float32 python', 
                 '../DeepLearningTutorials/code/logistic_sgd.py'])


---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-9-5c38181a230c> in <module>()
      1 subprocess.call(['THEANO_FLAGS=device=gpu,floatX=float32 python', 
----> 2                  '../DeepLearningTutorials/code/logistic_sgd.py'])

/home/topolo/Public/anaconda2/lib/python2.7/subprocess.pyc in call(*popenargs, **kwargs)
    520     retcode = call(["ls", "-l"])
    521     """
--> 522     return Popen(*popenargs, **kwargs).wait()
    523 
    524 

/home/topolo/Public/anaconda2/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
    708                                 p2cread, p2cwrite,
    709                                 c2pread, c2pwrite,
--> 710                                 errread, errwrite)
    711         except Exception:
    712             # Preserve original exception in case os.close raises.

/home/topolo/Public/anaconda2/lib/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, to_close, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
   1333                         raise
   1334                 child_exception = pickle.loads(data)
-> 1335                 raise child_exception
   1336 
   1337 

OSError: [Errno 2] No such file or directory

In [15]:
execfile('../DeepLearningTutorials/code/logistic_sgd_b.py')


Downloading data from http://www.iro.umontreal.ca/~lisa/deep/data/mnist/mnist.pkl.gz
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-15-e874ffb309e2> in <module>()
----> 1 execfile('../DeepLearningTutorials/code/logistic_sgd_b.py')

/home/topolo/PropD/DeepLearningTutorials/code/logistic_sgd_b.py in <module>()
    473 
    474 if __name__ == '__main__':
--> 475     sgd_optimization_mnist()

/home/topolo/PropD/DeepLearningTutorials/code/logistic_sgd_b.py in sgd_optimization_mnist(learning_rate, n_epochs, dataset, batch_size)
    275 
    276     """
--> 277     datasets = load_data(dataset)
    278 
    279     train_set_x, train_set_y = datasets[0]

/home/topolo/PropD/DeepLearningTutorials/code/logistic_sgd_b.py in load_data(dataset)
    203         )
    204         print('Downloading data from %s' % origin)
--> 205         urllib.request.urlretrieve(origin, dataset)
    206 
    207     print('... loading data')

/home/topolo/Public/anaconda2/lib/python2.7/urllib.pyc in urlretrieve(url, filename, reporthook, data, context)
     96     else:
     97         opener = _urlopener
---> 98     return opener.retrieve(url, filename, reporthook, data)
     99 def urlcleanup():
    100     if _urlopener:

/home/topolo/Public/anaconda2/lib/python2.7/urllib.pyc in retrieve(self, url, filename, reporthook, data)
    247             headers = fp.info()
    248             if filename:
--> 249                 tfp = open(filename, 'wb')
    250             else:
    251                 import tempfile

IOError: [Errno 2] No such file or directory: '../data/mnist.pkl.gz'

In [18]:
os.listdir( '../' )


Out[18]:
['CUDACFD_out',
 'cantera',
 'CompPhys',
 'setup.py.in',
 'Propulsion',
 'DeepLearningTutorials',
 'cs344',
 'MLgrabbag',
 'OpenNN',
 'thrust']

In [19]:
import sklearn

In [ ]: