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


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

Tensorflow.js是一個開放源代碼庫,由Google開發,用於在瀏覽器或節點環境中運行機器學習模型以及深度學習神經網絡。

.unique() 函數用於查找沿張量軸的唯一元素。

用法:

tf.unique (x, axis?)

參數:

  • x:它是第一個張量輸入,可以是 tf.Tensor、TypedArray 或 Array 類型。參數可以是這些類型(int32、string、bool)。
  • 軸(number ):它是可選的第二張量輸入。張量的軸用於查找唯一元素。

返回值:它返回值和索引。



範例1:在這個例子中,我們定義了一個整數類型的輸入張量,然後打印它的唯一值。為了創建輸入張量,我們使用 .tensor1d() 方法,為了打印輸出,我們使用 .print() 方法。

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining tensor input elements
const a = tf.tensor1d([1, 1, 2, 2, 4, 4, 7, 7, 8]);
  
// Calling unique() method 
const {values, indices} = tf.unique(a);
  
// Printing the values and indices 
values.print();   // [1, 2, 4, 7, 8,]
indices.print();  // [0, 0, 1, 1, 2, 2, 3, 3, 4]

輸出:

Tensor
    [1, 2, 4, 7, 8]
Tensor
    [0, 0, 1, 1, 2, 2, 3, 3, 4]

範例2:在此示例中,使用了軸參數。為了創建輸入張量,我們使用 .tensor2d() 方法,為了打印輸出,我們使用 .print() 方法。

Javascript


// Importing the tensorflow.js library 
import * as tf from "@tensorflow/tfjs"
  
// Defining tensor input elements 
const a = tf.tensor2d([[0, 0, 0], [2, 0, 0], [2, 0, 0]]);
  
// Calling the unique() method 
const {values, indices} = tf.unique(a, 0)
  
// Printing the values and indices
values.print();   // [[1, 0, 0],
                  //  [2, 0, 0]]
indices.print();  // [0, 0, 1]

輸出:

Tensor
    [[0, 0, 0],
     [2, 0, 0]]
Tensor
    [0, 1, 1]

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

相關用法


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