Skip to content

Instantly share code, notes, and snippets.

@popcornell
Created April 28, 2018 10:10
Show Gist options
  • Save popcornell/502f42666496c5bf9f7266bc42758761 to your computer and use it in GitHub Desktop.
Save popcornell/502f42666496c5bf9f7266bc42758761 to your computer and use it in GitHub Desktop.
Moore-Penrose Pseudo-Inverse in TensorFlow
import tensorflow as tf
def p_inv(matrix):
"""Returns the Moore-Penrose pseudo-inverse"""
s, u, v = tf.svd(matrix)
threshold = tf.reduce_max(s) * 1e-5
s_mask = tf.boolean_mask(s, s > threshold)
s_inv = tf.diag(tf.concat([1. / s_mask, tf.zeros([tf.size(s) - tf.size(s_mask)])], 0))
return tf.matmul(v, tf.matmul(s_inv, tf.transpose(u)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment