【问题标题】:How to apply node2vec for building link prediction model如何应用 node2vec 构建链路预测模型
【发布时间】:2020-08-14 07:55:48
【问题描述】:

我一直在努力学习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. 请帮助我提高我的分数。

在此先感谢您的帮助。

【问题讨论】:

    标签: python python-3.x graph logistic-regression


    【解决方案1】:

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

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

    下一步是从给定的图形中隐藏一些边。这是准备训练数据集所必需的。随着社交网络的发展,引入了新的边缘。机器学习模型需要知道进化的图。带有隐藏边的图是图Gt,我们当前的数据集是图Gt+n

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

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

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

    您可以在节点中添加更多度量值作为值,以便模型可以根据您的需要预测特征。例如 adam/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 中的某些数组为空而出现索引不足错误。

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

    您还需要更大的数据集,以便正确训练模型。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2014-01-08
      相关资源
      最近更新 更多