Reputation: 4101
i would like to learn the parameters of a rotation matrix in 3D using Tensorflow. Therefore, I defined the rotation matrix the following way
g = tf.Graph()
with g.as_default():
#rotations
thetax = tf.Variable(tf.zeros([1]))
thetax = tf.Variable(tf.zeros([1]))
thetay = tf.Variable(tf.zeros([1]))
p = tf.placeholder(tf.float32, [3])
rotation_matrix_x = tf.pack([tf.constant(1.0),tf.constant(0.0),tf.constant(0.0),
tf.constant(0.0),tf.cos(thetax), -tf.sin(thetax),
tf.constant(0.0),tf.sin(thetax), tf.cos(thetax)])
rotation_matrix_y = tf.pack([
tf.cos(thetax),tf.constant(0.0), -tf.sin(thetax),
tf.constant(1.0),tf.constant(0.0),tf.constant(0.0),
tf.sin(thetax),0, tf.cos(thetax)])
rotation_matrix_z = tf.pack([
tf.cos(thetax), -tf.sin(thetax),tf.constant(0.0),
tf.sin(thetax), tf.cos(thetax),tf.constant(0.0),
tf.constant(1.0),tf.constant(0.0),tf.constant(0.0)])
rotation_matrix_x = tf.reshape(rotation_matrix_x, (3,3))
rotation_matrix_y = tf.reshape(rotation_matrix_y, (3,3))
rotation_matrix_z = tf.reshape(rotation_matrix_z, (3,3))
rotated = tf.mult(tf.mult(rotation_matrix_x,tf.mult(rotation_matrix_y,rotation_matrix_z) ,p)
I have now two problems
ValueError: Shapes TensorShape([]) and
TensorShape([Dimension(1)]) must have the same rank
Thanks in advance
Upvotes: 1
Views: 1675
Reputation: 1644
I recently run across the same problem. This is my current solution:
one = tf.ones_like(cos_rot_x, dtype=tf.float32)
zero = tf.zeros_like(cos_rot_x, dtype=tf.float32)
rot_x = tf.stack([tf.concat([one, zero, zero], axis=1),
tf.concat([zero, cos_rot_x, sin_rot_x], axis=1),
tf.concat([zero, -sin_rot_x, cos_rot_x], axis=1)], axis=1)
rot_y = tf.stack([tf.concat([cos_rot_y, zero, -sin_rot_y], axis=1),
tf.concat([zero, one, zero], axis=1),
tf.concat([sin_rot_y, zero, cos_rot_y], axis=1)], axis=1)
rot_z = tf.stack([tf.concat([cos_rot_z, sin_rot_z, zero], axis=1),
tf.concat([-sin_rot_z, cos_rot_z, zero], axis=1),
tf.concat([zero, zero, one], axis=1)], axis=1)
rot_matrix = tf.matmul(rot_z, tf.matmul(rot_y, rot_x))
Notice that in this snippet cos_rot_x
has shape (batchsize, 1) so you can keep the batch dimension during the transformation.
Upvotes: 3
Reputation: 126154
For problem (1)—the shape error—I think the problem is caused by the fact that you are trying to pack together scalars (such as tf.constant(0.0)
) with single-element vectors (i.e. tf.Variable(tf.zeros([1]))
). You should be able to fix this by redefining the variables as scalars:
thetax = tf.Variable(tf.zeros([]))
thetax = tf.Variable(tf.zeros([]))
thetay = tf.Variable(tf.zeros([]))
I'm not sure about how to redefine the problem more elegantly... but hopefully this gets you unstuck!
Upvotes: 2