溫馨提示×

TensorFlow中怎么實現(xiàn)丟棄法

小億
84
2024-05-10 15:19:54

在TensorFlow中,可以通過使用tf.keras.layers.Dropout層來實現(xiàn)丟棄法。丟棄法是一種常用的正則化技術(shù),可以在訓(xùn)練過程中隨機丟棄一部分神經(jīng)元,防止過擬合。

下面是一個使用丟棄法的簡單示例:

import tensorflow as tf

# 定義一個包含丟棄法的神經(jīng)網(wǎng)絡(luò)模型
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation='softmax')
])

# 編譯模型
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# 訓(xùn)練模型
model.fit(train_images, train_labels, epochs=5)

在上面的示例中,tf.keras.layers.Dropout(0.2)表示在訓(xùn)練過程中以概率0.2丟棄輸入的神經(jīng)元。在測試過程中,該層會保持所有神經(jīng)元的輸出。

0