Open In App

Tensorflow.js tf.linalg.qr() Function

Last Updated : 18 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Tensorflow.js is an open-source library that is developed by Google for running machine learning models as well as deep learning neural networks in the browser or node environment. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.

The .linalg.qr() function is used to calculate the QR decomposition referring to m by n matrix applying Householder transformation.

Syntax:

tf.linalg.qr(x, fullMatrices?)

Parameters:  

  • x: The stated tf.Tensor which is to be QR-decomposed. It must have a rank greater than or equal to 2. Assume, its shape as […, M, N]. It is of type tf.Tensor.
  • fullMatrices: It is an optional parameter and is of type boolean whose by default value is false. In case it’s true, then it evaluates normal-sized Q else it evaluates just the highest N columns of Q and R.

Return Value: It returns [tf.Tensor, tf.Tensor].

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining a 2d tensor
const tn = tf.tensor2d([[3, 5], [7, 2]]);
  
// Calling linalg.qr() function
let [Q, R] = tf.linalg.qr(tn);
  
// Printing outputs
console.log('q');
Q.print();
console.log('r');
R.print();


Output:

q
Tensor
    [[-0.3939192, 0.919145  ],
     [-0.919145 , -0.3939193]]
r
Tensor
    [[-7.6157722, -3.8078861],
     [0         , 3.8078861 ]]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining a 2d tensor
const tn = tf.tensor2d([[3, 5], [7, 2]]);
  
// Calling linalg.qr() function
let [Q, R] = tf.linalg.qr(tn, true);
  
// Printing outputs
console.log('Orthogonalized:');
Q.transpose().print();
console.log('Regenerated:');
R.dot(Q).print();


Output:

Orthogonalized:
Tensor
    [[-0.3939192, -0.919145 ],
     [0.919145  , -0.3939193]]
Regenerated:
Tensor
    [[6.4999986 , -5.499999 ],
     [-3.4999995, -1.4999998]]

Reference: https://js.tensorflow.org/api/latest/#linalg.qr



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads