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


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

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

.tensor()函數用於在值,形狀和數據類型的幫助下創建新的張量。

用法:

tf.tensor( value, shape, dataType)

Parameters: 

  • Value:張量的值,它可以是數字的簡單或嵌套Array或TypedArray。如果數組元素是字符串,則它們將編碼為UTF-8並保持為Uint8Array []。
  • 形狀[可選]:它是一個可選參數。它采用張量的形狀。如果未提供,則張量將從該值推斷出其形狀。
  • dataType [可選]:它也是可選參數。它可以是“ float32”或“ int32”或‘bool’或“ complex64”或‘string’。

返回值:它返回相同數據類型的張量。



範例1:在這個例子中,我們創建一個張量並打印它。為了創建張量,我們使用.tensor()方法,而要打印張量,我們使用.print()方法。

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Creating the tensor
var val = tf.tensor([1, 2, 3, 4, 5, 6, 7]);
 
// Printing the tensor
val.print()

輸出:

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

範例2:在此示例中,我們創建的張量沒有提到張量的shape參數,讓我們在這裏看到shape參數。

Javascript


// Importing the tensorflow library
import * as tf from "@tensorflow/tfjs"
 
// Defining the value of the tensor
var value = [1, 2, 3, 4, 5, 6]    
 
// Specify the shape of the tensor
var shape = [2, 3]
 
// Creting the tensor
var val = tf.tensor(value, shape)
 
// Printing the tensor
val.print()

輸出:

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

上麵的示例創建了2×3維的張量。

範例3:在此示例中,我們將創建具有值,形狀和數據類型的張量。我們正在創建String類型值的張量。

Javascript


// Importing the tensorflow.Js lbrary
import * as tf from "@tensorflow/tfjs"
 
// Creting a value variable which
// stores the value
var value = ['1', '2', '3', '4', '5', '6']
 
// Creting a shape variable
// which stores the shape
var shape = [2, 3]
 
// Creating a d_Type variable
// which strores the data-type
var d_Type = 'string'
 
// Creating the tensor
var val = tf.tensor(value, shape, d_Type)
 
// Printing the tensor
val.print()

輸出:

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

打印String類型值的張量。

相關用法


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