📜  Tensorflow.js tf.fill()函数

📅  最后修改于: 2022-05-13 01:56:25.147000             🧑  作者: Mango

Tensorflow.js tf.fill()函数

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

tf.fill()是在tf.Tensor类中定义的函数。它用于创建一个用标量值填充的张量。

句法:

tf.fill( shape, value, dtype )

参数:

  • shape:它是一个整数数组,定义了输出张量形状
  • value:这是一个标量值输出张量将被填充。
  • dtype:它定义了输出张量中元素的数据类型。可以是'float32'|'int32'|'bool'|'complex64'|'字符串' 。它是可选的,默认值为'float32'。

返回值:返回用标量值填充的指定形状量。

示例 1:用标量数填充张量

  • 创建一个用标量值 2填充的形状为[4, 2]的张量。
  • 它将输出张量中元素的默认数据类型设为float
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()


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
    [[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