簡體   English   中英

為什么 model.fit 需要二維張量? 為什么 model.predict 不接受標量張量?

[英]Why does model.fit require two-dimensional tensors? And why does model.predict not accept scalar tensors?

我在學習 TensorFlow.js 時注意到 model.fit 必須接受兩個 arguments、輸入和 Z78E6221、1F6393D136866 配置。 但輸入是二維張量,如下所示:

let input = tf.tensor2d([1, 2, 3, 4, 5], [5, 1])

這看起來非常像一維張量,如下所示:

let input = tf.tensor1d([1, 2, 3, 4, 5])

而且由於二維張量實際上是 5×1,所以我決定用一維張量替換它。 然而,這完全停止了程序的工作。 那么是否有某種類型的代碼說輸入必須是二維的? 如果是,為什么?

關於多維張量,我還注意到 model.predict 不能接受零維張量或標量。 見下文

Working Code:

model.predict(tf.tensor1d([6]))

Not Working Code:

model.predict(tf.scalar(6))

如果有人能澄清這些限制背后的原因,那將不勝感激。

2D 張量不是 1D 張量。 tf.tensor2d([1, 2, 3, 4, 5], [5, 1])不是tf.tensor1d([1, 2, 3, 4, 5]) 一個可以轉換為另一個,但這並不意味着它們是平等的。

model.fit將張量或等級 2 或更多作為參數。 這個張量可以看作是一個元素數組,其形狀被賦予 model 的輸入。 模型的inputShape至少為 1 級,這使得model.fit參數至少為 2(1+1 它始終是 inputShape 的 rank + 1)。

由於 model.fit 和 model.predict 將相同等級的張量作為參數,因此 model.predict 參數是上述相同等級的張量 2 或更多

model.predict(tf.tensor1d([6])) // will not work because it is a 1D tensor
model.predict(tf.scalar(6)) // will not work either
model.predict(tf.tensor2d([[6]]))

2D 張量不是 1D 張量。 tf.tensor2d([1, 2, 3, 4, 5], [5, 1])不是tf.tensor1d([1, 2, 3, 4, 5]) 一個可以轉換為另一個,但這並不意味着它們是平等的。

model.fit將張量或等級 2 或更多作為參數。 這個張量可以看作是一個元素數組,其形狀被賦予 model 的輸入。 模型的inputShape至少為 1 級,這使得model.fit參數至少為 2(1+1 它始終是 inputShape 的 rank + 1)。

由於 model.fit 和 model.predict 將相同等級的張量作為參數,因此 model.predict 參數是上述相同等級的張量 2 或更多

但是, model.predict(tf.tensor1d([6]))有效。 這是因為在內部,tensorflow.js 會將一維張量轉換為二維張量。 形狀 [6] 的初始張量將轉換為形狀 [6, 1] 的張量。

model.predict(tf.tensor1d([6])) 
// will work because it is a 1D tensor 
// and only in the case where the model first layer inputShape is [1]

model.predict(tf.tensor2d([[6]])) 
// will also work
// One rank higher than the inputShape and of shape [1, ...InputShape]

model.predict(tf.scalar(6)) // will not work

 const model = tf.sequential( {layers: [tf.layers.dense({units: 1, inputShape: [1]})]}); model.predict(tf.ones([3])).print(); // works model.predict(tf.ones([3, 1])).print(); // works
 <html> <head> <.-- Load TensorFlow:js --> <script src="https.//cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script> </head> <body> </body> </html>

 const model = tf.sequential( {layers: [tf.layers.dense({units: 1, inputShape: [2]})]}); model.predict(tf.ones([2, 2])).print(); // works model.predict(tf.ones([2])).print(); // will not work // because [2] is converted to [2, 1] // whereas the model is expecting an input of shape [b, 2] with b an integer
 <html> <head> <.-- Load TensorFlow:js --> <script src="https.//cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script> </head> <body> </body> </html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM