단어 벡터를 문장 벡터로 바꾸는 텍스트 유사도 계산
6226 단어 자연 언어 처리
# coding: utf-8
# In[2]:
###
from gensim.models import word2vec
w2v=word2vec.Word2Vec.load('d:/chat_data/corpus_vector.model')
##
import jieba
import re
raw_data = []
w = open('******','r',encoding= 'utf-8')
for line in w.readlines():
newline = line.strip()
newline = re.sub(' ','',newline)
newline = jieba.cut(newline)
raw_data.append(list(newline))
w.close()
import numpy as np
# In[72]:
###
def sent2vec(s):
words = s
M = []
for w in words:
try:
M.append(w2v.wv[w])
except:
continue
M = np.array(M)
v = M.sum(axis=0)
return v / np.sqrt((v ** 2).sum())
newdata = []
newdata_dict = {}
seed = 0
for word in raw_data:
try:
newline = sent2vec(word)
if len(newline)<300:
continue
newdata.append(newline)
times += 1
newdata_dict[tuple(newline)] = ''.join(word)
except:
continue
####
ws = open('******','r',encoding='gbk')
times = 0
import re
import jieba
standard_data = []
from zhon.hanzi import punctuation
for i in ws.readlines():
times += 1
if times == 1:
continue
newline = i.strip().split(',')
newline = re.sub("[A-Za-z0-9\[\`\~\!\@\#\$\^\&\*\(\)\=\|\{\}\'\:\;\'\,\[\]\.\\/\?\~\!\@\#\\\&\*\%\-\_]", "", newline[0])
newline = re.sub(' ','',newline)
newline = re.sub("[%s]+" %punctuation, "", newline)
standard_data.append(list(jieba.cut(newline)))
ws.close()
standard_newdata = []
new_standard_dict = {}
for word in standard_data:
try:
newline = sent2vec(word)
if len(newline)<300:
continue
standard_newdata.append(newline)
new_standard_dict[tuple(newline)] = ''.join(word)
except:
continue
# In[45]:
from gensim import corpora, models, similarities
# In[114]:
####
import math
def cos_dist(a, b):
if len(a) != len(b):
return None
part_up = 0.0
a_sq = 0.0
b_sq = 0.0
for a1, b1 in zip(a,b):
part_up += a1*b1
a_sq += a1**2
b_sq += b1**2
part_down = math.sqrt(a_sq*b_sq)
if part_down == 0.0:
return None
else:
return part_up / part_down
# In[ ]:
####
result_data = {}
for i in standard_newdata:
for j in newdata:
result_data[new_standard_dict[tuple(i)]+'\t'+newdata_dict[tuple(j)]] = cos_dist(i,j)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
NLP4J - Java로 형태소 해석 (Yahoo! 개발자 네트워크 일본어 형태소 해석을 이용)Yahoo! Japan이 제공하고 있는 일본어 형태소 해석 API입니다. 텍스트 분석 : 일본어 형태소 분석 - Yahoo! 개발자 네트워크 품목 설명 제공자 야후 주식회사 Yahoo Japan Corporation...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.