Search code examples
pythontensorflowkeraszero-padding

How to pad tensors of different shape to make them of same shape for 2nd dimension


I have 3 tensors with shape (100,43,1024), (100,37,1024) and (100,42,1024). I want to make the second dimension of all these tensors to the maximum value of 2nd dimension i.e 43 in this case. Could you plz help me how to use pad function to make them of equal shape?


Solution

  • if you are operating with numpy array, you can zero pad them in this way:

    # create your data
    n_sample = 5
    X = [np.random.uniform(0,1, (n_sample,43,1024)),
         np.random.uniform(0,1, (n_sample,37,1024)),
         np.random.uniform(0,1, (n_sample,42,1024))]
    
    # find max dim
    max_dim = np.max([x.shape[1] for x in X])
    print(max_dim)
    
    X_pad = []
    for x in X:
        X_pad.append(np.pad(x, ((0,0),(max_dim-x.shape[1],0),(0,0)), mode='constant')) # pre padding
        # X_pad.append(np.pad(x, ((0,0),(0,max_dim-x.shape[1],(0,0)), mode='constant')) # post padding
        
    # check padded shape
    print([x.shape for x in X_pad])