我认为您走在正确的轨道上,噪声本质上是加性的,如果您查看 (SNR) 信噪比计算
信噪比 = 20 * log(p_s)/(p_n)
这不过是
信噪比 = 20 (log(p_s) - log(p_n))
所以我们基本上是减去信号(有噪声)中的噪声功率
为整个信号添加噪声
我会和你发布的一样做
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(137)
t = np.linspace(0, 10, 100)
p = np.sin(t)
percentage = 0.05
n = np.random.normal(0, p.std(), t.size) * percentage
pn = p + n
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.set_title('Noise added to entire signal')
ax1.plot(t, p, label='pure signal')
ax1.plot(t, pn, label='signal+noise')
ax2 = fig.add_subplot(212)
ax2.plot(t, pn - p, label='added noise', c='r')
plt.legend()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.set_title('Noise added to part of the signal')
ax1.plot(t, p, label='pure signal')
random_indices = np.random.randint(0, t.size, int(t.size*percentage))
pr = p.copy()
pr[random_indices] += n[random_indices]
ax1.plot(t, pr, label='signal+noise')
ax2 = fig.add_subplot(212)
ax2.plot(t, pr - p, label='added noise', c='r')
plt.legend()
plt.show()
注意
我注意到的一件有趣的事情是np.random.normal 对于非常小的方差值主要采样正值,因此最好缩放 5%,即用更高的方差值采样后的方差