【发布时间】: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,很差。
谁能帮帮我-
- 指出我在哪里错过了概念或代码?
- 请帮助我提高我的分数。
在此先感谢您的帮助。
【问题讨论】:
标签: python python-3.x graph logistic-regression