闭着眼睛复现Metapath2vec(Stellargraph)

from stellargraph import datasets
from stellargraph import IndexedArray
from stellargraph import StellarGraph
import pandas as pd
################################################################################
#命名可以没有顺序
author = IndexedArray(index=["a1","a2","a3","a4"])
paper = IndexedArray(index=["p1", "p2", "p3"])
venue = IndexedArray(index=["v1", "v2", "v3"])

edges_AP = pd.DataFrame(
    {"source": ["a1","a2","a3","a4"], "target": ["p1", "p2", "p3", "p3"]},index=[0,1,2,3]
)
edges_PV = pd.DataFrame(
    {"source": ["p1", "p2", "p3"], "target": ["v1", "v2", "v3"]},index=[4,5,6]
)
#index的用处是为每一条边给一个唯一id

Graph = StellarGraph(nodes={"author": author, "paper": paper,"venue": venue},
                     edges={"AP":edges_AP, "PV":edges_PV})
print(Graph.info())


################################################################################
#随机游走
walk_length = 100  # maximum length of a random walk to use throughout this notebook

# specify the metapath schemas as a list of lists of node types.
metapaths = [
    ["author", "paper", "author"],
    ["author", "paper", "paper", "author"],
    ["author", "paper", "venue","paper", "author"],
]

from stellargraph.data import UniformRandomMetaPathWalk

# Create the random walker
rw = UniformRandomMetaPathWalk(Graph)

walks = rw.run(
    nodes=list(Graph.nodes()),  # root nodes
    length=walk_length,  # maximum length of a random walk
    n=1,  # number of random walks per root node
    metapaths=metapaths,  # the metapaths
)

print("Number of random walks: {}".format(len(walks)))

################################################################################
#Word2Vec
from gensim.models import Word2Vec
model = Word2Vec(walks, vector_size=64, window=5, min_count=0, sg=1, workers=2, epochs=100)
model.save('word2vec.model')
#model = Word2Vec.load('word2vec.model')
################################################################################
vectors = model.wv.vectors #获取模型中全部的节点向量
words = model.wv.index_to_key #获取模型中全部的节点类型
vecs=model.wv['a1'] #取出一个节点的向量

附:安装stellargraph

pip install stellargraph

其他的包不用安装,stellargraph里面带了。

另外可能会出现 no module xxx(忘记叫啥了)。pip install xxx就行。

你可能感兴趣的:(metapath2vec,stellargraph,异质网络)