def test_jacobian(self): m_np = np.array([[1., 2.], [3., 4.]], np.float32) m = tf.Variable(m_np) x = tf.Variable([4., -1.], tf.float32) y = tf.einsum('nm,m->n', m, x) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) jacobian = tfutils.jacobian(y, x) jacobian_actual = sess.run(jacobian) self.assertTrue(np.allclose(jacobian_actual, m_np))
def test_jacobian_multirank_y(self): m_np = np.array([[1., 2.], [3., 4.]], np.float32) m = tf.Variable(m_np) x = tf.Variable([4.], tf.float32) y = m * x with tf.Session() as sess: sess.run(tf.global_variables_initializer()) jacobian = tfutils.jacobian(y, x) jacobian_actual = sess.run(jacobian) jacobian_actual = np.reshape(jacobian_actual, m_np.shape) self.assertTrue(np.allclose(jacobian_actual, m_np))
def test_jacobian_dynamic_dim(self): m_np = np.array([[1., 2.], [3., 4.]], np.float32) # m = tf.Variable(m_np) # x = tf.Variable([4., -1.], tf.float32) m = tf.placeholder(tf.float32, shape=[2, None]) x = tf.placeholder(tf.float32, shape=[None]) y = tf.einsum('nm,m->n', m, x) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) jacobian = tfutils.jacobian(y, x) jacobian_actual = sess.run(jacobian, feed_dict={m: m_np, x: [4., -1.]}) self.assertTrue(np.allclose(jacobian_actual, m_np))