論文中に 「Spearman順位相関係数」として登場する用語。
Spearman順位相関係数 とは:値そのものでなく「順位(rank)」で相関を計算。外れ値に強く、非線形でも単調なら検出可。
Spearman 順位相関係数(ρ, rho)は、 Pearson 相関の順位ベース版です。 値そのものでなく「順位」を使って相関を計算するため、 外れ値に強く、 非線形でも単調なら検出できます。
計算手順:
使い分け:
Python:scipy.stats.spearmanr(x, y)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # 基本パターン import pandas as pd import numpy as np from scipy import stats import matplotlib.pyplot as plt import seaborn as sns # データ読み込み df = pd.read_csv('data/raw/SSDSE-B-2026.csv', encoding='cp932') # 基本統計量 df.describe() # 可視化 sns.pairplot(df[['食料費', '教育費', '住居費']]) plt.show() |
このページの上にある3つの概念マップ(関係マップ、 包含マップ、 ツリーマップ)でこの概念の位置づけが視覚的に分かります。 関連手法を辿って学習を進めましょう。
統計データ活用コンペティションのSSDSE-B-2026データは、 47都道府県の社会経済データ。 この概念を使って以下のような分析ができます:
| 機能 | Python (pandas) | Python (scipy) |
|---|---|---|
| 要約統計 | df.describe() | stats.describe() |
| 平均 | df.mean() | np.mean() |
| 標準偏差 | df.std() | np.std() |
| 相関 | df.corr() | stats.pearsonr() |
| t検定 | — | stats.ttest_ind() |
| 回帰 | — | stats.linregress() |
| 分布フィッティング | — | stats.norm.fit() |
この概念は、 他の多くの統計概念と密接に関連しています。 ジャストインタイム型学習では、 必要に応じて関連用語へジャンプしながら全体像を構築します。
| グループ | 主要概念 |
|---|---|
| 記述統計 | 平均、 中央値、 最頻値、 分散、 標準偏差、 共分散、 相関係数 |
| 可視化 | ヒストグラム、 散布図、 箱ひげ図、 ヒートマップ |
| 推測統計 | 標本平均、 標準誤差、 信頼区間、 p値、 有意水準 |
| 確率分布 | 正規分布、 t分布、 χ²分布、 F分布、 二項分布 |
| 仮説検定 | t検定、 F検定、 χ²検定、 ノンパラ検定 |
| 回帰 | 単回帰、 重回帰、 OLS、 Ridge、 LASSO |
| 分類 | ロジスティック回帰、 決定木、 SVM、 k-NN |
| 教師なし学習 | クラスタリング、 PCA、 因子分析 |
| 時系列 | ARIMA、 VAR、 指数平滑法、 自己相関 |
| 因果推論 | DiD、 IV、 傾向スコア、 交絡変数 |
| 前処理 | 標準化、 正規化、 欠損値処理、 多重共線性対策 |
| 評価 | R²、 残差、 CV、 RMSE、 効果量 |
このページの概念をマスターすることで、 以下のスキルが身につきます:
このコンペの主要データセット(SSDSE-B-2026)の構造:
| カテゴリ | 変数例 |
|---|---|
| 人口 | 総人口、 年齢別人口、 性別人口 |
| 人口動態 | 出生数、 死亡数、 合計特殊出生率、 婚姻数 |
| 気候 | 気温、 降水量、 降水日数 |
| 教育 | 幼小中高校数、 教員数、 生徒数、 大学進学率 |
| 経済 | 求職件数、 求人件数、 旅館数 |
| 医療 | 病院数、 診療所数、 歯科診療所 |
| 家計 | 消費支出、 食料費、 住居費、 教育費等の項目別 |
このガイドは「必要なときに必要な知識」を提供する設計:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | # 必須ライブラリのインストール pip install pandas numpy scipy statsmodels scikit-learn matplotlib seaborn # 標準的なインポート import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score, mean_squared_error # 日本語表示の設定(matplotlib) plt.rcParams['font.family'] = 'Hiragino Sans' plt.rcParams['axes.unicode_minus'] = False # データ読み込み(SSDSE は cp932 エンコーディング) df = pd.read_csv('data/raw/SSDSE-B-2026.csv', encoding='cp932') print(df.shape) print(df.head()) print(df.describe()) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | def quick_eda(df, target=None): """探索的データ分析の基本テンプレート""" print(f"Shape: {df.shape}") print(f"\nColumn types:\n{df.dtypes}") print(f"\nMissing values:\n{df.isnull().sum()}") print(f"\nBasic stats:\n{df.describe()}") # 数値列の可視化 numeric_cols = df.select_dtypes(include=[np.number]).columns df[numeric_cols].hist(bins=20, figsize=(15, 10)) plt.tight_layout() plt.show() # 相関ヒートマップ if len(numeric_cols) > 1: plt.figure(figsize=(12, 10)) sns.heatmap(df[numeric_cols].corr(), annot=True, fmt='.2f', cmap='RdBu_r', center=0) plt.show() # ターゲットがあれば散布図行列 if target and target in df.columns: sns.pairplot(df[numeric_cols[:5]], hue=target if df[target].dtype == 'O' else None) plt.show() |
分析結果を報告する際の標準的な構成:
p値だけでなく効果量も併記するのが現代統計の標準。 主要な指標と Cohen の解釈基準:
| 統計量 | 効果量 | 小 | 中 | 大 |
|---|---|---|---|---|
| 2群平均差 | Cohen's d | 0.2 | 0.5 | 0.8 |
| 相関 | r | 0.1 | 0.3 | 0.5 |
| 線形回帰 | R² | 0.02 | 0.13 | 0.26 |
| ANOVA | η² (eta²) | 0.01 | 0.06 | 0.14 |
| χ² | Cramér's V | 0.1 | 0.3 | 0.5 |
| ロジスティック | Odds Ratio | 1.5 | 2.5 | 4.0 |
Spearman順位相関係数 がデータサイエンスの体系の中でどこに位置するかを、 3つの異なる視点で可視化します。 同じ情報でも見方を変えると気付きが変わります。
🌐 統計・データサイエンス › 関連・回帰 › 相関 › Spearman相関
中心の概念から放射状に、 前提・兄弟・発展形・応用先などの関係性を矢印で結びます。 横の繋がりを見るのに最適。 ノードをドラッグ、 ホイールでズーム、 クリックで遷移。
大きな円が小さな円を包含する Circle Packing 図。 「Spearman順位相関係数」は緑色でハイライト。
長方形を入れ子に分割した Treemap 図。 各分野の規模感を面積で比較。 「Spearman順位相関係数」は緑色でハイライト。
| マップ | 分かること | こんな時に見る |
|---|---|---|
| 🔗 関係マップ | 手法間の横の関係(前提→発展→応用) | 「次に何を学べばよい?」 学習順序の判断 |
| ⭕ 包含マップ | 分類体系の入れ子構造(上位⊃下位) | 「この手法はどんなジャンルに属する?」 |
| 🌳 ツリーマップ | 分野の規模比較(面積=ボリューム) | 「データサイエンス全体の俯瞰像」 |
💡 ジャストインタイム学習のヒント:3つの視点を行き来することで、 概念を多角的に理解できます。 包含マップやツリーマップはズーム/ドリルダウンで大分類から細部まで探索できます。
Spearman 順位相関とその近縁用語:
47都道府県の主要 8 変数で Spearman 順位相関行列を作り、 Pearson との比較で「非線形だが単調」な関係を炙り出す。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from scipy import stats df = pd.read_csv('data/raw/SSDSE-B-2026.csv', encoding='cp932', header=1) df.columns = [c.strip() for c in df.columns] cols = ['総人口', '65歳以上人口', '製造品出荷額等', '小売業年間商品販売額', '現金給与総額', '一般病院数', '完全失業率', '出生率'] X = df[cols].apply(pd.to_numeric, errors='coerce') rho_s = X.corr(method='spearman').round(3) rho_p = X.corr(method='pearson').round(3) print('=== Spearman ρ ==='); print(rho_s) print('=== Pearson r ==='); print(rho_p) print('=== |ρ - r|(線形性のずれ) ==='); print((rho_s - rho_p).abs().round(3)) |
典型的な観察例: 総人口と製造品出荷額は Pearson r=0.96 / Spearman ρ=0.92 とほぼ一致するが、 完全失業率と出生率は Pearson=-0.18 / Spearman=-0.34 と大きく違う。 後者は「線形ではないが単調」な関係を示唆。 ρ と r の差分が大きいペアを優先的に散布図で確認する。
1 2 3 4 5 6 7 8 9 10 11 12 | from itertools import combinations rows = [] n = len(X) for a, b in combinations(cols, 2): rho, p = stats.spearmanr(X[a], X[b], nan_policy='omit') # Fisher z 変換で 95% CI z = np.arctanh(rho) se = 1/np.sqrt(n-3) lo, hi = np.tanh(z - 1.96*se), np.tanh(z + 1.96*se) rows.append([a, b, rho, p, lo, hi]) res = pd.DataFrame(rows, columns=['a','b','rho','p','CI_lo','CI_hi']) print(res.sort_values('rho').round(3).to_string(index=False)) |
1 2 3 4 5 6 7 8 | fig, axes = plt.subplots(1, 2, figsize=(13, 5.5)) sns.heatmap(rho_s, annot=True, fmt='.2f', cmap='RdBu_r', vmin=-1, vmax=1, ax=axes[0]) axes[0].set_title('Spearman ρ') sns.heatmap(rho_p, annot=True, fmt='.2f', cmap='RdBu_r', vmin=-1, vmax=1, ax=axes[1]) axes[1].set_title('Pearson r') plt.tight_layout(); plt.savefig('corr_compare.png', dpi=140) |
Spearman ρ が捉えるのは「単調関係(monotonic)」だけで、 U 字や逆 U 字のような非単調関係は Pearson と同様に 0 に近くなる。 「ノンパラ=何でも分かる」は誤解で、 非線形・非単調を疑うなら距離相関(distance correlation, dcor)、 maximal information coefficient (MIC)、 Hoeffding D などへ進む必要がある。 また「単調ではあるが微弱」の場合も ρ は小さい値しか出ない。
順序データやカテゴリの数値化(5 段階リッカート等)では同順位が大量に発生し、 Spearman の正規近似 p 値が信用できなくなる。 タイがある場合は scipy.stats.spearmanr の method='asymptotic'(タイ補正済み)か、 並べ替え検定で求めるのが確実。 タイが多いなら Kendall τ-b(タイ補正版)の方が頑健。 査読時に「タイの扱い」を必ず聞かれるので明記すること。
直観的には便利な指標だが、 「差分が小さい=線形」は厳密ではない。 標本サイズが小さければ差分が偶然大きくなり、 大きければ差分が偶然小さくなる。 差分の正式な検定は存在せず、 ブートストラップで信頼区間を作るくらい。 真の線形性検定をしたいなら Ramsey RESET 検定や、 残差プロットの目視を推奨。
Spearman は順位に変換するため確かに外れ値に頑健だが、 「順位の中で極端な点」(最大・最小に張り付く点)の影響は残る。 たとえば東京・神奈川を含む 47 都道府県データでは、 順位 1 と順位 2 が特定の組合せで固定されるため、 ρ は依然として影響を受ける。 外れ値を完全に除きたいなら、 95% トリミング相関や中央値ベースのロバスト相関を検討する。
n=10 で ρ=0.7 を見て「強い相関」と結論するのは早い。 95%CI は概ね [0.13, 0.92] と非常に広く、 偶然のばらつきで簡単に変わる。 小サンプルでは必ず CI(Fisher z 変換)と並べ替え検定 p 値を両方報告すること。 n < 20 では Kendall τ の方が漸近正規近似が安定するという指摘もある。
「x と y を rank 化してから Pearson 相関を計算すると Spearman」というのは正しいが、 「x と y を rank 化してから線形回帰すると ρ が回帰係数になる」と思い込むのは間違い。 順位回帰の係数は ρ ではなく、 Spearman の式とは異なる。 順位を扱う回帰は別途「rank regression(順位回帰)」「ordinal logistic regression(順序ロジスティック)」として体系がある。
1 2 3 4 5 6 7 | from scipy import stats rho, p = stats.spearmanr(x, y) # 多変量行列 rho_mat, p_mat = stats.spearmanr(X, axis=0) # タイがある場合の選択 rho, p = stats.spearmanr(x, y, nan_policy='omit', alternative='two-sided') |
1 2 3 4 5 6 | spearman = df.corr(method='spearman') pearson = df.corr(method='pearson') kendall = df.corr(method='kendall') # 全部まとめて for m in ['pearson','spearman','kendall']: print(m); print(df.corr(method=m).round(2)) |
1 2 3 4 5 6 | import pingouin as pg # Spearman + CI + power res = pg.corr(x, y, method='spearman') print(res[['r','CI95%','p-val','power']]) # ペアワイズ・全変数で print(pg.pairwise_corr(df, method='spearman')) |
1 2 3 4 5 6 7 8 9 | import seaborn as sns g = sns.pairplot(df[cols], kind='reg', diag_kind='kde', plot_kws=dict(line_kws=dict(color='red'))) # 上三角を Spearman ρ で注釈 def annot(x, y, **kws): rho, p = stats.spearmanr(x, y) ax = plt.gca() ax.annotate(f'ρ={rho:.2f}', xy=(0.05,0.9), xycoords='axes fraction') g.map_upper(annot) |
1 2 3 4 5 6 7 | from scipy.stats import permutation_test def stat(x, y): return stats.spearmanr(x, y).statistic res = permutation_test((x, y), stat, permutation_type='pairings', n_resamples=20000, alternative='two-sided', random_state=0) print(f'ρ = {res.statistic:.3f}, p_perm = {res.pvalue:.4f}') |
「スピアマンの順位相関」を理解するうえで必要なキーワードを 10 件以上提示します。 各チップから対応セクションへ移動できます。
30 秒結論 文脈 直感 数式 記号読み解き 実値計算 Python 実装 落とし穴 関連手法 関連用語 グループ教材 概念マップ
このセクションは「スピアマンの順位相関」を扱う 用語ページ です。 統計データ分析コンペティション(2026)の再現教材における中核用語のひとつで、47都道府県の人口 (A1101) と所得 (A4101) の順位相関 という観点で SSDSE-B-2026(47 都道府県 × 複数年 × 100 超列)に紐づけられます。
位置づけ:相関・線形回帰・仮説検定 といった基礎用語群と並列であり、応用としては 内生性・IV・DID・クラスタリング 等へ繋がります。
スピアマンの順位相関 を一言でいえば「47都道府県の人口 (A1101) と所得 (A4101) の順位相関」。 47 都道府県という小さな母集団でも、 SSDSE-B-2026 の A1101 列に注目すると、 大都市圏と地方の差・人口規模に伴う相対比較など、 様々なパターンが見えてきます。
比喩でいうと、 スピアマンの順位相関 はデータ分析の「眼鏡」のようなもの。 同じデータでも眼鏡を変えれば、 平均(中心)・分散(ばらつき)・相関(連動)・因果(影響)と、 異なる情報が浮かび上がります。 SSDSE-B-2026 を題材に、 この眼鏡をかけてみるのが本ページの狙いです。
スピアマンの順位相関 の代表的な定義式は次のとおりです。
$$ r_s = 1 - \frac{6 \sum d_i^2}{n(n^2-1)} $$ここで使われる記号や演算の意味は次節で言葉に翻訳します。
数式の各記号を、日本語の意味に変換します。
SSDSE-B-2026(公的統計の社会・教育系データセット、 47 都道府県 × 10 年分超 × 100 以上の列)を用いて、 「スピアマンの順位相関」を体感します。 ファイル名は SSDSE-B-2026.csv、 読み込みは下記の Python コードで行います。
import pandas as pd
# SSDSE-B-2026 を読み込む(cp932 / Shift_JIS)
df = pd.read_csv('data/raw/SSDSE-B-2026.csv', skiprows=[1], encoding='cp932')
print(df.shape) # (564, 112)
print(df['SSDSE-B-2026'].unique()) # 含まれる年度
latest = df[df['SSDSE-B-2026'] == df['SSDSE-B-2026'].max()].copy()
print(latest[['Prefecture', 'A1101', 'A4101']].head())
ここで使った中心列 A1101 は SSDSE-B-2026 における 47都道府県の人口 (A1101) と所得 (A4101) の順位相関 に関連する指標です。 算出例:
A1101 平均と標準偏差を求めるA1101 と A4101 の相関(線形・順位)を比較するscipy / pandas / scikit-learn / statsmodels を中心とした標準的な実装例です。 まず CSV を読み込み、 次に スピアマンの順位相関 の解析を行います。
import pandas as pd
import numpy as np
from scipy import stats
df = pd.read_csv('data/raw/SSDSE-B-2026.csv', skiprows=[1], encoding='cp932')
df = df[df['SSDSE-B-2026'] == df['SSDSE-B-2026'].max()].copy()
x = df['A1101'].astype(float).values
y = df['A4101'].astype(float).values
# 基本統計量
print('n =', len(x))
print('mean(x) =', np.mean(x))
print('std(x) =', np.std(x, ddof=1))
# スピアマンの順位相関 の代表的計算(用途に応じて scipy/statsmodels を切替える)
r, p = stats.pearsonr(x, y)
print(f'Pearson r = {r:.4f}, p = {p:.4g}')
rs, ps = stats.spearmanr(x, y)
print(f'Spearman rho = {rs:.4f}, p = {ps:.4g}')
用途別の追加実装:
# 標準化と簡易クラスタリングの例
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
X = df[['A1101', 'A4101']].astype(float).values
Xs = StandardScaler().fit_transform(X)
km = KMeans(n_clusters=4, n_init=10, random_state=0).fit(Xs)
df['cluster'] = km.labels_
print(df[['Prefecture', 'A1101', 'A4101', 'cluster']].head(10))
# 時系列(北海道の A1101)— 例として ARIMA 系の前処理
import statsmodels.api as sm
ts = df.sort_values('SSDSE-B-2026').groupby('SSDSE-B-2026')['A1101'].mean()
print(ts.tail())
res = sm.tsa.stattools.adfuller(ts)
print('ADF stat:', res[0], 'p:', res[1])
スピアマンの順位相関 を実務で扱う際に踏みやすい落とし穴を 5 件挙げます。
本ページでは「スピアマンの順位相関」を 12 セクション(🔖 キーワード索引/💡 30 秒結論/📍 文脈/🎨 直感/📐 数式/🔬 記号読み解き/🧮 実値計算/🐍 Python 実装/⚠️ 落とし穴/🌐 関連手法/🔗 関連用語/📚 グループ教材)で完結に整理しました。 SSDSE-B-2026 を素材に、 概念の輪郭・式の意味・実装手順・典型的な失敗パターンの 4 点を最低限押さえれば、 統計データ分析コンペの現場で迷わず使えるはずです。