大規模モデルの数学的基盤: スカラーからテンソルまで

1. データ構造の基礎

1.1 スカラー

単一数値で表される最小単位。機械学習ではハイパーパラメータ表現に使用される。


# スカラー実装例
weight_decay = 0.0001  # 重み減衰係数
batch_size_val = 64    # バッチサイズ
temperature_scale = 1.0  # サンプリング温度

print(f"学習パラメータ: 減衰率={weight_decay}, サイズ={batch_size_val}")

1.2 ベクトル

n次元空間を表現する数値列。自然言語処理では単語埋め込みに応用される。


import numpy as np

# 5次元語彙表現
vocab_vector = np.array([0.2, -0.4, 0.7, 0.1, -0.3])  
# 位置情報符号化
pos_encoding = np.array([1, 0, 1, 0, 1])           

print(f"語彙ベクトル次元: {vocab_vector.shape}")
print(f"位置符号化パターン: {pos_encoding}")

1.3 行列

線形変換を実現する2次元配列。重み行列としてニューラルネットワークで活用。


# キー変換行列(4×3)
W_k = np.array([
    [0.3, -0.2, 0.5],
    [0.1, 0.4, -0.3],
    [-0.2, 0.6, 0.1],
    [0.4, 0.1, 0.2]
])

print(f"キー行列次元: {W_k.shape}")
print(f"転置行列:\n{W_k.T}")
print(f"フロベニウスノルム: {np.linalg.norm(W_k):.4f}")

1.4 テンソル

高次元データ表現の基本構造。多頭アテンション処理で多用される。


# 4階テンソル構築
batch = 4
length = 5
dim = 8
heads = 2

# 形状: (バッチ, 頭数, 長さ, 次元/頭数)
attn_tensor = np.random.randn(batch, heads, length, dim//heads)

print(f"テンソル形状: {attn_tensor.shape}")
print(f"要素総数: {attn_tensor.size}")

2. 基本演算

2.1 行列積

線形変換の核となる演算。入力データと重みの結合処理に使用。


# 変換処理例
input_data = np.array([[2, 3],    # 入力行列(2×2)
                        [4, 1]])
weight = np.array([[0.6, 0.4],   # 重み行列(2×2)
                    [0.3, 0.7]])

output = input_data @ weight  # 行列乗算
print(f"変換結果:\n{output}")
print(f"形状検証: {input_data.shape} × {weight.shape} → {output.shape}")

2.2 固有値解析

行列の本質的構造を抽出する手法。主成分分析に応用可能。


def pca_analysis():
    # 相関行列生成
    cov_matrix = np.array([[5, 2], 
                            [2, 3]])
    
    # 固有分解
    eigen_vals, eigen_vecs = np.linalg.eig(cov_matrix)
    
    print("主成分分析結果:")
    print(f"固有値: {eigen_vals}")
    print(f"寄与率: {eigen_vals/np.sum(eigen_vals):.2%}")
    
    # 低ランク近似
    reduced_rank = eigen_vecs[:, 0].reshape(2,1) @ eigen_vals[0] * eigen_vecs[:, 0].reshape(1,2)
    print(f"第一主成分近似誤差: {np.linalg.norm(cov_matrix - reduced_rank):.4f}")

pca_analysis()

3. ノルム体系

3.1 ベクトルノルム

モデル正則化に使用される距離尺度。代表的な3種類を実装。


def vector_norms():
    sample = np.array([2, -1, 3, 0.5])
    
    l1 = np.sum(np.abs(sample))  # L1ノルム
    l2 = np.sqrt(np.sum(sample**2))  # L2ノルム
    linf = np.max(np.abs(sample))  # 無限大ノルム
    
    print(f"サンプルベクトル: {sample}")
    print(f"L1ノルム: {l1}")
    print(f"L2ノルム: {l2:.4f}")
    print(f"無限大ノルム: {linf}")

vector_norms()

4. アテンション機構

4.1 クエリ・キー・バリュー処理

Transformerモデルの核となる計算フロー。


def attention_flow(query, key, value):
    # 内積による類似度計算
    similarity = query @ key.T  
    # スケーリング因子適用
    scaled = similarity / np.sqrt(key.shape[1])
    # softmax正規化
    weights = np.exp(scaled) / np.sum(np.exp(scaled), axis=1, keepdims=True)
    # 重み付き和
    output = weights @ value
    
    return output, weights

# 実装検証
q = np.random.randn(3, 4)  # クエリ行列
k = np.random.randn(5, 4)  # キー行列
v = np.random.randn(5, 6)  # バリューベクトル

result, attn_weights = attention_flow(q, k, v)
print(f"出力形状: {result.shape}")
print(f"重み分布合計: {np.sum(attn_weights[0]):.1f}")

タグ: テンソル計算 行列演算 アテンション機構 数値解析 線形代数

6月28日 16:33 投稿