An implementation of data dimension reduction and restoration in Keras with tensorflow as Backend

Data Dimension Reduction

In neural network for points cloud data and temporal data along with the emerging graph convolution nerual network, data dimension reduction is a essential step in calculation graph. However, there is no explicit example code online can be used as template. I will introduce a few lines as a simple implementation in Keras with tensorflow as backend. So, be careful with your framework before a straight copy.

    import tensorflow as tf
    import numpy as np 
    from keras import backend as K
    from keras.layers.core import Reshape
    shape = (10,3,3,1)
    img = np.zeros(shape)
    for i in range(0,3):
        for j in range(0,3):
            img[:,i,j,0] = i*3+j

    sess = tf.InteractiveSession()
    a = tf.Print(img, [img], message="This is img: ") # convert numpy.ndarray to tensor
    a_re = Reshape((a.shape[1]*a.shape[2],1,1))(a) # a_re.shape = (10,9,1,1)
    print(a_re.shape)
    a_sq = tf.squeeze(a_re,[2]) # a_sq.shape = (10,9,1)
    print(a_sq.shape)

Data Dimension Restoration

In segmentation application, sometimes we need restore data to origin shape after data dimension reduction. Following the above lines, a_sq can convert to original shape.

    a_bk = Reshape((a.shape[1],a.shape[2],a.shape[3]))(a_sq) # the result can be compared using a_bk.eval() and a.eval()
    result_0 = tf.equal(a,a_bk) # also can use tf.equal to check equality element-wise

Case suspends for better answer if anyone please to enlight more.

comments powered by Disqus