You need to enable JavaScript to run this app. 如何按PyTorch Geometric方式将节点索引还原为原始名称并重排DataFrame
优惠活动
大模型
产品
解决方案
定价
更多

如何按PyTorch Geometric方式将节点索引还原为原始名称并重排DataFrame

把节点索引映射回原始名称的实现方法

核心思路

你已经有了node_indices(节点名称→索引的映射字典),只需要生成反向映射字典,就能把DataFrame里的索引值还原成原始节点名称,后续也能轻松对应到节点嵌入。

具体实现步骤

  1. 创建索引到节点名称的反向字典
    直接反转现有node_indices的键值对即可:
index_to_node = {idx: node for node, idx in node_indices.items()}
  1. 还原DataFrame的Source和Target列
    用这个反向字典对已转为索引的列做映射,就能得到原始名称:
# 新增列存储原始名称(也可以直接覆盖原列)
df['Source_Original'] = df['Source'].map(index_to_node)
df['Target_Original'] = df['Target'].map(index_to_node)
  1. 结合PyTorch Geometric提取节点嵌入
    当你用PyG训练完模型得到节点嵌入(比如model(data.x)输出的张量),可以通过反向字典把每个索引对应的嵌入和原始节点名称关联:
import torch
from torch_geometric.data import Data

# 构建PyG的Data对象(基于你的索引化边数据)
edge_index = torch.tensor(df[['Source', 'Target']].values.T, dtype=torch.long)
data = Data(edge_index=edge_index)

# 假设模型输出了节点嵌入 embeddings(形状: [节点总数, 嵌入维度])
embeddings = model(data.x)

# 把嵌入和节点名称一一对应
node_embeddings = {
    node: embeddings[idx].detach().numpy() 
    for node, idx in node_indices.items()
}

这样你就能通过原始节点名称直接取出对应的嵌入向量了。

完整示例代码

把上述步骤整合到你的现有代码里:

import pandas as pd

data = {'Source': ['Rainfall', 'SP2', 'SP2', 'Inflow','Rainfall','Inflow', 'Inflow', 'Inflow','SWT','SP1','SP1','SWD'],
       'Target': ['SP1', 'Evp', 'Outflow', 'SP2','SWD','SWD', 'SP2','SP1','SP1','SP2','Evp','Loss']}  
df = pd.DataFrame(data)

# 生成节点到索引的映射(你的原有代码)
nodes = pd.concat([df['Source'], df['Target']]).unique()
node_indices = {node: i for i, node in enumerate(nodes)}
df['Source'] = df['Source'].map(node_indices)
df['Target'] = df['Target'].map(node_indices)

# 反向映射还原原始名称
index_to_node = {idx: node for node, idx in node_indices.items()}
df['Source_Original'] = df['Source'].map(index_to_node)
df['Target_Original'] = df['Target'].map(index_to_node)

# 查看结果
print(df[['Source', 'Source_Original', 'Target', 'Target_Original']])

内容的提问来源于stack exchange,提问作者Ponlok Peter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 10:22:25