0

In Tensorflow, I'm trying to create the following matrix:

A = [[a, 0], [0,b]]

Where a and b are the parameters I'm trying to solve for.

Here's what I have so far:

a =  tf.Variable((1,), name="a", dtype = tf.float64)
b = tf.Variable((1,), name="b", dtype = tf.float64)
const = tf.constant(0,dtype = tf.float64, shape = (1,))
A0 = tf.transpose(tf.stack([a,const]))
A1 = tf.transpose(tf.stack([const,b]))
A = tf.stack([A0,A1])

However the shape of A ends up being (2,1,2) which is wrong (since A0 and B0 both have shapes (1,2))

Is there an easier way to create the matrix object A in Tensorflow, or does anyone know why the shape is getting messed up with what I'm doing?

2
  • Would it be easier to make A a variable and solve for a[0,0] and A[1,1] instead?
    – c2huc2hu
    Commented May 16, 2018 at 20:55
  • Thought about that, but what I wrote is actually the simplified version where a actually = (1-delta)/alpha and b = delta (e.g. delta and alpha are what I'm actually solving for.) Commented May 16, 2018 at 20:57

2 Answers 2

1

Well you can create a single variable vector params = tf.Variable((2,), name="ab") and then multiply with the identity matrix tf.eye(2):

A = tf.matmul(tf.expand_dims(params,0), tf.eye(2))
1

tf.stack increases the rank of the tensor (creating a new axis) and combines them in the new axis. If you want to combine tensors along an existing axis, you should use tf.concat.

a = tf.Variable((1,), name="a", dtype = tf.float64)
b = tf.Variable((1,), name="b", dtype = tf.float64)
const = tf.constant(0,dtype = tf.float64, shape = (1,))
A0 = tf.stack([a, const], axis=1)
A1 = tf.stack([const, b], axis=1)  # more clear than tf.transpose

A = tf.concat((A0, A1), axis=0)

A is now shape (2, 2).

To explain, each object is a rank-1 tensor with one element:

A = [1]
const = [0]

stacking gives:

tf.stack((A, const), axis=0) = [[1], [0]]  # 2x1 matrix

concatenating gives:

tf.concat((A, const), axis=0) = [1, 0]  # 2 vector

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.