0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

高次元空間ではランダムベクトルはほぼ直交する

0
Posted at

Pythonで確認してみます。

スクリーンショット 2026-05-02 20.37.17.png

import numpy as np
import matplotlib.pyplot as plt

def simulate_cosine_similarity(dim, num_samples=10000):
    """
    指定された次元数でランダムベクトルのペアを生成し、コサイン類似度を計算する
    """
    # 正規分布からランダムベクトルを生成 (num_samples x dim)
    v1 = np.random.randn(num_samples, dim)
    v2 = np.random.randn(num_samples, dim)
    
    # 各ベクトルのノルムを計算
    v1_norm = np.linalg.norm(v1, axis=1)
    v2_norm = np.linalg.norm(v2, axis=1)
    
    # 内積を計算
    dot_product = np.sum(v1 * v2, axis=1)
    
    # コサイン類似度 cos(theta) = (v1 . v2) / (|v1| * |v2|)
    cosine_sim = dot_product / (v1_norm * v2_norm)
    return cosine_sim

# 比較する次元数
dimensions = [2, 10, 100, 1000]
colors = ['blue', 'green', 'orange', 'red']

plt.figure(figsize=(10, 6))

for d, color in zip(dimensions, colors):
    similarities = simulate_cosine_similarity(d)
    
    # ヒストグラムの描画
    plt.hist(similarities, bins=100, range=(-1, 1), alpha=0.5, 
             label=f'Dimension $d={d}$', color=color, density=True)

plt.axvline(0, color='black', linestyle='--', alpha=0.5)
plt.title('Distribution of Cosine Similarity between Random Vectors')
plt.xlabel('Cosine Similarity ($\cos \\theta$)')
plt.ylabel('Density')
plt.legend()
plt.grid(axis='y', alpha=0.3)
plt.show()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?