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


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

Tensorflow.js是Google開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。

.tensor5d()函數用於創建具有參數(即值,形狀和數據類型)的新5維張量。

句法:

tf.tensor5d(value, shape?, dataType?)

參數:

  • value:張量的值,它可以是數字的嵌套數組,平麵數組或TypedArray。
  • shape:它采用張量的形狀。如果未提供張量,則張量將從其值推斷其形狀。它是一個可選參數。
  • datatype:它可以是‘float32’或‘int32’或‘bool’或‘complex64’或‘string’值。它是一個可選參數。

返回值:它返回相同數據類型的張量。返回的張量將始終為5維。

注意:也可以使用tf.tensor()函數來實現5d張量函數,但是使用tf.tensor5d()可以使代碼易於理解和讀取。

範例1:在這裏,我們正在創建5d張量並進行打印。為了創建5d張量,我們使用.tensor5d()函數,並使用.print()函數打印張量。在這裏,我們將5d數組(即嵌套數組)傳遞給value參數。



Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs";
  
// Create the tensor
let example1 = tf.tensor5d([[[
    [[1, 3], [2, 8]], 
    [[3, 9], [4, 2]]
]]]);
  
// Print the tensor
example1.print()

輸出:

Tensor
    [[[[[1, 3],
        [2, 8]],

       [[3, 9],
        [4, 2]]]]]

範例2:

在上麵的示例中,我們在傳遞平麵數組並指定張量的shape參數的位置創建張量。在這裏,我們將看到shape參數的用法。

Javascript


// Import the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Define the value of the tensor
var value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  
// Specify the shape of the tensor
var shape = [1, 2, 6, 1, 1];
  
// Create the tensor
let example2 = tf.tensor5d(value, shape);
  
// Print the tensor
example2.print();

輸出:

Tensor
    [[[ [[1 ],],
        [[2 ],],
        [[3 ],],
        [[4 ],],
        [[5 ],],
        [[6 ],]],

      [ [[7 ],],
        [[8 ],],
        [[9 ],],
        [[10],],
        [[11],],
        [[12],]]]]

範例3:

在這裏,在此示例中,我們將通過指定值,形狀和數據類型來創建張量。我們將創建張量,其中所有值均為字符串數據類型。

Javascript


// Import the tensorflow.js library
import * as tf from "@tensorflow/tfjs";
  
// Define the value of the tensor
var value = ["C", "C++", "Java", "Python",
            "PHP", "JS", "SQL", "React"];
  
// Specify the shape of the tensor
var shape = [1, 2, 4, 1,1 ];
  
// Create the tensor
var example3 = tf.tensor5d(value, shape);
  
// Print the tensor
example3.print();

輸出:

Tensor
    [[[ [['C'     ],],
        [['C++'   ],],
        [['Java'  ],],
        [['Python'],]],

      [ [['PHP'   ],],
        [['JS'    ],],
        [['SQL'   ],],
        [['React' ],]]]]

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

相關用法


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