问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

Spearman 相关系数的可视化和应用场景

创作时间:
作者:
@小白创作中心

Spearman 相关系数的可视化和应用场景

引用
CSDN
1.
https://blog.csdn.net/flyfish1986/article/details/140290313

Spearman 相关系数的可视化和应用场景

Spearman 相关系数

Spearman 相关系数(Spearman’s Rank Correlation Coefficient),也称为Spearman 秩相关系数,用于衡量两个变量之间的单调关系(无论是线性还是非线性)。计算方法基于变量的秩次(即变量的排序 后面有例子),公式为(后面有推导过程):

$$
\rho = 1 - \frac{6 \sum d_i^2}{n(n^2 - 1)}
$$

其中,$d_i$ 是两个变量的秩次之差,$n$ 是样本数量。

变量是连续或离散型变量,变量不需要服从正态分布,适用于度量单调关系(无论是线性还是非线性)。对异常值不敏感,可以度量单调关系,对变量间的线性关系度量不如 Pearson 相关系数精确。

单调关系

单调关系是指在整个数据范围内,两个变量之间的关系始终保持单调性,即一个变量增加(或减少)时,另一个变量也始终增加(或减少),但不要求是线性关系。单调关系可以是单调递增或单调递减。

  • 单调递增:当一个变量增加,另一个变量也增加。
  • 单调递减:当一个变量增加,另一个变量减少。

变量的秩次(rank)

计算变量的秩次

步骤:

  1. 排序:首先,将数据按照从小到大的顺序进行排序。
  2. 分配秩次:为排序后的数据分配秩次。
  3. 处理重复值:如果存在重复值,对这些值分配相同的秩次,取它们的平均秩次。
  4. 还原原始顺序:将秩次分配还原到原始数据顺序中。

示例

假设有以下数据:

$$
x = [3, 1, 4, 1, 5]
$$

步骤 1: 排序

首先,将数据排序:

排序后的数据 = $[1, 1, 3, 4, 5]$

步骤 2: 分配秩次

为排序后的数据分配秩次:

排序后的数据 = $[1, 1, 3, 4, 5]$

秩次 = $[1, 2, 3, 4, 5]$

步骤 3: 处理重复值

注意到数据中有重复值 1。对于重复值,分配相同的秩次,取它们的平均秩次:

排序后的数据 = $[1, 1, 3, 4, 5]$

秩次 = $[1.5, 1.5, 3, 4, 5]$

步骤 4: 还原原始顺序

将分配好的秩次还原到原始数据的顺序中:

原始数据 = $[3, 1, 4, 1, 5]$

原始数据对应的秩次 = $[3, 1.5, 4, 1.5, 5]$

Python 代码验证

import numpy as np
import pandas as pd

# 原始数据
x = np.array([3, 1, 4, 1, 5])

# 使用 pandas 计算秩次
ranks = pd.Series(x).rank()

# 打印原始数据及其对应的秩次
print(f'原始数据: {x}')
print(f'对应的秩次: {ranks.values}')
原始数据: [3 1 4 1 5]
对应的秩次: [3.  1.5 4.  1.5 5. ]

Spearman 相关系数的计算 ,可视化数据和相关系数

散点图和秩次图

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import spearmanr

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 生成样本数据
np.random.seed(0)
x = np.random.randn(100)
y_linear = 2 * x + np.random.randn(100)  # 线性相关
y_nonlinear = np.sin(x) + np.random.randn(100) * 0.1  # 非线性相关

# 计算 Spearman 相关系数
spearman_corr_linear, _ = spearmanr(x, y_linear)
spearman_corr_nonlinear, _ = spearmanr(x, y_nonlinear)

print(f'Spearman 相关系数 (x, y_linear): {spearman_corr_linear}')
print(f'Spearman 相关系数 (x, y_nonlinear): {spearman_corr_nonlinear}')

# 可视化
plt.figure(figsize=(14, 6))

# 线性相关数据散点图
plt.subplot(1, 2, 1)
sns.scatterplot(x=x, y=y_linear)
plt.title(f'Linear Relationship\nSpearman 相关系数: {spearman_corr_linear:.2f}')
plt.xlabel('X')
plt.ylabel('Y')

# 非线性相关数据散点图
plt.subplot(1, 2, 2)
sns.scatterplot(x=x, y=y_nonlinear)
plt.title(f'Nonlinear Relationship\nSpearman 相关系数: {spearman_corr_nonlinear:.2f}')
plt.xlabel('X')
plt.ylabel('Y')

plt.tight_layout()
plt.show()

# 可视化秩次图
plt.figure(figsize=(14, 6))

# 线性相关数据秩次图
plt.subplot(1, 2, 1)
rank_x = pd.Series(x).rank()
rank_y_linear = pd.Series(y_linear).rank()
sns.scatterplot(x=rank_x, y=rank_y_linear)
plt.title(f'Rank Plot (Linear)\nSpearman 相关系数: {spearman_corr_linear:.2f}')
plt.xlabel('Rank of X')
plt.ylabel('Rank of Y')

# 非线性相关数据秩次图
plt.subplot(1, 2, 2)
rank_y_nonlinear = pd.Series(y_nonlinear).rank()
sns.scatterplot(x=rank_x, y=rank_y_nonlinear)
plt.title(f'Rank Plot (Nonlinear)\nSpearman 相关系数: {spearman_corr_nonlinear:.2f}')
plt.xlabel('Rank of X')
plt.ylabel('Rank of Y')

plt.tight_layout()
plt.show()

Spearman 相关系数主要应用于以下情况:

  1. 非线性单调关系:当两个变量之间存在非线性但单调的关系时,例如一个变量增加,另一个变量也增加(或减少),但不是线性关系。
  2. 异常值:数据集中存在异常值时,Spearman 相关系数对这些异常值不敏感,能提供更稳健的相关性度量。
  3. 非正态分布:当数据不符合正态分布时,Spearman 相关系数仍然可以提供有效的相关性度量。
  4. 序列数据:数据是有序但不连续的,例如排名数据或打分数据,适合使用 Spearman 相关系数。

进阶部分 公式的推导

假设有n个数据点,两个变量X和Y,各自的秩次分别为R(X_i)和R(Y_i)。定义秩次差d_i = R(X_i) - R(Y_i)。

1. 秩次差的平方和:

$$
\sum_{i=1}^n d_i^2 = \sum_{i=1}^n \left( R(X_i) - R(Y_i) \right)^2
$$

2. 完全独立的秩次:当X和Y完全独立时,秩次差d_i是独立且均匀分布的随机变量。

3. 期望值的计算:为了计算秩次差的平方和的期望,需要知道单个秩次差平方的期望。考虑两个秩次R(X_i)和R(Y_i)的差值d_i,可以使用以下步骤:

每个秩次R(X_i)和R(Y_i)都是从 1 到n的排列,因此可以看成是从集合 {1, 2, …, n} 中随机抽取的值。

可以把秩次差的期望值计算分成两个部分:

  1. 单个秩次差d_i的均值和方差:对于每一个d_i,因为秩次是独立且均匀分布的,所以有:

$$
E(d_i) = E(R(X_i) - R(Y_i)) = E(R(X_i)) - E(R(Y_i)) = \frac{n+1}{2} - \frac{n+1}{2} = 0
$$

$$
\text{Var}(d_i) = \text{Var}(R(X_i) - R(Y_i)) = \text{Var}(R(X_i)) + \text{Var}(R(Y_i)) = 2 \times \text{Var}(R) = 2 \times \frac{(n^2 - 1)}{12}
$$

其中Var(R) = \frac{(n^2 - 1)}{12} 是秩次R的方差。因此,d_i的方差是:

$$
\text{Var}(d_i) = \frac{n^2 - 1}{6}
$$

  1. 秩次差平方和的期望:由于d_i的均值为 0,方差为\frac{n^2 - 1}{6},所以d_i^2的期望是方差:

$$
E(d_i^2) = \text{Var}(d_i) = \frac{n^2 - 1}{6}
$$

因此,秩次差平方和的期望E(\sum d_i^2)为:

$$
E\left(\sum d_i^2\right) = n \cdot E(d_i^2) = n \cdot \frac{n^2 - 1}{6} = \frac{n(n^2 - 1)}{6}
$$

秩次的方差 解释 推导过程的12

假设有n个观测值,其秩次R_i从 1 到n分布。秩次的方差可以通过以下步骤计算:

  1. 秩次的均值:对于秩次R_i,其取值范围是 {1, 2, …, n}。均值为:

$$
E(R) = \frac{1 + 2 + \cdots + n}{n} = \frac{n(n + 1) / 2}{n} = \frac{n + 1}{2}
$$

  1. 秩次的方差:秩次的方差Var(R)是:

$$
\text{Var}(R) = E(R^2) - \left(E(R)\right)^2
$$

其中E(R^2)是所有秩次平方的均值,可以通过以下计算:

$$
E(R^2) = \frac{1^2 + 2^2 + \cdots + n^2}{n} = \frac{n(n + 1)(2n + 1)}{6n} = \frac{(n + 1)(2n + 1)}{6}
$$

假如n=10

$$
1^2+2^2+\cdots+n^2=\frac{(2n+1)(1+2+\cdots+n)}{3}=\frac{n(n+1)(2n+1)}{6}
$$

import numpy as np
import matplotlib.pyplot as plt

#  implementation of the triangular arrangement based on the description
def create_correct_triangle(n):
    triangle = np.zeros((n, n), dtype=int)
    for i in range(n):
        triangle[i, :i+1] = i+1
    return triangle

# Create the  triangular arrangement for n=10
correct_triangle = create_correct_triangle(10)

# Plot the  triangular arrangement
plt.figure(figsize=(10, 10))
plt.imshow(correct_triangle, cmap='viridis', interpolation='nearest')
plt.colorbar(label='Number')

# Add text for each cell
for i in range(10):
    for j in range(i+1):
        plt.text(j, i, correct_triangle[i, j], ha="center", va="center", color="w")

# Set labels and title
plt.title(' Triangular Arrangement for Squares Sum')
plt.xlabel('Column')
plt.ylabel('Row')
plt.grid(False)
plt.show()

因此,秩次的方差为:

$$
\text{Var}(R) = \frac{(n + 1)(2n + 1)}{6} - \left(\frac{n + 1}{2}\right)^2
$$

  1. 简化方差公式:通过对上式进行简化,得到:

$$
\text{Var}(R) = \frac{(n + 1)(2n + 1) \cdot 2}{12} - \frac{(n + 1)^2 \cdot 3}{12} = \frac{2(n + 1)(2n + 1) - 3(n + 1)^2}{12}
$$

继续简化:

$$
\text{Var}(R) = \frac{2n^2 + 2n + 2n + 1 - 3n^2 - 6n - 3}{12} = \frac{n^2 - 1}{12}
$$

最终得到秩次R的方差为:

$$
\text{Var}(R) = \frac{n^2 - 1}{12}
$$

秩次R

秩次R是指在一组数据中,每个数据点的排名。假设有一组数据X = {X_1, X_2, \ldots, X_n},可以给每个数据点分配一个秩次R(X_i),表示它在数据集中的相对位置。例如,在数据集X = {3, 1, 4, 1, 5}中,数据点的秩次R可以是{3, 1.5, 4, 1.5, 5}(在有重复值时,取平均秩次)。

秩次差d_i

秩次差d_i是两个变量的秩次之差。假设有两个变量X和Y,它们的秩次分别为R(X_i)和R(Y_i)。那么秩次差d_i定义为:

$$
d_i = R(X_i) - R(Y_i)
$$

这是计算 Spearman 秩相关系数时的重要步骤。通过计算所有数据点的秩次差d_i,可以进一步计算秩次差的平方和,从而得出 Spearman 秩相关系数。

举例说明

假设有两个变量X和Y:

$$
X = {3, 1, 4, 1, 5}
$$

$$
Y = {2, 3, 4, 3, 6}
$$

可以计算两个变量的秩次:

  • X的秩次R(X) = {3, 1.5, 4, 1.5, 5}
  • Y的秩次R(Y) = {1, 2.5, 3, 2.5, 4.5}

然后计算秩次差d_i:

$$
d = R(X) - R(Y) = {3 - 1, 1.5 - 2.5, 4 - 3, 1.5 - 2.5, 5 - 4.5} = {2, -1, 1, -1, 0.5}
$$

秩次差的方差

如前所述,秩次R的方差是:

$$
\text{Var}(R) = \frac{n^2 - 1}{12}
$$

而秩次差d_i的方差是两个秩次方差的和:

$$
\text{Var}(d_i) = \text{Var}(R(X)) + \text{Var}(R(Y)) = 2 \times \frac{n^2 - 1}{12} = \frac{n^2 - 1}{6}
$$

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号