当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Tensorflow.js tf.eye()用法及代码示例


Tensorflow.js 是一个开源库,用于在 Javascript 中创建机器学习模型,允许用户直接在浏览器中运行模型。

tf.eye() 是在类 tf.Tensor 中定义的函数。它用于创建指定行和列的单位矩阵。

形状为 [m, n] 的单位矩阵由所有对角线元素的值 1 和其余位置的值 0 组成。

用法:

tf.eye(numRows, numColumns, batchShape, dtype)

参数:



  • numRows:返回单位矩阵的行数。
  • numColumns:返回单位矩阵的列数。这是一个可选参数。如果未指定,则返回单位矩阵的形状为 [numRows, numRows]。
  • batchShape:它是一个数组,通过复制单位矩阵定义将附加到返回单位矩阵形状开头的形状。这是一个可选参数。假设 batchShape = [a, b] 那么返回的单位矩阵形状是 [a, b, numRows, numColumns]
  • dtype:指定为返回单位矩阵中元素的数据类型。它是可选的。

返回值:它返回单位矩阵的张量。

范例1:创建方形单位矩阵

  • 通过在 tf.eye() 方法中定义 numRows = 3,创建形状为 [3, 3] 的单位矩阵。

Javascript


// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
// Creating an identity matrix  of shape [3,3]
var matrix = tf.eye(numRows = 3)
   
// Printing the identity matrix
matrix.print()

输出:

Tensor
    [[1, 0, 0],
     [0, 1, 0],
     [0, 0, 1]]

范例2:创建矩形的单位矩阵

  • 通过在 tf.eye() 方法中定义 numRows = 3 和 numColumns = 4,创建形状为 [3, 4] 的单位矩阵。

Javascript


// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
// Creating an identity matrix  of shape [3,4]
var matrix = tf.eye(numRows = 3, numColumns = 4)
   
// Printing the identity matrix
matrix.print()

输出:

Tensor
    [[1, 0, 0, 0],
     [0, 1, 0, 0],
     [0, 0, 1, 0]]

范例3:通过指定 batchShape 创建单位矩阵

  • 通过在 tf.eye() 方法中定义 numRows = 2 和 numColumns = 3,创建形状为 [2, 3] 的单位矩阵。
  • 复制通过包含 batchShape = [3] 将上述单位矩阵 3 次
  • 那么返回单位矩阵的形状是 [3, 2, 3]

Javascript


// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
// Creating an identity matrix  of shape [2,3]
// And include batchShape = [3] to replicate identity matrix 3 times
// Shape of returning tensor is [3, 2, 3]
var matrix = tf.eye(numRows = 2, numColumns = 3, batchShape = [3])
   
// Printing the identity matrix
matrix.print()

输出:

Tensor
    [[[1, 0, 0],
      [0, 1, 0]],

     [[1, 0, 0],
      [0, 1, 0]],

     [[1, 0, 0],
      [0, 1, 0]]]

参考:https://js.tensorflow.org/api/latest/#eye




相关用法


注:本文由纯净天空筛选整理自ManikantaBandla大神的英文原创作品 Tensorflow.js tf.eye() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。