相关性描述了数据之间的统计关系。这意味着相关性是相似性的度量:高度相关的两个信号(即具有强统计关系的信号)彼此相似
def correlation(signal1, signal2):
"""Return the correlation value of two signals which are assumed to be normalized (mean 0, std 1)."""
return np.mean(signal1 * signal2)
def normalize_and_correlate(signal1, signal2):
"""Return the correlation value of two signals after normalizing them."""
return correlation(
((signal1 - np.mean(signal1)) / np.std(signal1)),
((signal2 - np.mean(signal2)) / np.std(signal2)),
)
def plot_correlation(signal1, signal2, title=""):
# Ensure that both signals have the same number of samples
assert len(signal1) == len(signal2)
# Ensure that the signals have both mean 0 and standard deviation 1
signal1 = (signal1 - np.mean(signal1)) / np.std(signal1)
signal2 = (signal2 - np.mean(signal2)) / np.std(signal2)
multiplied_signals = signal1 * signal2
correlation_value = correlation(signal1, signal2)
y_max = max(np.max(np.abs(signal1)), np.max(np.abs(signal2)), np.max(np.abs(multiplied_signals)))
#fig, axs = plt.subplots(3, figsize=(12, 6))
fig = plt.figure(figsize=(12, 6), constrained_layout=True)
fig.suptitle(title)
# Create grid for the different plots
gs = fig.add_gridspec(3, 10)
axs = [fig.add_subplot(gs[0, :-1]), fig.add_subplot(gs[1, :-1]),
fig.add_subplot(gs[2, :-1]), fig.add_subplot(gs[:,-1])]
axs[0].plot(np.arange(len(signal1)), signal1, marker="o", lw=0.1)
axs[1].plot(np.arange(len(signal2)), signal2, marker="o", lw=0.1)
axs[2].plot(np.arange(len(multiplied_signals)), multiplied_signals, marker="o", lw=0.1)
axs[3].axhline(0, color="black", lw=0.5)
axs[3].axhline(correlation_value, lw=5)
axs[0].set_ylim(-y_max*1.1, y_max*1.1)
axs[1].set_ylim(-y_max*1.1, y_max*1.1)
axs[2].set_ylim(-y_max*1.1, y_max*1.1)
axs[2].set_ylim(-np.max(np.abs(multiplied_signals)) * 1.1, np.max(np.abs(multiplied_signals)) * 1.1)
axs[3].set_ylim(-1.01, 1.01)
axs[3].set_xticks([])
axs[0].get_xaxis().set_ticks([])
axs[0].set_ylabel("$x[t]$")
axs[1].set_ylabel("$y[t]$")
axs[2].set_ylabel("$x[t]\cdot y[t]$")
axs[1].get_xaxis().set_ticks([])
axs[2].set_xlabel("time in samples")
axs[0].title.set_text("The first signal $x[t]$")
axs[1].title.set_text("The second signal $y[t]$")
axs[2].title.set_text("Element-wise multiplication of both signals")
axs[3].title.set_text("Correlation: {:.2f}".format(correlation_value))
1.np.mean()计算全局均值
2.np.std()函数被用来:计算沿指定轴的标准差。返回数组元素的标准差
3.assert 语句用来声明某个条件是真的。
如果你非常确信某个你使用的列表中至少有一个元素,而你想要检验这一点,并且在它非真的时候引发一个错误,那么 assert 语句是应用在这种情形下的理想语句。
当 assert 语句失败的时候,会引发 AssertionError。
4.约束布局是指通过一系列限制来确定画布中元素的位置的方式,它预先会确定一个元素的绝对定位,之后以该元素的位置为基点对其他元素进行绝对定位,从而灵活地调整元素的位置。
matplolib 在绘制多子图时默认并未启用约束布局,它提供了两种方式启用约束布局:第一种方式是使用 subplots0或figure()函数的constrained_layout 参数;第二种方式是修改figure.constrained_layout.use 配置项。
5. ax.set_xlim,ax.set_ylim 设置x,y轴的最大值的上限
正弦波与偏移π的正弦波的相关性
signal2 = np.sin(np.linspace(np.pi, 5*np.pi, 40))
plot_correlation(signal1, signal2, "A sine wave and a sine wave shifted by $\pi$ are negatively correlated.")
这里我们看到两个信号沿水平轴镜像,因此所有元素乘积都为负。结果,相关值高但为负。因此,有时报告相关性的绝对值也是常见的。
两个(白色)噪声信号的相关性
np.random.seed(100)
noise1 = np.random.uniform(-1, 1, size=40)
noise2 = np.random.uniform(-1, 1, size=40)
plot_correlation(noise1, noise2, "Two different white noise signals should show no correlation.")
1.函数原型: numpy.random.uniform(low,high,size)
功能:从一个均匀分布[low,high)中随机采样,注意定义域是左闭右开,即包含low,不包含high.
ow: 采样下界,float类型,默认值为0;
high: 采样上界,float类型,默认值为1;
size: 输出样本数目,为int或元组(tuple)类型,例如,size=(m,n,k), 则输出 m * n * k 个样本
返回值:ndarray类型,其形状和参数size中描述一致。
正如我们在前面的(固定)示例中看到的,两个噪声信号不具有高相关性。这是由于它们的随机性。
注:由于我们总是要处理信号的方差,所以测量的相关性很少精确为0。
进一步注意:我们还将在稍后的实验中使用相关性来区分浊音和清音段。