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


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

當您想創建一個沒有多個輸入和輸出的模型並且它將逐層開發時,我們將使用深度學習的順序模型。本質上有兩種類型的模型函數和順序模型。所以在本文中,我們將在 Tensorflow.js 中看到帶有 tf.sequential() 的 Sequential 模型。

tf.sequential() 函數創建一個模型,其中一層的一個輸出是下一層的輸入。簡單來說,我們可以說它是一個沒有分支和跳躍的線性層堆疊。

用法:

tf.sequential( layers, name )

參數:

  • layers:它是我們要添加到模型中的層的列表。
  • name:型號名稱。

範例1:在此示例中,我們將創建一個具有 2 個密集層的輸入形狀 3 的序列模型,並使用該模型進行一些預測。



在 inputShape:[null,3] 中,第一個參數是未確定的批次維度,第二個參數是模型最後一層的輸出大小。您可以傳遞 inputShape:[null, 3] 或 inputShape:[3]

Javascript


// Import Tensorflow.js
import * as tf from "@tensorflow/tfjs"
  
// Create model tf.sequential() method
// Here you need to specify the input 
// shape for first layer manually and
// for the second layer it will 
// automatilly update
var model = tf.sequential({ 
    layers:[tf.layers.dense({units:1,inputShape:[3]}),
    tf.layers.dense({units:4})] 
});
        
// Prediction with model
console.log('Lets Predict Something:');
model.predict(tf.ones([1,3])).print();

輸出:

Lets Predict Something:
Tensor
    [[-1.1379941, 0.945751, -0.1970642, -0.5935861],]

範例2:在此示例中,我們將使用 model.add() 函數創建一個具有 2 個輸入形狀為 16 的密集層的模型,以向模型中添加一個密集層。

Javascript


// Import Tensorflow.js
import * as tf from "@tensorflow/tfjs"
  
// Create sequantial model
var model = tf.sequential();
  
// Add dense layer using model.add() 
model.add(tf.layers.dense({units:8, inputShape:[16]}));
  
model.add(tf.layers.dense({units:4}));
  
// Predict something
console.log('Lets predict something:');
model.predict(tf.ones([8,16])).print();
Output:
Lets predict something:
Tensor
   [[0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824],
    [0.9305074, -0.7196146, 0.5809593, -0.08824]]

參考文獻: https://js.tensorflow.org/api/latest/#sequential

相關用法


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