簡體   English   中英

關於 tensorflow 神經網絡中輸入大小的問題

[英]A question about input size in a tensorflow neural network

我是 PyTorch 用戶,但最近閱讀了一些使用 tensorflow 實現的代碼。 我的問題是,如果我們只有這樣一個簡單的神經網絡,輸入大小在哪里指定? 或者這個 model 是否允許使用可變大小的輸入?

class SimpleNet(tf.keras.Model):
    def __init__(self):
        super(SimpleNet, self).__init__()
        activation = tf.keras.activations.tanh
        self.features = [

         #Where is the input size specified?
            tf.keras.layers.Dense(89, activation),
            tf.keras.layers.Dense(6 * 32, activation),
            tf.keras.layers.Dense(32, activation),
            tf.keras.layers.Dense(1),
        ]

    def process(self, x):
        x = apply_layers(x, self.features)
        return x

    ...

當您將真實數據傳遞給input_shape時,會推斷 input_shape。 這意味着,如果您沒有明確定義input_shape ,它是可變的。 例如,您可以在input_shape的第一層顯式定義您的 input_shape:

tf.keras.layers.Dense(89, activation, input_shape=(5,))

並且每一層都從上一層的 output 導出所需的input shape 但是請注意,一旦您向 model 提供真實數據,它就會存儲此input_shape以供將來使用。 另一個例子表明,只要數據與第一個Dense層兼容,數據的形狀並不重要:

import tensorflow as tf

activation = tf.keras.activations.tanh
model1 = tf.keras.Sequential(
    [
    tf.keras.layers.Dense(89, activation),
    tf.keras.layers.Dense(6 * 32, activation),
    tf.keras.layers.Dense(32, activation),
    tf.keras.layers.Dense(1),
    ])

tf.print('Works -->', model1(tf.random.normal((10, 1))).shape)
model2 = tf.keras.Sequential(
    [
    tf.keras.layers.Dense(89, activation),
    tf.keras.layers.Dense(6 * 32, activation),
    tf.keras.layers.Dense(32, activation),
    tf.keras.layers.Dense(1),
    ])
tf.print('Works -->', model2(tf.random.normal((10, 5))).shape)
Works --> TensorShape([10, 1])
Works --> TensorShape([10, 1])

其中 10 表示樣本數,1 和 5 表示特征數。

暫無
暫無

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

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