Search code examples
pythonmatrixlinear-algebradivisiontheano

matrix divided by rows of another matrix, without a loop in theano


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


Solution

  • 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()