我计算了窗口大小 =2 的共现矩阵
首先编写一个函数,给出正确的邻域词(这里我使用了获取上下文)
创建矩阵,如果邻域中存在特定值,则只需加 1。
这是python代码:
import numpy as np
CORPUS=["abc def ijk pqr", "pqr klm opq", "lmn pqr xyz abc def pqr abc"]
top2000 = [ "abc","pqr","def"]#list(set((' '.join(ctxs)).split(' ')))
a = np.zeros((3,3), np.int32)
for sentence in CORPUS:
for index,word in enumerate(sentence.split(' ')):
if word in top2000 :
print(word)
context=GetContext(sentence,index)
print(context)
for word2 in context:
if word2 in top2000:
a[top2000.index(word)][top2000.index(word2)]+=1
print(a)
获取上下文函数
def GetContext(sentence, index):
words = sentence.split(' ')
ret=[]
for word in words:
if index==0:
ret.append(words[index+1])
ret.append(words[index+2])
elif index==1:
ret.append(words[index-1])
ret.append(words[index+1])
if len(words)>3:
ret.append(words[index+2])
elif index==(len(words)-1):
ret.append(words[index-2])
ret.append(words[index-1])
elif index==(len(words)-2):
ret.append(words[index-2])
ret.append(words[index-1])
ret.append(words[index+1])
else:
ret.append(words[index-2])
ret.append(words[index-1])
ret.append(words[index+1])
ret.append(words[index+2])
return ret
结果如下:
array([[0, 3, 3],
[3, 0, 2],
[3, 2, 0]])