📚 The CoCalc Library - books, templates and other resources
cocalc-examples / data-science-ipython-notebooks / deep-learning / theano-tutorial / intro_theano / utils.py
132932 viewsLicense: OTHER
""" This file contains different utility functions that are not connected1in anyway to the networks presented in the tutorials, but rather help in2processing the outputs into a more understandable way.34For example ``tile_raster_images`` helps in generating a easy to grasp5image from a set of samples or weights.6"""789import numpy10from six.moves import xrange111213def scale_to_unit_interval(ndar, eps=1e-8):14""" Scales all values in the ndarray ndar to be between 0 and 1 """15ndar = ndar.copy()16ndar -= ndar.min()17ndar *= 1.0 / (ndar.max() + eps)18return ndar192021def tile_raster_images(X, img_shape, tile_shape, tile_spacing=(0, 0),22scale_rows_to_unit_interval=True,23output_pixel_vals=True):24"""25Transform an array with one flattened image per row, into an array in26which images are reshaped and layed out like tiles on a floor.2728This function is useful for visualizing datasets whose rows are images,29and also columns of matrices for transforming those rows30(such as the first layer of a neural net).3132:type X: a 2-D ndarray or a tuple of 4 channels, elements of which can33be 2-D ndarrays or None;34:param X: a 2-D array in which every row is a flattened image.3536:type img_shape: tuple; (height, width)37:param img_shape: the original shape of each image3839:type tile_shape: tuple; (rows, cols)40:param tile_shape: the number of images to tile (rows, cols)4142:param output_pixel_vals: if output should be pixel values (i.e. int843values) or floats4445:param scale_rows_to_unit_interval: if the values need to be scaled before46being plotted to [0,1] or not474849:returns: array suitable for viewing as an image.50(See:`Image.fromarray`.)51:rtype: a 2-d array with same dtype as X.5253"""5455assert len(img_shape) == 256assert len(tile_shape) == 257assert len(tile_spacing) == 25859# The expression below can be re-written in a more C style as60# follows :61#62# out_shape = [0,0]63# out_shape[0] = (img_shape[0]+tile_spacing[0])*tile_shape[0] -64# tile_spacing[0]65# out_shape[1] = (img_shape[1]+tile_spacing[1])*tile_shape[1] -66# tile_spacing[1]67out_shape = [68(ishp + tsp) * tshp - tsp69for ishp, tshp, tsp in zip(img_shape, tile_shape, tile_spacing)70]7172if isinstance(X, tuple):73assert len(X) == 474# Create an output numpy ndarray to store the image75if output_pixel_vals:76out_array = numpy.zeros((out_shape[0], out_shape[1], 4),77dtype='uint8')78else:79out_array = numpy.zeros((out_shape[0], out_shape[1], 4),80dtype=X.dtype)8182#colors default to 0, alpha defaults to 1 (opaque)83if output_pixel_vals:84channel_defaults = [0, 0, 0, 255]85else:86channel_defaults = [0., 0., 0., 1.]8788for i in xrange(4):89if X[i] is None:90# if channel is None, fill it with zeros of the correct91# dtype92dt = out_array.dtype93if output_pixel_vals:94dt = 'uint8'95out_array[:, :, i] = numpy.zeros(96out_shape,97dtype=dt98) + channel_defaults[i]99else:100# use a recurrent call to compute the channel and store it101# in the output102out_array[:, :, i] = tile_raster_images(103X[i], img_shape, tile_shape, tile_spacing,104scale_rows_to_unit_interval, output_pixel_vals)105return out_array106107else:108# if we are dealing with only one channel109H, W = img_shape110Hs, Ws = tile_spacing111112# generate a matrix to store the output113dt = X.dtype114if output_pixel_vals:115dt = 'uint8'116out_array = numpy.zeros(out_shape, dtype=dt)117118for tile_row in xrange(tile_shape[0]):119for tile_col in xrange(tile_shape[1]):120if tile_row * tile_shape[1] + tile_col < X.shape[0]:121this_x = X[tile_row * tile_shape[1] + tile_col]122if scale_rows_to_unit_interval:123# if we should scale values to be between 0 and 1124# do this by calling the `scale_to_unit_interval`125# function126this_img = scale_to_unit_interval(127this_x.reshape(img_shape))128else:129this_img = this_x.reshape(img_shape)130# add the slice to the corresponding position in the131# output array132c = 1133if output_pixel_vals:134c = 255135out_array[136tile_row * (H + Hs): tile_row * (H + Hs) + H,137tile_col * (W + Ws): tile_col * (W + Ws) + W138] = this_img * c139return out_array140141142