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


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

Tensorflow.js 是一個由 Google 開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型以及深度學習神經網絡。 .sparseReshape() 函數在渲染的壓縮張量上擁有與 reshape() 函數相同的語法。根據所需的新形狀重新計算輸入索引。

注意:

  • 如果所述新形狀的一個元素是不同的值,即 -1,則計算該維度的大小,使得密集大小的計數保持不變。
  • 至多隻有所述新形狀的一個分量可以是 -1。
  • 這裏,由所述新形狀指示的壓縮分量的計數應該與由所述輸入形狀原始指示的壓縮分量的計數相同。
  • 重塑無法影響所述稀疏張量中值的順序。
  • 如果輸入張量具有秩 R_in 以及 N 個加載值,並且新形狀具有長度 R_out,則輸入索引的形狀為 [N, R_in],輸入形狀的長度為 R_in,則輸出索引的形狀為[N, R_out],輸出形狀的長度為R_out。

用法:

tf.sparseReshape(inputIndices, inputShape, newShape)

參數:此方法接受以下參數:

  • inputIndices:它是所述的二維。 N x R_in 矩陣以及稀疏張量中加載值的索引。它可以是 tf.Tensor2D、TypedArray 或 Array 類型。
  • inputShape:它是所述的一維。 R_in Tensor1D 以及輸入稀疏張量的壓縮形狀。它可以是 tf.Tensor1D、TypedArray 或 Array 類型。
  • newShape:它是所述的一維。 R_out Tensor1D 以及所需的新壓縮形狀。它可以是 tf.Tensor1D、TypedArray 或 Array 類型。

返回值:它返回tf.Tensor對象。



範例1:在下麵的示例中,我們使用其所有參數調用了 sparse.sparseReshape() 函數,並打印了沒有索引和形狀的輸出響應。

Javascript


// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs")
  
// Calling sparse.sparseReshape() function
// with all its parameter
const res = tf.sparse.sparseReshape(
    [[1, 0, 1], [2, 0, 1], [1, 1, 2], [0, -1, 0], [-3, 1, 2]],
    [1, 2, 9], [-1, 9]);
  
// Printing output
console.log(res);

輸出:

{
  "outputIndices":{
    "kept":false,
    "isDisposedInternal":false,
    "shape":[
      5,
      2
    ],
    "dtype":"float32",
    "size":10,
    "strides":[
      2
    ],
    "dataId":{
      "id":82
    },
    "id":82,
    "rankType":"2",
    "scopeId":36
  },
  "outputShape":{
    "kept":false,
    "isDisposedInternal":false,
    "shape":[
      2
    ],
    "dtype":"float32",
    "size":2,
    "strides":[],
    "dataId":{
      "id":83
    },
    "id":83,
    "rankType":"1",
    "scopeId":36
  }
}

範例2:在以下示例中,我們使用其所有參數調用了 sparse.sparseReshape() 函數,並打印了輸出響應及其索引和形狀。

Javascript


// Importing the tensorflow.js library
const tf = require("@tensorflow/tfjs")
  
// Calling sparse.sparseReshape() function
// with all its parameter
const res = tf.sparse.sparseReshape(
    [[1.1, 0, 1.2], [2.1, 0.2, 1.3], [1.4, 2.3, 2.5], [null, -1, 0], [-3, 1, 2]],
    [1.0, 3, 3], [-1, 9]);
  
// Printing output indices
res['outputIndices'].print();
  
// Printing output shape
res['outputShape'].print();

輸出:

Tensor
    [[1 , 2 ],
     [2 , 2 ],
     [2 , 3 ],
     [0 , -3],
     [-2, -4]]
Tensor
    [1, 9]

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




相關用法


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