Skip to content

Instantly share code, notes, and snippets.

@braingineer
Last active April 27, 2016 19:59
Show Gist options
  • Save braingineer/4837baee2f2782f77cddc0dce852064d to your computer and use it in GitHub Desktop.
Save braingineer/4837baee2f2782f77cddc0dce852064d to your computer and use it in GitHub Desktop.
reversing a tensor for rnn stuff
from __future__ import print_function
import theano
import theano.tensor as T
import numpy as np
import random
A = np.arange(1,31).reshape(5,6).astype(np.float32)
sizes = np.zeros(5, dtype='int16')
for i in range(5):
sizes[i] = random.randint(1,5)
A[i,sizes[i]:] = 0
sizes = 6 - sizes
A_r = A[:,::-1]
def step_wrapper(seq1, indexer):
out = T.zeros_like(seq1)
N = seq1.shape[0]
return T.set_subtensor(out[:N-indexer], seq1[indexer:])
M = T.matrix()
S = T.ivector()
result,_ = theano.scan(fn=step_wrapper,
sequences=[M,S])
F = theano.function(inputs=[M,S], outputs=result)
print("Original matrix: \n", A)
print("reversed before: \n", A_r)
print("reversed after: \n", F(A_r, sizes))
'''
Output:
Original matrix:
[[ 1. 2. 3. 4. 0. 0.]
[ 7. 0. 0. 0. 0. 0.]
[ 13. 0. 0. 0. 0. 0.]
[ 19. 20. 21. 22. 23. 0.]
[ 25. 26. 27. 28. 0. 0.]]
reversed before:
[[ 0. 0. 4. 3. 2. 1.]
[ 0. 0. 0. 0. 0. 7.]
[ 0. 0. 0. 0. 0. 13.]
[ 0. 23. 22. 21. 20. 19.]
[ 0. 0. 28. 27. 26. 25.]]
reversed after:
[[ 4. 3. 2. 1. 0. 0.]
[ 7. 0. 0. 0. 0. 0.]
[ 13. 0. 0. 0. 0. 0.]
[ 23. 22. 21. 20. 19. 0.]
[ 28. 27. 26. 25. 0. 0.]]
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment