深度學(xué)習(xí)中高斯噪聲:為什么以及如何使用

來(lái)源:DeepHub IMBA 本文約1800字,建議閱讀8分鐘
高斯噪聲是深度學(xué)習(xí)中用于為輸入數(shù)據(jù)或權(quán)重添加隨機(jī)性的一種技術(shù)。

在數(shù)學(xué)上,高斯噪聲是一種通過(guò)向輸入數(shù)據(jù)添加均值為零和標(biāo)準(zhǔn)差(σ)的正態(tài)分布隨機(jī)值而產(chǎn)生的噪聲。正態(tài)分布,也稱(chēng)為高斯分布,是一種連續(xù)概率分布,由其概率密度函數(shù) (PDF) 定義:
pdf(x) = (1 / (σ * sqrt(2 * π))) * e^(- (x — μ)2 / (2 * σ2))其中 x 是隨機(jī)變量,μ 是均值,σ 是標(biāo)準(zhǔn)差。
通過(guò)生成具有正態(tài)分布的隨機(jī)值并將它們添加到輸入數(shù)據(jù)。例如如果對(duì)圖像添加高斯噪聲,可以將圖像表示為像素值的二維矩陣,然后使用 numpy 庫(kù) np.random.randn(rows,cols) 生成具有正態(tài)分布的隨機(jī)值, 并將它們添加到圖像的像素值中。這就會(huì)得到添加了高斯噪聲的新圖像。
高斯噪聲也稱(chēng)為白噪聲,是一種服從正態(tài)分布的隨機(jī)噪聲。在深度學(xué)習(xí)中,訓(xùn)練時(shí)往往會(huì)在輸入數(shù)據(jù)中加入高斯噪聲,以提高模型的魯棒性和泛化能力。這稱(chēng)為數(shù)據(jù)擴(kuò)充。通過(guò)向輸入數(shù)據(jù)添加噪聲,模型被迫學(xué)習(xí)對(duì)輸入中的微小變化具有魯棒性的特征,這可以幫助它在新的、看不見(jiàn)的數(shù)據(jù)上表現(xiàn)更好。高斯噪聲也可以在訓(xùn)練過(guò)程中添加到神經(jīng)網(wǎng)絡(luò)的權(quán)重中以提高其性能,這種技術(shù)稱(chēng)為 Dropout。
讓我們先從一個(gè)簡(jiǎn)單的例子開(kāi)始:
噪聲的標(biāo)準(zhǔn)偏差 (noise_std) 被設(shè)置為較大的值 50,這將導(dǎo)致更多的噪聲被添加到圖像中??梢钥吹皆肼暩用黠@,并且原始圖像的特征不太明顯。
值得注意的是,在添加更多噪聲時(shí),需要確保噪聲不超過(guò)像素值的有效范圍(即 0 到 255 之間)。在這個(gè)例子中,np.clip() 函數(shù)用于確保噪聲圖像的像素值落在有效范圍內(nèi)。
雖然更多的噪聲可能更容易看出原始圖像和噪聲圖像之間的差異,但它也可能使模型更難以從數(shù)據(jù)中學(xué)習(xí)有用的特征,并可能導(dǎo)致過(guò)度擬合或欠擬合。所以最好從少量噪聲開(kāi)始,然后在監(jiān)控模型性能的同時(shí)逐漸增加噪聲。
import cv2import numpy as np# Load the imageimage = cv2.imread('dog.jpg')# Add Gaussian noise to the imagenoise_std = 50noise = np.random.randn(*image.shape) * noise_stdnoisy_image = np.clip(image + noise, 0, 255).astype(np.uint8)# Display the original and noisy imagesImage', image)Image', noisy_image)cv2.waitKey(0)cv2.destroyAllWindows()

高斯噪聲如何用于深度學(xué)習(xí)的一些示例。
數(shù)據(jù)增強(qiáng):高斯噪聲在深度學(xué)習(xí)中的一種常見(jiàn)用途是在訓(xùn)練期間將其添加到輸入數(shù)據(jù)中。例如可以在每個(gè)圖像通過(guò)模型之前添加高斯噪聲。這將迫使模型學(xué)習(xí)對(duì)輸入中的微小變化具有魯棒性的特征,這些噪聲可以代表圖像上的污跡或輕微的缺失。因此即使圖像與訓(xùn)練數(shù)據(jù)略有不同,模型也更有可能正確識(shí)別圖像。 Dropout:高斯噪聲在深度學(xué)習(xí)中的另一個(gè)用途是在訓(xùn)練期間將其添加到神經(jīng)網(wǎng)絡(luò)的權(quán)重中。這被稱(chēng)為Dropout。在訓(xùn)練過(guò)程中,dropout 以一定的概率(例如 0.5)隨機(jī)將網(wǎng)絡(luò)中的一些權(quán)重設(shè)置為零。這迫使網(wǎng)絡(luò)學(xué)習(xí)數(shù)據(jù)的多個(gè)冗余表示,使模型更健壯且不易過(guò)度擬合。 正則化:將高斯噪聲添加到模型的參數(shù)中也可以看作是一種正則化技術(shù)。它迫使模型具有更小的權(quán)重值,這反過(guò)來(lái)又使模型更通用并且更不容易過(guò)度擬合。 對(duì)抗訓(xùn)練:對(duì)抗性示例是專(zhuān)門(mén)為欺騙模型而設(shè)計(jì)的輸入,在對(duì)抗訓(xùn)練中,模型是在用小的、有針對(duì)性的擾動(dòng)增強(qiáng)的例子上訓(xùn)練的,比如高斯噪聲。這使得模型對(duì)對(duì)抗性示例更加穩(wěn)健。 半監(jiān)督學(xué)習(xí):訓(xùn)練時(shí)可以在輸入數(shù)據(jù)中加入高斯噪聲,提高半監(jiān)督模型的性能。這可以幫助模型更好地利用有限的標(biāo)記數(shù)據(jù)并學(xué)習(xí)更多的一般特征。 遷移學(xué)習(xí):微調(diào)時(shí)可以在輸入數(shù)據(jù)中加入高斯噪聲,以提高遷移學(xué)習(xí)模型的性能。這可以幫助模型更好地適應(yīng)新任務(wù)并更好地泛化到看不見(jiàn)的數(shù)據(jù)。 生成對(duì)抗網(wǎng)絡(luò) (GAN):可以將高斯噪聲添加到生成器輸入中,以提高生成樣本的多樣性。 貝葉斯深度學(xué)習(xí):訓(xùn)練時(shí)可以在模型的權(quán)重中加入高斯噪聲,使其對(duì)過(guò)擬合具有更強(qiáng)的魯棒性,提高模型的泛化能力。 強(qiáng)化學(xué)習(xí):在訓(xùn)練過(guò)程中,可以在代理的輸入或動(dòng)作空間中加入高斯噪聲,使其對(duì)環(huán)境變化具有更強(qiáng)的魯棒性,提高智能體的泛化能力。
在上述所有示例中,高斯噪聲通過(guò)特定的均值和標(biāo)準(zhǔn)差,以受控方式添加到輸入或權(quán)重。目標(biāo)是提高模型的性能和魯棒性,同時(shí)又不會(huì)讓模型很難從數(shù)據(jù)中學(xué)習(xí)。
下面我們介紹如何在使用 Python 和 Keras在訓(xùn)練期間將高斯噪聲添加到輸入數(shù)據(jù),說(shuō)明如何在訓(xùn)練期間將高斯噪聲添加到輸入數(shù)據(jù),然后再將其傳遞給模型:
from keras.preprocessing.image import ImageDataGenerator# Define the data generatordatagen = ImageDataGenerator(featurewise_center=False, # set input mean to 0 over the datasetsamplewise_center=False, # set each sample mean to 0featurewise_std_normalization=False, # divide inputs by std of the datasetsamplewise_std_normalization=False, # divide each input by its stdzca_whitening=False, # apply ZCA whiteningrotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)width_shift_range=0.1, # randomly shift images horizontally (fraction of total width)height_shift_range=0.1, # randomly shift images vertically (fraction of total height)horizontal_flip=False, # randomly flip imagesvertical_flip=False, # randomly flip imagesnoise_std=0.5 # add gaussian noise to the data with std of 0.5)# Use the generator to transform the data during trainingmodel.fit_generator(datagen.flow(x_train, y_train, batch_size=32),steps_per_epoch=len(x_train) / 32, epochs=epochs)
Keras 的 ImageDataGenerator 類(lèi)用于定義一個(gè)數(shù)據(jù)生成器,該數(shù)據(jù)生成器將指定的數(shù)據(jù)增強(qiáng)技術(shù)應(yīng)用于輸入數(shù)據(jù)。我們將 noise_std 設(shè)置為 0.5,這意味著標(biāo)準(zhǔn)偏差為 0.5 的高斯噪聲將添加到輸入數(shù)據(jù)中。然后在調(diào)用 model.fit_generator 期間使用生成器在訓(xùn)練期間將數(shù)據(jù)擴(kuò)充應(yīng)用于輸入數(shù)據(jù)。
至于Dropout,可以使用Keras中的Dropout層,設(shè)置dropout的rate,如果設(shè)置rate為0.5,那么dropout層會(huì)drop掉50%的權(quán)重。以下是如何向模型添加 dropout 層的示例:
from keras.layers import Dropoutmodel = Sequential()model.add(Dense(64, input_dim=64, activation='relu'))model.add(Dropout(0.5))model.add(Dense(64, activation='relu'))model.add(Dense(10, activation='softmax'))
需要注意的是,標(biāo)準(zhǔn)差、Dropout的實(shí)際值將取決于具體問(wèn)題和數(shù)據(jù)的特征。使用不同的值進(jìn)行試驗(yàn)并監(jiān)視模型的性能通常是一個(gè)好主意。
下面我們介紹使用Keras 在訓(xùn)練期間將高斯噪聲添加到輸入數(shù)據(jù)和權(quán)重。為了向輸入數(shù)據(jù)添加噪聲,我們可以使用 numpy 庫(kù)生成隨機(jī)噪聲并將其添加到輸入數(shù)據(jù)中。這是如何執(zhí)行此操作的示例:
import numpy as np# Generate some random input datax_train = np.random.rand(1000, 64)y_train = np.random.rand(1000, 10)# Add Gaussian noise to the input datanoise_std = 0.5x_train_noisy = x_train + noise_std * np.random.randn(*x_train.shape)# Train the modely_train, epochs=10)
我們輸入數(shù)據(jù) x_train 是形狀為 (1000, 64) 的二維數(shù)組,噪聲是使用 np.random.randn(*x_train.shape) 生成的,它將返回具有相同形狀的正態(tài)分布均值為 0,標(biāo)準(zhǔn)差為 1的隨機(jī)值數(shù)組。然后將生成的噪聲與噪聲的標(biāo)準(zhǔn)差 (0.5) 相乘,并將其添加到輸入數(shù)據(jù)中,從而將其添加到輸入數(shù)據(jù)中。
為了給權(quán)重添加噪聲,我們可以使用 Keras 中的 Dropout 層,它會(huì)在訓(xùn)練過(guò)程中隨機(jī)丟棄一些權(quán)重。高斯噪聲是深度學(xué)習(xí)中廣泛使用的技術(shù),在圖像分類(lèi)訓(xùn)練時(shí)可以在圖像中加入高斯噪聲,提高圖像分類(lèi)模型的魯棒性。這在訓(xùn)練數(shù)據(jù)有限或具有很大可變性時(shí)特別有用,因?yàn)槟P捅黄葘W(xué)習(xí)對(duì)輸入中的小變化具有魯棒性的特征。
以下是如何在訓(xùn)練期間向圖像添加高斯噪聲以提高圖像分類(lèi)模型的魯棒性的示例:
from keras.preprocessing.image import ImageDataGenerator# Define the data generatordatagen = ImageDataGenerator(featurewise_center=False, # set input mean to 0 over the datasetsamplewise_center=False, # set each sample mean to 0featurewise_std_normalization=False, # divide inputs by std of the datasetsamplewise_std_normalization=False, # divide each input by its stdzca_whitening=False, # apply ZCA whiteningrotation_range=0, # randomly rotate images in the range (degrees, 0 to 180)width_shift_range=0, # randomly shift images horizontally (fraction of total width)height_shift_range=0, # randomly shift images vertically (fraction of total height)horizontal_flip=False, # randomly flip imagesvertical_flip=False, # randomly flip imagesnoise_std=0.5 # add gaussian noise to the data with std of 0.5)# Use the generator to transform the data during trainingmodel.fit_generator(datagen.flow(x_train, y_train, batch_size=32),steps_per_epoch=len(x_train) / 32, epochs=epochs)
目標(biāo)檢測(cè):在目標(biāo)檢測(cè)模型的訓(xùn)練過(guò)程中,可以將高斯噪聲添加到輸入數(shù)據(jù)中,以使其對(duì)圖像中的微小變化(例如光照條件、遮擋和攝像機(jī)角度)更加魯棒。
def add_noise(image, std):"""Add Gaussian noise to an image."""noise = np.random.randn(*image.shape) * stdreturn np.clip(image + noise, 0, 1)# Add noise to the training imagesx_train_noisy = np.array([add_noise(img, 0.1) for img in x_train])# Train the modelmodel.fit(x_train_noisy, y_train, epochs=10)
語(yǔ)音識(shí)別:在訓(xùn)練過(guò)程中,可以在音頻數(shù)據(jù)中加入高斯噪聲,這可以幫助模型更好地處理音頻信號(hào)中的背景噪聲和其他干擾,提高語(yǔ)音識(shí)別模型的魯棒性。
def add_noise(audio, std):"""Add Gaussian noise to an audio signal."""noise = np.random.randn(*audio.shape) * stdreturn audio + noise# Add noise to the training audiox_train_noisy = np.array([add_noise(audio, 0.1) for audio in x_train])# Train the modelmodel.fit(x_train_noisy, y_train, epochs=10)
生成模型:在 GAN、Generative Pre-training Transformer (GPT) 和 VAE 等生成模型中,可以在訓(xùn)練期間將高斯噪聲添加到輸入數(shù)據(jù)中,以提高模型生成新的、看不見(jiàn)的數(shù)據(jù)的能力。
# Generate random noisenoise = np.random.randn(batch_size, 100)# Generate fake imagesfake_images = generator.predict(noise)# Add Gaussian noise to the fake imagesfake_images_noisy = fake_images + 0.1 * np.random.randn(*fake_images.shape)# Train the discriminatornp.zeros((batch_size, 1)))
在這個(gè)例子中,生成器被訓(xùn)練為基于隨機(jī)噪聲作為輸入生成新的圖像,并且在生成的圖像傳遞給鑒別器之前,將高斯噪聲添加到生成的圖像中。這提高了生成器生成新的、看不見(jiàn)的數(shù)據(jù)的能力。
對(duì)抗訓(xùn)練:在對(duì)抗訓(xùn)練時(shí),可以在輸入數(shù)據(jù)中加入高斯噪聲,使模型對(duì)對(duì)抗樣本更加魯棒。
下面的對(duì)抗訓(xùn)練使用快速梯度符號(hào)法(FGSM)生成對(duì)抗樣本,高斯噪聲為 在訓(xùn)練期間將它們傳遞給模型之前添加到對(duì)抗性示例中。這提高了模型對(duì)對(duì)抗性示例的魯棒性。
# Generate adversarial examplesx_adv = fgsm(model, x_train, y_train, eps=0.01)# Add Gaussian noise to the adversarial examplesnoise_std = 0.05x_adv_noisy = x_adv + noise_std * np.random.randn(*x_adv.shape)# Train the modely_train, epochs=10)
去噪:可以將高斯噪聲添加到圖像或信號(hào)中,模型的目標(biāo)是學(xué)習(xí)去除噪聲并恢復(fù)原始信號(hào)。下面的例子中輸入圖像“x_train”首先用標(biāo)準(zhǔn)的高斯噪聲破壞 0.1 的偏差,然后將損壞的圖像通過(guò)去噪自動(dòng)編碼器以重建原始圖像。自動(dòng)編碼器學(xué)習(xí)去除噪聲并恢復(fù)原始信號(hào)。
# Add Gaussian noise to the imagesnoise_std = 0.1x_train_noisy = x_train + noise_std * np.random.randn(*x_train.shape)# Define the denoising autoencoderinput_img = Input(shape=(28, 28, 1))x = Conv2D(32, (3, 3), activation='relu', padding='same')(input_img)x = MaxPooling2D((2, 2), padding='same')(x)x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)encoded = MaxPooling2D((2, 2), padding='same')(x)# at this point the representation is (7, 7, 32)x = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded)x = UpSampling2D((2, 2))(x)x = Conv2D(32, (3, 3), activation='relu', padding='same')(x)x = UpSampling2D((2, 2))(x)decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(x)autoencoder = Model(input_img, decoded)autoencoder.compile(optimizer='adam', loss='binary
異常檢測(cè):高斯噪聲可以添加到正常數(shù)據(jù)中,模型的目標(biāo)是學(xué)習(xí)將添加的噪聲作為異常檢測(cè)。
# Add Gaussian noise to the normal datanoise_std = 0.1x_train_noisy = x_train + noise_std * np.random.randn(*x_train.shape)# Concatenate the normal and the noisy datax_train_concat = np.concatenate((x_train, x_train_noisy))y_train_concat = np.concatenate((np.zeros(x_train.shape[0]), np.ones(x_train_noisy.shape[0])))# Train the anomaly detection modely_train_concat, epochs=10)
穩(wěn)健優(yōu)化:在優(yōu)化過(guò)程中,可以將高斯噪聲添加到模型的參數(shù)中,使其對(duì)參數(shù)中的小擾動(dòng)更加穩(wěn)健。
# Define the loss functiondef loss_fn(params):model.set_weights(params)return model.evaluate(x_test, y_test, batch_size=32)[0]# Define the optimizeroptimizer = optimizers.Adam(1e-3)# Define the step functiondef step_fn(params):with tf.GradientTape() as tape:loss = loss_fn(params)grads = tape.gradient(loss, params)optimizer.apply_gradients(zip(grads, params))return params + noise_std * np.random.randn(*params.shape)# Optimize the modelparams = model.get_weights()
高斯噪聲是深度學(xué)習(xí)中用于為輸入數(shù)據(jù)或權(quán)重添加隨機(jī)性的一種技術(shù)。它是一種通過(guò)將均值為零且標(biāo)準(zhǔn)差 (σ) 正態(tài)分布的隨機(jī)值添加到輸入數(shù)據(jù)中而生成的隨機(jī)噪聲。向數(shù)據(jù)中添加噪聲的目的是使模型對(duì)輸入中的小變化更健壯,并且能夠更好地處理看不見(jiàn)的數(shù)據(jù)。高斯噪聲可用于廣泛的應(yīng)用,例如圖像分類(lèi)、對(duì)象檢測(cè)、語(yǔ)音識(shí)別、生成模型和穩(wěn)健優(yōu)化。
作者:AI TutorMaster

