2

What is the equivalent theano implementation of the code below without using a loop?

dt = np.dtype(np.float32)

a=[[12,3],
   [2,4],
   [2,4],]

b=[[12,3,2,3],
   [2,4,4,5]]

a=np.asarray(a,dtype=dt)
b=np.asarray(b,dtype=dt)
print(a.shape)
print(b.shape)
ainvb=np.zeros((3,2,4))
for i in range(4):
   ainvb[:,:,i]=a/b[:,i].T

the loop in numpy also can be replaced with:

 ainvb=a[:,:,None]/b

What I need to do is to divide columns of "a" by each row of "b". At the end, there will 4 matrices of size 3*2 (size of "a") where each are "a" divided by one of the rows of "b".

-Regards

PickleRick
  • 419
  • 1
  • 5
  • 13
  • Have you tried using the numpy solution in Theano? Theano intends to largely replicate the numpy API and so an expression like this may work exactly as intended in Theano too. – Daniel Renshaw Dec 04 '15 at 08:37
  • @DanielRenshaw you mean exact same expression might work in theano too? I will give it a try! – PickleRick Dec 04 '15 at 08:38

1 Answers1

1

This works in Theano just the same as it does in numpy. Here's a script comparing the three approaches:

import numpy as np
import theano
import theano.tensor as tt


def numpy_v1(a, b):
    ainvb = np.zeros((3, 2, 4))
    for i in range(4):
        ainvb[:, :, i] = a / b[:, i].T
    return ainvb


def numpy_v2(a, b):
    return a[:, :, None] / b


def compile_theano_v1():
    a, b = tt.matrices('a', 'b')
    return theano.function([a, b], a[:, :, None] / b)


def main():
    dt = np.dtype(np.float32)

    a = [[12, 3],
         [2, 4],
         [2, 4], ]

    b = [[12, 3, 2, 3],
         [2, 4, 4, 5]]

    a = np.asarray(a, dtype=dt)
    b = np.asarray(b, dtype=dt)
    print(a.shape)
    print(b.shape)

    theano_v1 = compile_theano_v1()

    numpy_v1_ainvb = numpy_v1(a, b)
    numpy_v2_ainvb = numpy_v2(a, b)
    theano_v1_ainvb = theano_v1(a, b)

    assert np.allclose(numpy_v1_ainvb, numpy_v2_ainvb)
    assert np.allclose(numpy_v2_ainvb, theano_v1_ainvb)


main()
Daniel Renshaw
  • 33,729
  • 8
  • 75
  • 94