# HG changeset patch # User savardf # Date 1268147719 18000 # Node ID dc0d77c8a87807f9eaba6439698441f880eb8f50 # Parent d982dfa583dfb3040a06a9e670bb750419adb4c9 Commented table_series code, changed ParamsStatisticsArray to take shared params instead, create DummySeries to use when we don't want to save a named series diff -r d982dfa583df -r dc0d77c8a878 utils/tables_series/__init__.py --- a/utils/tables_series/__init__.py Fri Mar 05 18:08:34 2010 -0500 +++ b/utils/tables_series/__init__.py Tue Mar 09 10:15:19 2010 -0500 @@ -1,2 +1,2 @@ -from series import ErrorSeries, BasicStatisticsSeries, AccumulatorSeriesWrapper, SeriesArrayWrapper, ParamsStatisticsWrapper +from series import ErrorSeries, BasicStatisticsSeries, AccumulatorSeriesWrapper, SeriesArrayWrapper, SharedParamsStatisticsWrapper, DummySeries diff -r d982dfa583df -r dc0d77c8a878 utils/tables_series/series.py --- a/utils/tables_series/series.py Fri Mar 05 18:08:34 2010 -0500 +++ b/utils/tables_series/series.py Tue Mar 09 10:15:19 2010 -0500 @@ -12,6 +12,12 @@ ''' def get_beginning_description_n_ints(int_names, int_width=64): + """ + Begins construction of a class inheriting from IsDescription + to construct an HDF5 table with index columns named with int_names. + + See Series().__init__ to see how those are used. + """ int_constructor = "Int64Col" if int_width == 32: int_constructor = "Int32Col" @@ -66,7 +72,21 @@ class Series(): def __init__(self, table_name, hdf5_file, index_names=('epoch',), title=None, hdf5_group='/'): - """This is used as metadata in the HDF5 file to identify the series""" + """Basic arguments each Series must get. + + Parameters + ---------- + table_name : str + Name of the table to create under group "hd5_group" (other parameter). No spaces, ie. follow variable naming restrictions. + hdf5_file : open HDF5 file + File opened with openFile() in PyTables (ie. return value of openFile). + index_names : tuple of str + Columns to use as index for elements in the series, other example would be ('epoch', 'minibatch'). This would then allow you to call append(index, element) with index made of two ints, one for epoch index, one for minibatch index in epoch. + title : str + Title to attach to this table as metadata. Can contain spaces and be longer then the table_name. + hdf5_group : str + Path of the group (kind of a file) in the HDF5 file under which to create the table. + """ self.table_name = table_name self.hdf5_file = hdf5_file self.index_names = index_names @@ -75,6 +95,12 @@ def append(self, index, element): raise NotImplementedError +# To put in a series dictionary instead of a real series, to do nothing +# when we don't want a given series to be saved. +class DummySeries(): + def append(self, index, element): + pass + class ErrorSeries(Series): def __init__(self, error_name, table_name, hdf5_file, index_names=('epoch',), title=None, hdf5_group='/'): Series.__init__(self, table_name, hdf5_file, index_names, title) @@ -89,12 +115,21 @@ return get_description_with_n_ints_n_floats(self.index_names, (self.error_name,)) def append(self, index, error): + """ + Parameters + ---------- + index : tuple of int + Following index_names passed to __init__, e.g. (12, 15) if index_names were ('epoch', 'minibatch_size') + error : float + Next error in the series. + """ if len(index) != len(self.index_names): raise ValueError("index provided does not have the right length (expected " \ + str(len(self.index_names)) + " got " + str(len(index))) newrow = self._table.row + # Columns for index in table are based on index_names for col_name, value in zip(self.index_names, index): newrow[col_name] = value newrow[self.error_name] = error @@ -111,6 +146,16 @@ """ def __init__(self, base_series, reduce_every, reduce_function=numpy.mean): + """ + Parameters + ---------- + base_series : Series + This object must have an append(index, value) function. + reduce_every : int + Apply the reduction function (e.g. mean()) every time we get this number of elements. E.g. if this is 100, then every 100 numbers passed to append(), we'll take the mean and call append(this_mean) on the BaseSeries. + reduce_function : function + Must take as input an array of "elements", as passed to (this accumulator's) append(). Basic case would be to take an array of floats and sum them into one float, for example. + """ self.base_series = base_series self.reduce_function = reduce_function self.reduce_every = reduce_every @@ -126,6 +171,8 @@ The index used is the one of the last element reduced. E.g. if you accumulate over the first 1000 minibatches, the index passed to the base_series.append() function will be 1000. + element : float + Element that will be accumulated. """ self._buffer.append(element) @@ -140,7 +187,7 @@ # Outside of class to fix an issue with exec in Python 2.6. # My sorries to the God of pretty code. -def BasicStatisticsSeries_construct_table_toexec(index_names): +def _BasicStatisticsSeries_construct_table_toexec(index_names): toexec = get_beginning_description_n_ints(index_names) bpos = len(index_names) @@ -154,26 +201,43 @@ return LocalDescription +basic_stats_functions = {'mean': lambda(x): numpy.mean(x), + 'min': lambda(x): numpy.min(x), + 'max': lambda(x): numpy.max(x), + 'std': lambda(x): numpy.std(x)} + class BasicStatisticsSeries(Series): """ Parameters ---------- series_name : str Not optional here. Will be prepended with "Basic statistics for " + stats_functions : dict, optional + Dictionary with a function for each key "mean", "min", "max", "std". The function must take whatever is passed to append(...) and return a single number (float). """ - def __init__(self, table_name, hdf5_file, index_names=('epoch',), title=None, hdf5_group='/'): + def __init__(self, table_name, hdf5_file, stats_functions=basic_stats_functions, index_names=('epoch',), title=None, hdf5_group='/'): Series.__init__(self, table_name, hdf5_file, index_names, title) self.hdf5_group = hdf5_group - self.construct_table() + self.stats_functions = stats_functions - def construct_table(self): - table_description = BasicStatisticsSeries_construct_table_toexec(self.index_names) + self._construct_table() + + def _construct_table(self): + table_description = _BasicStatisticsSeries_construct_table_toexec(self.index_names) self._table = self.hdf5_file.createTable(self.hdf5_group, self.table_name, table_description) def append(self, index, array): + """ + Parameters + ---------- + index : tuple of int + Following index_names passed to __init__, e.g. (12, 15) if index_names were ('epoch', 'minibatch_size') + array + Is of whatever type the stats_functions passed to __init__ can take. Default is anything numpy.mean(), min(), max(), std() can take. + """ if len(index) != len(self.index_names): raise ValueError("index provided does not have the right length (expected " \ + str(len(self.index_names)) + " got " + str(len(index))) @@ -183,10 +247,10 @@ for col_name, value in zip(self.index_names, index): newrow[col_name] = value - newrow["mean"] = numpy.mean(array) - newrow["min"] = numpy.min(array) - newrow["max"] = numpy.max(array) - newrow["std"] = numpy.std(array) + newrow["mean"] = self.stats_functions['mean'](array) + newrow["min"] = self.stats_functions['min'](array) + newrow["max"] = self.stats_functions['max'](array) + newrow["std"] = self.stats_functions['std'](array) newrow.append() @@ -195,6 +259,8 @@ class SeriesArrayWrapper(): """ Simply redistributes any number of elements to sub-series to respective append()s. + + To use if you have many elements to append in similar series, e.g. if you have an array containing [train_error, valid_error, test_error], and 3 corresponding series, this allows you to simply pass this array of 3 values to append() instead of passing each element to each individual series in turn. """ def __init__(self, base_series_list): @@ -208,18 +274,41 @@ for series, el in zip(self.base_series_list, elements): series.append(index, el) -class ParamsStatisticsWrapper(SeriesArrayWrapper): +class SharedParamsStatisticsWrapper(SeriesArrayWrapper): + '''Save mean, min/max, std of shared parameters place in an array. + + This is specifically for cases where we have _shared_ parameters, + as we take the .value of each array''' + def __init__(self, arrays_names, new_group_name, hdf5_file, base_group='/', index_names=('epoch',), title=""): + """ + Parameters + ---------- + array_names : array of str + Name of each array, in order of the array passed to append(). E.g. ('layer1_b', 'layer1_W', 'layer2_b', 'layer2_W') + new_group_name : str + Name of a new HDF5 group which will be created under base_group to store the new series. + base_group : str + Path of the group under which to create the new group which will store the series. + title : str + Here the title is attached to the new group, not a table. + """ base_series_list = [] new_group = hdf5_file.createGroup(base_group, new_group_name, title=title) + stats_functions = {'mean': lambda(x): numpy.mean(x.value), + 'min': lambda(x): numpy.min(x.value), + 'max': lambda(x): numpy.max(x.value), + 'std': lambda(x): numpy.std(x.value)} + for name in arrays_names: base_series_list.append( BasicStatisticsSeries( table_name=name, hdf5_file=hdf5_file, - index_names=('epoch','minibatch'), + index_names=index_names, + stats_functions=stats_functions, hdf5_group=new_group._v_pathname)) SeriesArrayWrapper.__init__(self, base_series_list) diff -r d982dfa583df -r dc0d77c8a878 utils/tables_series/test_series.py --- a/utils/tables_series/test_series.py Fri Mar 05 18:08:34 2010 -0500 +++ b/utils/tables_series/test_series.py Tue Mar 09 10:15:19 2010 -0500 @@ -1,6 +1,9 @@ import tempfile import numpy import numpy.random + +from jobman import DD + from tables import * from series import * @@ -109,20 +112,20 @@ assert compare_lists(table.cols.max[:], [0.30, 0.58, 0.18, 1.9], floats=True) assert compare_lists(table.cols.std[:], [0.06236095, 0.31382939, 0.35640177, 0.85724366], floats=True) -def test_ParamsStatisticsWrapper_commoncase(h5f=None): +def test_SharedParamsStatisticsWrapper_commoncase(h5f=None): import numpy.random if not h5f: h5f_path = tempfile.NamedTemporaryFile().name h5f = openFile(h5f_path, "w") - stats = ParamsStatisticsWrapper(new_group_name="params", base_group="/", + stats = SharedParamsStatisticsWrapper(new_group_name="params", base_group="/", arrays_names=('b1','b2','b3'), hdf5_file=h5f, index_names=('epoch','minibatch')) - b1 = numpy.random.rand(5) - b2 = numpy.random.rand(5) - b3 = numpy.random.rand(5) + b1 = DD({'value':numpy.random.rand(5)}) + b2 = DD({'value':numpy.random.rand(5)}) + b3 = DD({'value':numpy.random.rand(5)}) stats.append((1,1), [b1,b2,b3]) h5f.close() @@ -132,10 +135,10 @@ b1_table = h5f.getNode('/params', 'b1') b3_table = h5f.getNode('/params', 'b3') - assert b1_table.cols.mean[0] - numpy.mean(b1) < 1e-3 - assert b3_table.cols.mean[0] - numpy.mean(b3) < 1e-3 - assert b1_table.cols.min[0] - numpy.min(b1) < 1e-3 - assert b3_table.cols.min[0] - numpy.min(b3) < 1e-3 + assert b1_table.cols.mean[0] - numpy.mean(b1.value) < 1e-3 + assert b3_table.cols.mean[0] - numpy.mean(b3.value) < 1e-3 + assert b1_table.cols.min[0] - numpy.min(b1.value) < 1e-3 + assert b3_table.cols.min[0] - numpy.min(b3.value) < 1e-3 def test_get_desc(): h5f_path = tempfile.NamedTemporaryFile().name @@ -166,5 +169,5 @@ test_ErrorSeries_common_case() test_BasicStatisticsSeries_common_case() test_AccumulatorSeriesWrapper_common_case() - test_ParamsStatisticsWrapper_commoncase() + test_SharedParamsStatisticsWrapper_commoncase()