node2vec

eliorcMIT长期未更新

用 Python 实现 node2vec 图嵌入算法,把网络中的节点映射成低维向量,方便下游做节点分类、链接预测等图学习任务。

Implementation of the node2vec algorithm.

v0.5.0发布于 2024-08-02 11:13 UTC1,304star248fork同步于 2026-11-07 07:31 UTC

怎么上手

由 README 提炼,执行前请确认
pip install node2vec
硬件要求按 README 说明

README 未说明,未提及 GPU 或显存要求;纯 CPU 运行,多进程并行在 Windows 上不可用,需设 workers=1

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

用 Python 实现的 node2vec 图节点嵌入工具,基于 gensim 训练,可快速得到节点和边的向量表示

用 Python 实现 node2vec 图嵌入算法,把网络中的节点映射成低维向量,方便下游做节点分类、链接预测等图学习任务。

核心能力

  • 基于 networkx 图生成随机游走并用 gensim Word2Vec 训练
  • 支持 p、q 参数控制游走偏向,可设置采样策略
  • 内置 Hadamard、Average、WeightedL1/L2 四种边嵌入
  • 支持多进程并行生成游走,可用 temp_folder 处理大图
  • 可保存词向量格式嵌入和完整模型供后续复用

容易踩的坑

输入图节点名必须全为字符串或全为整数,输出模型里统一为字符串;Windows 上并行游走因 joblib 问题不可用,必须传 workers=1;大图需通过 temp_folder 指定共享内存目录,否则可能内存不足

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.5.0
  1. v0.5.0最新正式版2024-08-02 · 2024-08-02 11:13 UTC

    Fixes issues with dependencies, keeps minimum python version at 3.8.

    Thanks to @Crosswind

  2. v0.4.6Fix Multigraph Bug2022-08-01 · 2022-08-01 11:34 UTC
    查看更新说明

    Bug fixes

    • Fixes #91 , where weights would be None. Now default to 1
  3. v0.4.52022-04-30 · 2022-04-30 05:55 UTC
    查看更新说明

    Bug Fixes

    • Bug fixed with weight initialization, #88 thanks to @ndrus-softserve
  4. v0.4.4Poetry and faster random walks2021-10-09 · 2021-10-09 06:10 UTC
    查看更新说明
    • Switch to Poetry for package management
    • Faster random walk generation by @Neronuser
  5. v0.4.3Gensim > 4.0.0 support for edges2021-04-16 · 2021-04-16 07:45 UTC
    查看更新说明

    Edge embedding support for gensim 4.0.0

    Resolved #63

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Node2Vec

    Downloads

    Python3 implementation of the node2vec algorithm Aditya Grover, Jure Leskovec and Vid Kocijan. node2vec: Scalable Feature Learning for Networks. A. Grover, J. Leskovec. ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (KDD), 2016.

    Maintenance

    I no longer have time to maintain this, if someone wants to pick the baton let me know

    Installation

    pip install node2vec

    Usage

    import networkx as nx
    from node2vec import Node2Vec
    
    # Create a graph
    graph = nx.fast_gnp_random_graph(n=100, p=0.5)
    
    # Precompute probabilities and generate walks - **ON WINDOWS ONLY WORKS WITH workers=1**
    node2vec = Node2Vec(graph, dimensions=64, walk_length=30, num_walks=200, workers=4)  # Use temp_folder for big graphs
    
    # Embed nodes
    model = node2vec.fit(window=10, min_count=1, batch_words=4)  # Any keywords acceptable by gensim.Word2Vec can be passed, `dimensions` and `workers` are automatically passed (from the Node2Vec constructor)
    
    # Look for most similar nodes
    model.wv.most_similar('2')  # Output node names are always strings
    
    # Save embeddings for later use
    model.wv.save_word2vec_format(EMBEDDING_FILENAME)
    
    # Save model for later use
    model.save(EMBEDDING_MODEL_FILENAME)
    
    # Embed edges using Hadamard method
    from node2vec.edges import HadamardEmbedder
    
    edges_embs = HadamardEmbedder(keyed_vectors=model.wv)
    
    # Look for embeddings on the fly - here we pass normal tuples
    edges_embs[('1', '2')]
    ''' OUTPUT
    array([ 5.75068220e-03, -1.10937878e-02,  3.76693785e-01,  2.69105062e-02,
           ... ... ....
           ..................................................................],
          dtype=float32)
    '''
    
    # Get all edges in a separate KeyedVectors instance - use with caution could be huge for big networks
    edges_kv = edges_embs.as_keyed_vectors()
    
    # Look for most similar edges - this time tuples must be sorted and as str
    edges_kv.most_similar(str(('1', '2')))
    
    # Save embeddings for later use
    edges_kv.save_word2vec_format(EDGES_EMBEDDING_FILENAME)
    
    

    Parameters

    node2vec.Node2vec
    • Node2Vec constructor:

      1. graph: The first positional argument has to be a networkx graph. Node names must be all integers or all strings. On the output model they will always be strings.
      2. dimensions: Embedding dimensions (default: 128)
      3. walk_length: Number of nodes in each walk (default: 80)
      4. num_walks: Number of walks per node (default: 10)
      5. p: Return hyper parameter (default: 1)
      6. q: Input parameter (default: 1)
      7. weight_key: On weighted graphs, this is the key for the weight attribute (default: 'weight')
      8. workers: Number of workers for parallel execution (default: 1)
      9. sampling_strategy: Node specific sampling strategies, supports setting node specific 'q', 'p', 'num_walks' and 'walk_length'. Use these keys exactly. If not set, will use the global ones which were passed on the object initialization`
      10. quiet: Boolean controlling the verbosity. (default: False)
      11. temp_folder: String path pointing to folder to save a shared memory copy of the graph - Supply when working on graphs that are too big to fit in memory during algorithm execution.
      12. seed: Seed for the random number generator (default: None). Deterministic results can be obtained if seed is set and workers=1.
    • Node2Vec.fit method: Accepts any key word argument acceptable by gensim.Word2Vec

    node2vec.EdgeEmbedder

    EdgeEmbedder is an abstract class which all the concrete edge embeddings class inherit from. The classes are AverageEmbedder, HadamardEmbedder, WeightedL1Embedder and WeightedL2Embedder which their practical definition could be found in the paper on table 1 Notice that edge embeddings are defined for any pair of nodes, connected or not and even node with itself.

    • Constructor:

      1. keyed_vectors: A gensim.models.KeyedVectors instance containing the node embeddings
      2. quiet: Boolean controlling the verbosity. (default: False)
    • EdgeEmbedder.__getitem__(item) method, better known as EdgeEmbedder[item]:

      1. item - A tuple consisting of 2 nodes from the keyed_vectors passed in the constructor. Will return the embedding of the edge.
    • EdgeEmbedder.as_keyed_vectors method: Returns a gensim.models.KeyedVectors instance with all possible node pairs in a sorted manner as string. For example, for nodes ['1', '2', '3'] we will have as keys "('1', '1')", "('1', '2')", "('1', '3')", "('2', '2')", "('2', '3')" and "('3', '3')".

    Caveats

    • Node names in the input graph must be all strings, or all ints
    • Parallel execution not working on Windows (joblib known issue). To run non-parallel on Windows pass workers=1 on the Node2Vec's constructor

    TODO

    • Parallel implementation for walk generation
    • Parallel implementation for probability precomputation