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


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

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

.tensor4d()函數用於創建一個新的4維張量,其參數為值,形狀和數據類型。

用法:

tf.tensor4d(value, shape, dataType)

Parameters: 該函數接受以下三個參數。

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

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



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

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

Javascript


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

輸出:

Tensor
    [[[[1 , 3],
       [20, 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
const value = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  
// Specify the shape of the tensor
const shape = [1, 2, 6, 1];
  
// Create the tensor
let example2 = tf.tensor4d(value, shape);
  
// Print the tensor
example2.print();

輸出:

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

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

在上麵的示例中,我們創建了一個尺寸為1 x 2 x 6 x 1的張量。

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

Javascript


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

輸出:

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

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

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

相關用法


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