Tensorflow.js是Google開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。 .tensor2d()函數用於創建一個新的二維張量,其參數為值,形狀和數據類型。
用法:
tf.tensor2d (value, shape, datatype)
Parameters:
- value:張量的值,它可以是數字的嵌套數組,平麵數組或TypedArray。
- shape:它采用張量的形狀。如果未提供張量,則張量將從其值推斷其形狀。它是一個可選參數。
- datatype:它可以是‘float32’或‘int32’或‘bool’或‘complex64’或‘string’值。它是一個可選參數。
返回值:它返回相同數據類型的張量。返回的張量將始終是二維的。
注意:也可以使用tf.tensor()函數來實現2d張量函數,但是使用tf.tensor2d()可以使代碼易於理解和讀取。
範例1:在此示例中,我們將創建一個2D張量並進行打印。為了創建2D張量,我們使用.tensor2d()函數,並使用.print()函數打印張量。在這裏,我們將2D數組(即嵌套數組)傳遞給value參數。
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs";
// Create the tensor
let example1 = tf.tensor2d([ [ 1, 2, 3 ], [ 4, 5, 6 ] ]);
// Print the tensor
example1.print()
輸出:
Tensor [[1, 2, 3], [4, 5, 6]]
範例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];
// Specify the shape of the tensor
const shape = [2, 4];
// Create the tensor
let example2 = tf.tensor2d(value, shape);
// Print the tensor
example2.print();
輸出:
Tensor [[1, 2, 3, 4], [5, 6, 7, 8]]
在上麵的示例中,我們創建了2 x 4維的張量。
範例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 = [2, 4];
// Specify the datatype of value of the tensor
const datatype = "string";
// Create the tensor
let example3 = tf.tensor2d(value, shape, datatype);
// Print the tensor
example3.print();
輸出:
Tensor [['C' , 'C++', 'Java', 'Python'], ['PHP', 'JS' , 'SQL' , 'React' ]]
在上麵的示例中,張量的打印值是字符串數據類型。
相關用法
- PHP imagecreatetruecolor()用法及代碼示例
- p5.js year()用法及代碼示例
- d3.js d3.utcTuesdays()用法及代碼示例
- PHP ImagickDraw getTextAlignment()用法及代碼示例
- PHP Ds\Sequence last()用法及代碼示例
- PHP Imagick floodFillPaintImage()用法及代碼示例
- PHP array_udiff_uassoc()用法及代碼示例
- PHP geoip_continent_code_by_name()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- PHP GmagickPixel setcolor()用法及代碼示例
- PHP opendir()用法及代碼示例
- PHP cal_to_jd()用法及代碼示例
- d3.js d3.bisectLeft()用法及代碼示例
- PHP stream_get_transports()用法及代碼示例
- PHP Ds\Deque pop()用法及代碼示例
- PHP SimpleXMLElement children()用法及代碼示例
注:本文由純淨天空篩選整理自girishthatte大神的英文原創作品 Tensorflow.js tf.tensor2d() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。