How to add Gaussian noise to data using Python?

Python can be used to add Gaussian noise to data using the numpy library. Below is an example code:

import numpy as np

def add_gaussian_noise(data, mean=0, std=1):
    noise = np.random.normal(mean, std, data.shape)
    noisy_data = data + noise
    return noisy_data

# 示例数据
data = np.array([1, 2, 3, 4, 5])

# 添加高斯噪声
noisy_data = add_gaussian_noise(data, mean=0, std=0.1)

# 打印结果
print("原始数据:", data)
print("加入高斯噪声后的数据:", noisy_data)

In the above code, the add_gaussian_noise function takes three parameters: data represents the input data, mean represents the mean of the Gaussian distribution, with a default value of 0, and std represents the standard deviation of the Gaussian distribution, with a default value of 1. Inside the function, numpy.random.normal function is used to generate random noise with the same shape as the input data, mean as mean, and standard deviation as std, and then add the noise to the input data to get the data with added noise.

bannerAds