iBM
iBM

Reputation: 185

Tiling Theano tensor

I have two tensors A and B where the first one has size (500,10) and the second has size (500). I want to find A / B. I am using regular / operator and it Theano compiler says that they should be the same size. Then I tried using tensor.tile on B to make it the same size as A. It has three parameters(x, reps, ndim). I tried different values and I am limited to these constraints: x.ndim = len(reps) and ndim = len(reps) Then having these constraints how can I tile the array to a matrix?! Is this a bug in Theano?

Upvotes: 0

Views: 1097

Answers (1)

eickenberg
eickenberg

Reputation: 14377

You can just broadcast it, and there are several ways to do it. Take the following example

import numpy as np
A = np.arange(1., 5001., 1.).reshape(500, 10)
B = np.arange(1., 501., 1.)

import theano
As = theano.shared(A)
Bs = theano.shared(B)

The failsafe way of doing this is adding an appropriate axis

AoverB = A / B[:, np.newaxis]
AoverBalso = A / B.reshape((-1, 1))
AsoverBs = As / Bs.reshape((-1, 1))

Another way is to exploit the fact that there is implicit broadcasting to pad the first axes if they are missing

AoverBT = A.T / B.T   # no axis was added here
AsoverBsT = As.T / Bs.T

In order to show that all these calculate the same thing, we use numpy.testing

from numpy.testing import assert_array_equal
assert_array_equal(AoverB, AoverBalso)
assert_array_equal(AoverB, AsoverBs.eval())
assert_array_equal(AoverB, AoverBT.T)
assert_array_equal(AoverB, AsoverBsT.T.eval())

Upvotes: 1

Related Questions