📌  相关文章
📜  Tensorflow.js tf.initializers.ones()函数

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

Tensorflow.js tf.initializers.ones()函数

Tensorflow.js 是一个非常知名的机器学习库,用于使用 JavaScript 开发机器学习模型。使用这个库的主要目的是直接从浏览器或 Node.js 中运行和部署机器学习模型。 Tensorflow.js 是一个开源硬件加速 JavaScript 库。在本文中,我们将讨论 Tensorflow.js 中的 tf.ones()函数。

tf.ones()创建一个所有元素都设置为 1 的张量,或者它用值 1 初始化张量。

句法:

tf.ones (shape, dtype)

参数:

  • 形状:这表示结果数组的形状。形状是一个整数数组,表示行数和列数。
  • dtype :这些是在结果中返回的值的类型。类型的默认值是浮点数。它可以是 int32、complex64、bool、 字符串或 float32。

返回类型:

此方法返回 dtype 类型的张量,其形状为 order (row*column),并初始化为 1。

示例 1:在此示例中,我们将创建一个 3*4 阶的张量并对其应用 tf.ones()。

Javascript
//import tensorflow.js
const tf=require("@tensorflow/tfjs")
//use tf.ones()
var GFG=tf.ones([3, 4]);
 
//print tensor
GFG.print()


Javascript
//import tensorflow.js
const tf=require("@tensorflow/tfjs")
 
//create tensor of shape 1*4
var GFG=tf.ones([3]);
 
//print tensor
GFG.print()


Javascript
//import tensorflow.js
const tf=require("@tensorflow/tfjs")
 
// create tensor with default dtype as float32
tf.ones([3, 3]).print();
 
// create tensor with complex values
tf.ones([3, 3],'complex64').print();
 
// create tensor with boolean values by default all
// values true because initialization by ones
tf.ones([3, 3],'bool').print();
 
//create tensor with integer values
tf.ones([3, 3],'int32').print();


输出:

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

示例 2:在此示例中,我们将通过在形状数组中给出单个元素来创建一个 1×4 阶的张量。

Javascript

//import tensorflow.js
const tf=require("@tensorflow/tfjs")
 
//create tensor of shape 1*4
var GFG=tf.ones([3]);
 
//print tensor
GFG.print()

输出

Tensor
   [1, 1, 1]

示例 3:具有不同 dtype 的 tf.ones()。

Javascript

//import tensorflow.js
const tf=require("@tensorflow/tfjs")
 
// create tensor with default dtype as float32
tf.ones([3, 3]).print();
 
// create tensor with complex values
tf.ones([3, 3],'complex64').print();
 
// create tensor with boolean values by default all
// values true because initialization by ones
tf.ones([3, 3],'bool').print();
 
//create tensor with integer values
tf.ones([3, 3],'int32').print();

输出:

Tensor
   [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]
Tensor
   [[1 + 0j, 1 + 0j, 1 + 0j],
    [1 + 0j, 1 + 0j, 1 + 0j],
    [1 + 0j, 1 + 0j, 1 + 0j]]
Tensor
   [[true, true, true],
    [true, true, true],
    [true, true, true]]
Tensor
   [[1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]]

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