當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Tensorflow.js tf.fill()用法及代碼示例

Tensorflow.js 是一個開源庫,用於在 Javascript 中創建機器學習模型,允許用戶直接在瀏覽器中運行模型。

tf.fill() 是在類 tf.Tensor 中定義的函數。它用於創建一個填充有標量值的張量。

用法:

tf.fill( shape, value, dtype )

參數:

  • shape:它是一個定義輸出張量形狀的整數數組。
  • value:它是一個標量值,用於填充輸出張量。
  • dtype:它定義了輸出張量中元素的數據類型。它可以是 ‘float32’|'int32'|'bool'|'complex64'|'string'。包含是可選的,默認值為 ‘float32’。

返回值:它返回填充有標量值的指定形狀的張量。



示例 1:用標量數填充張量

  • 創建一個形狀為 [4, 2] 的張量,填充為標量值 2。
  • 它將輸出張量中元素的默認數據類型作為浮點數。

Javascript


// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
  
// Creating a tensor of of shape [4,2] filled with 
// scalar value 2
var matrix = tf.fill(shape = [4,2],value = 2)
    
// Printing the tensor
matrix.print()

輸出:

Tensor
    [[2, 2],
     [2, 2],
     [2, 2],
     [2, 2]]

示例 2:顯式定義元素的數據類型

  • 創建一個形狀為 [3, 4] 的張量,其中填充了字符串“Gfg”。

Javascript


// Dynamic loading the "@tensorflow/tfjs" module
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
  
// Creating a tensor  of shape [3,4] filled
// with string value 'Gfg'
var matrix = tf.fill(shape = [3, 4], 
        value = 'Gfg', dtype = 'string')
    
// Printing the tensor
matrix.print()

輸出:

Tensor
    [['Gfg', 'Gfg', 'Gfg', 'Gfg'],
     ['Gfg', 'Gfg', 'Gfg', 'Gfg'],
     ['Gfg', 'Gfg', 'Gfg', 'Gfg']]

參考: https://js.tensorflow.org/api/latest/#fill

相關用法


注:本文由純淨天空篩選整理自ManikantaBandla大神的英文原創作品 Tensorflow.js tf.fill() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。