运用DeepWalk对图进行嵌入并做链路预测,链路预测的结果用precision@5评价。给出python代码。
时间: 2024-03-23 13:38:23 浏览: 85
以下是使用DeepWalk进行图嵌入和链路预测,并使用precision@5评价的Python代码:
```python
import networkx as nx
from deepwalk import DeepWalk
from sklearn.metrics import precision_score
# 构建图
G = nx.Graph()
G.add_edges_from([(0, 1), (0, 2), (1, 3), (2, 3), (2, 4), (3, 4), (3, 5)])
# 运行DeepWalk并得到嵌入
model = DeepWalk(G, walk_length=10, num_walks=80, workers=1)
model.train(window_size=5, iter=3)
embeddings = model.get_embeddings()
# 链路预测
test_edges = [(0, 4), (1, 4), (2, 5), (3, 0), (4, 5)]
y_true = [1, 0, 1, 0, 0] # 1表示存在边,0表示不存在边
y_pred = []
for edge in test_edges:
u, v = edge
if u in embeddings and v in embeddings:
score = embeddings[u] @ embeddings[v] # 内积作为得分
y_pred.append(score)
y_pred_sorted = [test_edges[i] for i in sorted(range(len(y_pred)), key=lambda k: y_pred[k], reverse=True)]
precision = precision_score(y_true, [int(edge in y_pred_sorted[:5]) for edge in test_edges], average='binary')
print('Precision@5:', precision)
```
在这个例子中,我们使用了一个相同的图,但是我们选择了5条边进行链路预测。我们计算了每条边的得分,并将它们按得分从高到低排序。然后,我们使用precision@5计算了预测结果的精度。
阅读全文