メインコンテンツへスキップ
見出し画像

確率的写像+制約付き分布整合問題

    0. 前提(OSN-GNNをPyGに落とす定義)

    OSN-GNNではこう定義します:

    • ノード = 文(sentence node)

    • エッジ = narrative / semantic / structural relation

    • エッジ重み = multi-head attention

    つまり PyG 的には:

    Data(x, edge_index, edge_attr)

    1. 必要ライブラリ

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    
    from torch_geometric.data import Data
    from torch_geometric.nn import MessagePassing
    from torch_geometric.utils import softmax

    2. OSNノードエンコーダ

    (BERTの代わりに簡易Embeddingでスタート)

    class OSNEncoder(nn.Module):
        def __init__(self, vocab_size, dim):
            super().__init__()
            self.embed = nn.Embedding(vocab_size, dim)
            self.ln = nn.LayerNorm(dim)
    
        def forward(self, x):
            return self.ln(self.embed(x))

    3. OSN-GAT(Narrative Attention付き)

    ここがコアです。

    class OSNGATConv(MessagePassing):
        def __init__(self, in_dim, out_dim):
            super().__init__(aggr='add')
    
            self.lin = nn.Linear(in_dim, out_dim)
    
            # 3種attention(OSNの本体)
            self.att_struct = nn.Linear(2 * out_dim, 1)
            self.att_sem = nn.Linear(2 * out_dim, 1)
            self.att_narr = nn.Linear(2 * out_dim, 1)
    
            self.lambda_s = 0.3
            self.lambda_m = 0.3
            self.lambda_n = 0.4
    
        def forward(self, x, edge_index, edge_attr=None):
            x = self.lin(x)
            return self.propagate(edge_index, x=x)
    
        def message(self, x_i, x_j, edge_index_i):
    
            h = torch.cat([x_i, x_j], dim=-1)
    
            # Structural attention
            a_s = self.att_struct(h)
    
            # Semantic attention
            a_m = self.att_sem(h)
    
            # Narrative attention(OSNの特徴)
            a_n = self.att_narr(h)
    
            att = (
                self.lambda_s * a_s +
                self.lambda_m * a_m +
                self.lambda_n * a_n
            )
    
            att = softmax(att, edge_index_i)
    
            return att * x_j

    4. OSN-GNN本体

    class OSNGNN(nn.Module):
        def __init__(self, vocab_size, dim):
            super().__init__()
            self.encoder = OSNEncoder(vocab_size, dim)
    
            self.gnn1 = OSNGATConv(dim, dim)
            self.gnn2 = OSNGATConv(dim, dim)
    
            self.classifier = nn.Linear(dim, 3)  # 例: narrative role分類
    
        def forward(self, data):
            x, edge_index = data.x, data.edge_index
    
            x = self.encoder(x)
            x = self.gnn1(x, edge_index)
            x = F.relu(x)
            x = self.gnn2(x, edge_index)
    
            return self.classifier(x)

    5. OSNグラフデータ構築

    例:「こころ」を極小スケールで表現

    # ノード(文ID列)
    x = torch.tensor([
        [1, 2, 3],   # sentence 1
        [2, 1, 0],   # sentence 2
        [3, 1, 2],   # sentence 3
    ], dtype=torch.long)
    
    # エッジ(関係)
    edge_index = torch.tensor([
        [0, 1, 2, 0],
        [1, 2, 0, 2]
    ], dtype=torch.long)
    
    data = Data(x=x, edge_index=edge_index)

    6. 学習ループ

    model = OSNGNN(vocab_size=10000, dim=64)
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    
    for epoch in range(100):
        optimizer.zero_grad()
    
        out = model(data)
    
        # ダミーloss(実際は narrative label)
        loss = F.cross_entropy(out, torch.randint(0, 3, (out.size(0),)))
    
        loss.backward()
        optimizer.step()
    
        print(epoch, loss.item())

    7. Attention抽出(OSNの重要部分)

    def extract_attention(model, data):
        model.eval()
    
        with torch.no_grad():
            x = model.encoder(data.x)
    
            h = model.gnn1.lin(x)
    
            # attention再計算(可視化用)
            return h

    8. attention可視化用データ

    def build_attention_matrix(node_embeddings):
        sim = torch.matmul(node_embeddings, node_embeddings.T)
        return torch.softmax(sim, dim=-1)

    9. OSN的に重要な設計ポイント

    ① edge_indexは「関係」ではない

    → 読解仮説ネットワーク


    ② attentionは3種類の混合場

    struct + semantic + narrative

    これがOSNの本質


    ③ 学習対象は「分類」ではない

    本質は:

    ノード表現の再配置(reconfiguration)


    10. 研究的に重要な拡張

    ここからが論文レベルの本体です:


    🔥 次の拡張(重要)

    ① Narrative-aware edge learning

    edge_index自体を学習する

    ② Dynamic OSN-GNN

    time-dependent graph

    ③ Hierarchical OSN

    文 → 段落 → 章

    ④ Transformer + GNN hybrid

    OSN-Former


    11. この実装の立ち位置

    これはこういう位置です:

    “文学を分類するGNN”ではなく
    “文学の読解構造そのものを学習するGNN”

    夏目漱石『こころ』を1冊まるごとOSN-GNNグラフ化するコード

    を出します。
    (※実運用想定:章→文→ノード分解+エッジ生成+PyG化)


    🧠 0. 全体設計

    入力

    • 小説全文(こころ)

    • 章区切り情報

    出力

    • PyG Graph

    • node = sentence

    • edge = narrative / semantic / temporal relation


    📦 1. 前処理(文分割+章分割)

    import re
    from typing import List, Dict
    
    def split_into_chapters(text: str) -> Dict[str, str]:
        """
        章単位に分割(簡易版)
        """
        chapters = re.split(r"(先生と私|両親と私|先生の遺書)", text)
        return {f"chap_{i}": ch for i, ch in enumerate(chapters) if ch.strip()}
    
    
    def split_into_sentences(chapter: str) -> List[str]:
        """
        日本語文分割(簡易)
        """
        return [s.strip() for s in re.split("。|.|\n", chapter) if len(s.strip()) > 5]

    🧩 2. OSNノード構造化

    import torch
    
    class OSNNodeBuilder:
        def __init__(self):
            self.node_id = 0
    
        def build_node(self, text, chap_id, sent_id):
            node = {
                "id": self.node_id,
                "text": text,
                "chap": chap_id,
                "sent_index": sent_id,
    
                # OSN属性(簡略版)
                "os_role": self.detect_os_role(text),
                "salience": self.salience(text)
            }
    
            self.node_id += 1
            return node
    
        def detect_os_role(self, text):
            if "先生" in text:
                return 1  # OS_OTHER
            if "私" in text:
                return 0  # OS_SELF
            return 2  # OS_BRIDGE
    
        def salience(self, text):
            return min(1.0, len(text) / 100)

    🔗 3. エッジ生成(ここがOSN-GNNの核心)

    import torch
    
    def build_edges(nodes):
        """
        OSNの3種類エッジを構築
        """
    
        edge_index = []
        edge_attr = []
    
        for i, n1 in enumerate(nodes):
            for j, n2 in enumerate(nodes):
    
                if i == j:
                    continue
    
                # ① temporal edge(順序)
                if n2["id"] == n1["id"] + 1:
                    edge_index.append([i, j])
                    edge_attr.append([1.0, 0.0, 0.0])  # structural
    
                # ② semantic edge(簡易)
                elif abs(n1["sent_index"] - n2["sent_index"]) < 3:
                    edge_index.append([i, j])
                    edge_attr.append([0.0, 1.0, 0.0])  # semantic
    
                # ③ narrative jump(章跨ぎ)
                elif n1["chap"] != n2["chap"]:
                    edge_index.append([i, j])
                    edge_attr.append([0.0, 0.0, 1.0])  # narrative
    
        return (
            torch.tensor(edge_index).t().contiguous(),
            torch.tensor(edge_attr, dtype=torch.float)
        )

    🧠 4. ノードベクトル化(簡易BERT代替)

    from sklearn.feature_extraction.text import TfidfVectorizer
    
    def vectorize_nodes(nodes):
        texts = [n["text"] for n in nodes]
    
        vec = TfidfVectorizer(max_features=256)
        x = vec.fit_transform(texts).toarray()
    
        return torch.tensor(x, dtype=torch.float)

    🧱 5. PyGデータ構築(ここがゴール)

    from torch_geometric.data import Data
    
    def build_pyg_graph(nodes):
    
        x = vectorize_nodes(nodes)
        edge_index, edge_attr = build_edges(nodes)
    
        data = Data(
            x=x,
            edge_index=edge_index,
            edge_attr=edge_attr
        )
    
        return data

    📘 6. 「こころ」全文をグラフ化

    def build_kokoro_graph(full_text):
    
        builder = OSNNodeBuilder()
    
        chapters = split_into_chapters(full_text)
    
        all_nodes = []
    
        for chap_id, chap_text in chapters.items():
            sentences = split_into_sentences(chap_text)
    
            for i, sent in enumerate(sentences):
                node = builder.build_node(sent, chap_id, i)
                all_nodes.append(node)
    
        graph = build_pyg_graph(all_nodes)
    
        return graph, all_nodes

    🧠 7. OSN-GNNに接続

    graph, nodes = build_kokoro_graph(kokoro_text)
    
    out = model(graph)

    🔥 8. attention可視化用データ抽出

    def extract_attention_edges(graph_output, nodes):
    
        attention_matrix = torch.matmul(graph_output, graph_output.T)
    
        return attention_matrix

    🌐 9. グラフ可視化(PyVis)

    from pyvis.network import Network
    
    def visualize_graph(nodes, edge_index):
    
        net = Network(height="800px", width="100%")
    
        for n in nodes:
            net.add_node(
                n["id"],
                label=n["text"][:20],
                title=n["text"]
            )
    
        for i in range(edge_index.shape[1]):
            src = int(edge_index[0][i])
            dst = int(edge_index[1][i])
    
            net.add_edge(src, dst)
    
        net.show("kokoro_osn_graph.html")

    🧠 10. この実装の本質

    これは単なるNLPではなく:

    ❌ 文章解析

    ❌ 依存構文解析

    ではなく


    ✅ OSN的意味

    小説=時間方向に展開する「意味ネットワーク」


    🔥 11. このコードがやっていること

    ① 文をノード化

    ② 関係を3種類のエッジに変換

    ③ GNNに投入可能なグラフ生成

    ④ attention可視化可能にする


    🚀 12. 次の進化ルート(重要)

    ここから先は研究領域です:


    🔥 Level 2

    • BERT埋め込み化

    • learned edge generation

    🔥 Level 3

    • narrative attention training

    • reading-path modeling

    🔥 Level 4(論文級)

    • OSN-GNN + RL読解エージェント


    🎯 一言でいうと

    このコードの意味:

    『こころ』を「読書体験」ではなく「グラフ空間」に変換する処理系



    🧠 0. 問題設定(OSN版タスク定義)

    入力

    • 小説『こころ』のOSNグラフ

      • node = 文

      • edge = narrative / semantic / temporal

    出力(今回の目的)

    各ノードに対して:

    y = 1  → 「先生の死に関係する文」
    y = 0  → それ以外

    📌 1. GATモデル(PyTorch Geometric)

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    
    from torch_geometric.nn import GATConv

    🧠 2. OSN-GAT(予測モデル本体)

    class KokoroDeathGAT(nn.Module):
        def __init__(self, in_dim, hidden_dim=64):
            super().__init__()
    
            # 2-layer GAT
            self.gat1 = GATConv(in_dim, hidden_dim, heads=4, concat=True)
            self.gat2 = GATConv(hidden_dim * 4, hidden_dim, heads=1, concat=False)
    
            # OSN prediction head
            self.classifier = nn.Sequential(
                nn.Linear(hidden_dim, hidden_dim),
                nn.ReLU(),
                nn.Linear(hidden_dim, 1)  # binary
            )
    
        def forward(self, x, edge_index):
    
            x = self.gat1(x, edge_index)
            x = F.elu(x)
    
            x = self.gat2(x, edge_index)
            x = F.elu(x)
    
            out = self.classifier(x)
    
            return torch.sigmoid(out).squeeze()

    🧩 3. ラベル生成(“先生の死”OSN定義)

    ここが重要です:

    OSN的ラベル定義

    先生の死 = narrative culmination node cluster

    簡易ラベル付け

    def label_kokoro_nodes(nodes):
    
        labels = []
    
        for n in nodes:
    
            text = n["text"]
    
            # 死関連語彙ベース(初期弱教師)
            if any(k in text for k in [
                "先生", "死んだ", "自殺", "遺書", "奥さん", "K"
            ]):
                labels.append(1)
            else:
                labels.append(0)
    
        return torch.tensor(labels, dtype=torch.float)

    📦 4. 学習データ

    def prepare_training(graph, nodes):
    
        x = graph.x
        edge_index = graph.edge_index
    
        y = label_kokoro_nodes(nodes)
    
        return x, edge_index, y

    🚀 5. 学習ループ(OSN-GAT training)

    model = KokoroDeathGAT(in_dim=graph.x.shape[1])
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    
    x, edge_index, y = prepare_training(graph, nodes)
    
    for epoch in range(200):
    
        model.train()
        optimizer.zero_grad()
    
        out = model(x, edge_index)
    
        loss = F.binary_cross_entropy(out, y)
    
        loss.backward()
        optimizer.step()
    
        if epoch % 20 == 0:
            print(f"epoch {epoch}, loss = {loss.item():.4f}")

    🔥 6. 予測(“先生の死”クラスタ抽出)

    model.eval()
    
    with torch.no_grad():
        pred = model(x, edge_index)
    
    death_nodes = (pred > 0.5).nonzero(as_tuple=True)[0]

    🌐 7. attention可視化(OSNコア)

    def extract_death_attention(model, x, edge_index):
    
        with torch.no_grad():
    
            h1 = model.gat1(x, edge_index)
    
            # attention scoreは内部で保持されていないので近似
            sim = torch.matmul(h1, h1.T)
    
            return torch.softmax(sim, dim=-1)

    📊 8. “死の伝播”スコア(OSN独自指標)

    def compute_death_propagation(pred, edge_index, num_nodes):
    
        score = torch.zeros(num_nodes)
    
        for i in range(edge_index.shape[1]):
    
            src = edge_index[0, i]
            dst = edge_index[1, i]
    
            score[dst] += pred[src]
    
        return score / (score.max() + 1e-8)

    🧠 9. このモデルの意味(重要)

    これは普通の分類器ではありません。


    ❌ 通常NLP

    • 文分類

    • 感情分類


    ✅ OSN-GNN

    「死」という意味構造がグラフ上でどこから発生し、どう拡散するか」


    🔥 10. このモデルがやっていること

    ① 文を「意味粒子」に変換

    ② GATで関係性再構成

    ③ “死”をグラフ上の場として推定

    ④ 伝播として可視化可能


    🧬 11. 拡張(研究レベル)

    ここから論文になります:


    ① Temporal GAT

    → 「遺書に向かう時間構造」

    ② Heterogeneous OSN-GAT

    → narrator / focalizer / OS_role別attention

    ③ Causal OSN-GAT

    → 「先生の死の原因ノード推定」

    ④ Counterfactual OSN

    → 「もしKがいなければ?」


    🎯 12. 最終的な一文

    このモデルの本質はこれです:

    先生の死を“出来事”ではなく“グラフ上の収束現象”として学習する

    focalizer値とnarrator_typeの整合方法は?

    結論から言うと、focalizer と narrator_type は「同じ軸で揃えると破綻する」ので、役割分離+制約付き整合(constraint-based alignment)にするのが正解です。


    🧠 1. まず根本整理:この2つは何が違うか

    narrator_type(語りの発生源)

    → 「誰が語っているか(utterance source)」

    例:

    • 語り手(地の文)

    • 先生の手記

    • 内的独白

    • 作者的介入


    focalizer(知覚の中心)

    → 「誰の視点で世界が見えているか(perception center)」

    例:

    • 私(語り手)

    • 先生

    • K

    • 不特定(神の視点っぽいもの)


    ⚠️ 重要な非対称性

    この2つは必ずズレる:

    ケースnarrator_typefocalizer一人称回想私が語る私が見る三人称心理描写語り手先生が見る自由間接話法語り手先生に寄る作者介入作者不定 or 読者

    👉 一致する方がむしろ例外


    🧩 2. 整合の基本設計(OSN-GNN的定義)

    🎯 核心ルール

    narrator_type = 発話源(source)

    focalizer = 視点重心(attention center)

    🧠 3. 整合方法(3層制約モデル)

    Layer 1:ハード制約(論理不可能な組み合わせ排除)

    narrator_type = CS_DS(発話)
    → focalizer は「発話者 or 観測者」に限定

    例:

    • 先生が「〜と言った」

      • narrator_type = CS_DS

      • focalizer = 先生 or 私(聞き手)


    Layer 2:ソフト制約(確率整合)

    P(focalizer | narrator_type, text)

    つまり:

    「この語り方なら、この視点の可能性が高い」


    例:

    narrator_typefocalizer候補GN_1H私(0.95)GN_3E不定(0.7)CS_FI被語り人物(0.8)


    Layer 3:意味整合(semantic alignment)

    ここがOSN的本体。

    focalizer = argmax similarity(text embedding, character embedding)

    つまり:

    「この文は誰の内面に最も近いか」


    🧠 4. OSN-GNNでの統合モデル

    ✳️ ノード構造

    node = {
        "text": "...",
        "narrator_type": "GN_3E",
        "focalizer": "K"
    }

    ✳️ 整合モジュール(Alignment Layer)

    class OSNAlignment(nn.Module):
    
        def __init__(self, hidden_dim, num_characters):
            super().__init__()
    
            self.focalizer_proj = nn.Linear(hidden_dim, num_characters)
    
            self.narrator_gate = nn.Linear(hidden_dim, 8)  # narrator_type数
    
        def forward(self, h):
    
            # narrator_type distribution
            narrator_logits = self.narrator_gate(h)
    
            # focalizer distribution
            focalizer_logits = self.focalizer_proj(h)
    
            return narrator_logits, focalizer_logits

    🔗 5. 整合損失(ここが重要)

    ① narrator制約損失

    L_narr = cross_entropy(narrator_pred, narrator_gold)

    ② focalizer制約損失

    L_focal = cross_entropy(focalizer_pred, focalizer_gold)

    ③ 整合性損失(OSN独自)

    L_align = KL(
        P(focalizer | narrator_type)
        || learned_joint_distribution
    )

    ④ 最終損失

    L = L_narr + L_focal + λ L_align

    🧠 6. 最重要:OSN的整合原理

    ❌ 間違いアプローチ

    • narrator = focalizer とみなす

    • 1対1対応を仮定する


    ✅ 正しいアプローチ

    narrator = 信号源

    focalizer = 観測フィルタ

    つまり:

    同じ文でも「誰が語るか」と「誰の視点か」は別空間

    🧬 7. グラフ的解釈(超重要)

    2層グラフになる

    Layer A:Narration Graph

    • narrator_typeノード空間

    Layer B:Focalization Graph

    • focalizer中心の意味空間


    接続:

    Narration → (transduction layer) → Focalization

    🔥 8. OSN-GNN的本質

    この設計の核心はこれです:

    語り(narration)と視点(perception)を分離した二重グラフ学習


    🚀 9. さらに進むと論文になる拡張

    ① Disentangled OSN-GNN

    • narrator embedding

    • focalizer embedding


    ② Causal alignment

    • narrator → focalizer cause graph


    ③ Counterfactual focalization

    • 「先生視点だったらどう見えるか」


    ④ Narrative collapse detection

    • narratorとfocalizerが崩壊する地点=文学的クライマックス


    🎯 一言でまとめると

    narrator_type は「声の発生源」

    focalizer は「意識のレンズ」

    そしてOSN-GNNは:

    その2つのズレそのものを構造として学習するモデル

    結論:整合とは「一致」ではなく「写像」である

    あなたの設計をOSN-GNNとして厳密化すると、こうなります:

    narrator_type と focalizer は同一空間の属性ではなく
    異なる表現空間間の写像関係


    🧩 1. 形式化(OSNコンパイラの本体)

    2つの空間

    Narration Space (N-space)
      n ∈ narrator_type
    
    Focalization Space (F-space)
      f ∈ focalizer

    写像としての整合

    Φ : N → F

    ではなく、実際はこう:

    Φ : (text, context) → P(F | N)

    つまり:

    narrator_type が focalizer を決めるのではなく
    文脈付き確率変換でしかない


    🔗 2. あなたの「ルール表」の本質

    あなたの if–then は実はこれに対応しています:

    ルール数理的意味if GN_1H → narrator_Ideterministic priorGN_3E → camera or charactermixture distributionCS_FI → character focalizerhigh entropy collapseconflict = truemultimodal posterior


    🧠 3. OSNコンパイラとしての正しい構造

    ここが重要です。

    ❌ 単純設計

    narrator_type → focalizer(決定)

    ✅ 正しい設計

              ┌────────────────────┐
    text ───▶ │ Narrator Parser     │
              └────────┬───────────┘
                       ↓
              P(N | text, context)
                       ↓
              ┌────────────────────┐
              │ Focalizer Inference │
              └────────┬───────────┘
                       ↓
              P(F | N, text, context)

    🧠 4. OSN的に重要な修正点(かなり本質)

    あなたの設計はすでにかなり完成度が高いですが、1点だけ重要な補正があります:


    ⚠️ focalizerは「一意ではない」

    特に『こころ』では:

    • 先生の遺書=focalizer混在

    • 回想=二重視点

    • 語り=後知識バイアス


    なので正しい定義はこれ:

    focalizer = distribution over attention centers

    つまり:

    「誰が見ているか」ではなく
    「誰の視点重みがどれくらい支配的か」


    🧩 5. OSNコンパイラへの統合設計

    あなたの仕様をGNNに落とすとこうなります:


    🧠 ノード構造

    node = {
        "text": "...",
    
        # narrator space
        "narrator_type": "GN_3E",
    
        # focalizer space(分布)
        "focalizer_dist": {
            "sensei": 0.7,
            "watashi": 0.2,
            "camera": 0.1
        }
    }

    🔗 binding layer(整合層)

    class NarrationFocalizationAligner(nn.Module):
    
        def forward(self, text_embedding):
    
            narrator_logits = self.narrator_head(text_embedding)
            focalizer_logits = self.focalizer_head(text_embedding)
    
            # coupling constraint
            joint = self.coupling_matrix(narrator_logits, focalizer_logits)
    
            return narrator_logits, focalizer_logits, joint

    ⚙️ 6. conflict の正しい意味

    あなたの:

    focalizer_conflict = true

    これは実は重要で、OSN的にはこう定義すべきです:


    🧠 conflict = 視点相転移点

    entropy(focalizer_dist) > threshold

    つまり:

    1つの視点では説明できない状態


    🧠 7. OSN的に一番重要な発見

    あなたの設計の本質はこれです:


    🔥 narrator_type は「生成過程」

    🔥 focalizer は「観測過程」


    この2つを分離すると何が起きるか:

    文学=生成モデル + 観測モデルの干渉現象になる


    🧬 8. GNNとしての最終形

    Node embedding
       ↓
    Narration encoder (what is said)
       ↓
    Focalization decoder (how it is seen)
       ↓
    alignment loss (consistency constraint)

    🎯 9. まとめ(最重要)

    あなたの設計を1行で厳密化すると:


    narrator_type と focalizer の整合とは
    決定ルールではなく確率的写像+制約付き分布整合問題である



     
     
    岩波書店の『定本漱石全集』に子規と青々の句が混入していると指摘している人です。近著『全ての漱石論者の絶望のために』スキとかフォローとかコメントはどうでもいいので、試食して美味しかったらまずちゃんと記事か本を買いましょう。礼儀知らずな人は近寄ってこないで。

    あなたへのおすすめ