如何应用node2vec建立链路预测模型

2024-06-16 10:50:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力学习python编程,并试图实现一个链接预测项目

我有一个包含元组对的列表,如:

ten_author_pairs = [('creutzig', 'gao'), ('creutzig', 'linshaw'), ('gao', 'linshaw'), ('jing', 'zhang'), ('jing', 'liu'), ('zhang', 'liu'), ('jing', 'xu'), ('briant', 'einav'), ('chen', 'gao'), ('chen', 'jing'), ('chen', 'tan')]

我能够使用以下代码生成未连接的对,即原始列表中不存在的对:

#generating negative examples - 

from itertools import combinations

elements = list(set([e for l in ten_author_pairs for e in l])) # find all unique elements

complete_list = list(combinations(elements, 2)) # generate all possible combinations

#convert to sets to negate the order

set1 = [set(l) for l in ten_author_pairs]
complete_set = [set(l) for l in complete_list]

# find sets in `complete_set` but not in `set1`
ten_unconnnected = [list(l) for l in complete_set if l not in set1]

print(len(ten_author_pairs))
print(len(ten_unconnnected))

这导致我有一个非常不平衡的数据集——这可能是现实生活数据集的预期情况

接下来,为了应用node2vec,首先,我将这两个列表转换为数据帧-

df = pd.DataFrame(ten_author_pairs, columns = ['u1','u2'])
df_negative = pd.DataFrame(ten_unconnected, columns = ['u1','u2'])
df['link'] = 1 #for connected pairs
df_negative['link'] = 0 #for unconnected pairs

df_new = pd.concat([df,df_negative])

然后,我绘制图并应用node2vec,如下所示:

# build graph
G_data = nx.from_pandas_edgelist(df_new, "u1", "u2", create_using=nx.Graph())

#!pip install node2vec
from node2vec import Node2Vec

# Generate walks
node2vec = Node2Vec(G_data, dimensions=100, walk_length=16, num_walks=50)

# train node2vec model
n2w_model = node2vec.fit(window=7, min_count=1)

最后,我使用逻辑回归进行链接预测,如下所示:

x = [(n2w_model[str(i)]+n2w_model[str(j)]) for i,j in zip(df_new['u1'], df_new['u2'])]

from sklearn.model_selection import train_test_split

xtrain, xtest, ytrain, ytest = train_test_split(np.array(x), df_new['link'], 
                                            test_size = 0.3, 
                                            random_state = 35)

from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(class_weight="balanced")

lr.fit(xtrain, ytrain)
predictions = lr.predict_proba(xtest)
from sklearn.metrics import roc_auc_score
roc_auc_score(ytest, predictions[:,1])

我得到的分数是0.36,很差

谁能帮帮我-

  1. 指出我在概念或代码上遗漏了什么
  2. 请帮助我提高分数

我真的提前感谢你的帮助


Tags: infromimportdfnewformodellist
1条回答
网友
1楼 · 发布于 2024-06-16 10:50:18

您的目标是预测两个未连接的节点之间是否存在链接

首先,提取它们之间没有链接的节点对

下一步是隐藏给定图形的一些边。这是准备训练数据集所必需的。随着社交网络的发展,新的优势被引入。机器学习模型需要知道图的演化。具有隐藏边的图是在时间t的图G,我们当前的数据集是在时间t+n的图G

删除链接或边时,应避免删除可能产生未连接节点或网络的任何边。下一步是为所有未连接的节点对(包括隐藏的节点对)创建特征

移除的边将标记为1(正样本),未连接的节点对将标记为0(负样本)

标记后,使用node2vec算法从图形中提取节点特征。要计算边的特征,可以将该对节点的特征相加。这些特征将通过逻辑回归模型进行训练

可以在节点中添加更多度量值作为值,以便模型可以根据需要预测特征。例如adamic/adar索引、公共邻居等

因为你已经在训练和测试样本中分割了你的图形,你必须找到哪些边具有模型预测的概率

predictions = lr.predict_proba(xtest)

for i in range(len(df)):
    try:
        index_in_x_train = np.where(xtrain == x[i])[0][1]
        predict_proba = lr.predict_proba(xtrain[index_in_x_train].reshape(1, -1))[:, 1]
        print(
            f'Probability of nodes {df.iloc[i, 0]} and {df.iloc[i, 1]} to form a link is : {float(predict_proba) * 100 : .2f}%')
    except:
        continue

try-catch用于确保不会出现索引外错误,因为xtrain中的某些数组将为空

分数较低可能是由于隐藏边的方式造成的。尝试使用不同的参数和测试大小调整逻辑回归

此外,您还需要一个更大的数据集,以便能够正确地训练模型

您还可以尝试不同的机器学习模型,例如随机森林分类器或多层感知器

相关问题 更多 >