Compute Singular Value Decomposition (SVD) with TensorFlow – TensorFlow Example

By | May 27, 2019

In this tutorial, we will write an example for computing SVD value with TensorFlow. You can exercise this example by update our example code.

import tensorflow as tf;
import numpy as np
A = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.float32)

s, u, v = tf.svd(A)

A2 = tf.matmul(tf.matmul(u, tf.diag(s)), tf.transpose(v))

init = tf.global_variables_initializer() 
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
    sess.run([init, init_local])
    np.set_printoptions(precision=4, suppress=True)
   
    s, u, v,a2 = (sess.run([s, u, v, A2]))
    print 's='
    print s
    print 'u='
    print u
    print 'v='
    print v
    print 'A='
    print a2

Notice:

You must know we also can caculate SVD in Numpy and you should know the difference between them, especial for V matrix.

Leave a Reply

Your email address will not be published. Required fields are marked *