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


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

Tensorflow.js 是 Google 開發的一個開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。它還可以幫助開發人員使用 JavaScript 語言開發 ML 模型,並且可以直接在瀏覽器或 Node.js 中使用 ML。

tf.reshape() 函數用於用指定的形狀重塑給定的張量。

用法:

tf.reshape(x, shape)

參數:該函數具有以下參數:

  • x:它是需要整形的輸入張量。
  • shape:我們需要傳遞數字數組來定義輸出形狀。

返回值:它返回一個tf.Tensor。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
const x = tf.tensor1d([10, 15, 16, 24]);
  
// Print the tensor
x.reshape([2, 2]).print();

輸出:

Tensor
    [[10, 15],
     [16, 24]]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using 2d
const x = tf.tensor2d(
  [1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]
);
x.reshape([3, 3]).print();
  
// Using 3d
const y = tf.tensor3d(
  [[[1], [2]], [[3], [4]]]
);
y.reshape([2, 2]).print();
  
// Using 4d
const z = tf.tensor4d(
  [11, 12, 13, 14], [1, 2, 2, 1]
);
z.reshape([2, 2]).print();

輸出:

Tensor
    [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]
Tensor
    [[1, 2],
     [3, 4]]
Tensor
    [[11, 12],
     [13, 14]]

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

相關用法


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