토큰

2017-10-04 1 views
1

의 배열에 가장 적합한 문장을 찾아 나는이 텍스트 마이닝에 대해 다음 DataFrame : 토큰의토큰

df = pd.DataFrame({'text':["Anyone who reads Old and Middle English literary texts will be familiar with the mid-brown volumes of the EETS, with the symbol of Alfreds jewel embossed on the front cover", 
        "Most of the works attributed to King Alfred or to Aelfric, along with some of those by bishop Wulfstan and much anonymous prose and verse from the pre-Conquest period, are to be found within the Society's three series", 
        "all of the surviving medieval drama, most of the Middle English romances, much religious and secular prose and verse including the English works of John Gower, Thomas Hoccleve and most of Caxton's prints all find their place in the publications", 
        "Without EETS editions, study of medieval English texts would hardly be possible."]}) 



text 
0 Anyone who reads Old and Middle English litera... 
1 Most of the works attributed to King Alfred or... 
2 all of the surviving medieval drama, most of t... 
3 Without EETS editions, study of medieval Engli... 

그리고 내가 가지고있는 목록 :

tokens = [['middl engl', 'mid-brown', 'symbol'], ["king", 'anonym', 'series'], ['mediev', 'romance', 'relig'], ['hocclev', 'edit', 'publ']] 

내가 가장을 찾기 위해 노력하고있어 위의 토큰 목록의 토큰 배열에 적합한 문장.

업데이트 : 자세한 내용은 내 문제를 설명하도록 요청 받았습니다.

문제는 내가 영어가 아닌 텍스트를 사용하고 있기 때문에 문제를 좀 더 설명하기가 어렵다는 것입니다.

나는 df.text에 문장을 내 토큰의 입력으로 목록을 각 요소를 가져 및 토큰 목록의 각 요소에 대해, 그것은 (어쩌면 일부 메트릭 의미에서) 가장 적합한 검색 일부 기능 X를 찾고 있어요. 이것은 출력이 중요하지 않다는 주요 아이디어입니다. 난 그냥 일하고 싶어요 :)

+1

또한 문제에 대해 좀 더 설명하고 예상되는 출력을 추가 할 수 있습니까? –

+0

문장과 토큰 목록 간의 유사성을 계산하고 토큰 목록의 가장 비슷한 문장을 출력 문장으로 선택합니다. 또는 문장에서 각 토큰 목록의 토큰 발생을 계산하는 간단한 방법은 토큰 목록 출력으로 최대 토큰 발생 문장을 선택하는 것입니다. – mutux

답변

0

내가 전에 말했듯이,이 게시물은 단지 내 문제의 실례입니다. 나는 클러스터링 문제를 해결하고 있었다. LDA와 K-means 알고리즘을 사용했습니다. 내 토큰 목록에 적합한 문장을 찾으려면 K- 평균 매개 변수을 사용했습니다.

import pandas as pd 
from sklearn.feature_extraction.text import TfidfVectorizer 
import lda 
from sklearn.feature_extraction.text import CountVectorizer 
import logging 
from sklearn.cluster import MiniBatchKMeans 
from sklearn import preprocessing 

df = pd.DataFrame({'text':["Anyone who reads Old and Middle English literary texts will be familiar with the mid-brown volumes of the EETS, with the symbol of Alfreds jewel embossed on the front cover", 
         "Most of the works attributed to King Alfred or to Aelfric, along with some of those by bishop Wulfstan and much anonymous prose and verse from the pre-Conquest period, are to be found within the Society's three series", 
         "all of the surviving medieval drama, most of the Middle English romances, much religious and secular prose and verse including the English works of John Gower, Thomas Hoccleve and most of Caxton's prints all find their place in the publications", 
         "Without EETS editions, study of medieval English texts would hardly be possible."], 
        'tokens':[['middl engl', 'mid-brown', 'symbol'], ["king", 'anonym', 'series'], ['mediev', 'romance', 'relig'], ['hocclev', 'edit', 'publ']]}) 
df['tokens'] = df.tokens.str.join(',') 


vectorizer = TfidfVectorizer(min_df=1, max_features=10000, ngram_range=(1, 2)) 
vz = vectorizer.fit_transform(df['tokens']) 

logging.getLogger("lda").setLevel(logging.WARNING) 
cvectorizer = CountVectorizer(min_df=1, max_features=10000, ngram_range=(1,2)) 
cvz = cvectorizer.fit_transform(df['tokens']) 

n_topics = 4 

n_iter = 2000 
lda_model = lda.LDA(n_topics=n_topics, n_iter=n_iter) 
X_topics = lda_model.fit_transform(cvz) 

num_clusters = 4 
kmeans_model = MiniBatchKMeans(n_clusters=num_clusters, init='k-means++', n_init=1, 
         init_size=1000, batch_size=1000, verbose=False, max_iter=1000) 
kmeans = kmeans_model.fit(vz) 
kmeans_clusters = kmeans.predict(vz) 
kmeans_distances = kmeans.transform(vz) 

X_all = X_topics 
kmeans1 = kmeans_model.fit(X_all) 
kmeans_clusters1 = kmeans1.predict(X_all) 
kmeans_distances1 = kmeans1.transform(X_all) 
d = dict() 
l = 1 


for i, desc in enumerate(df.text): 
    if(i < 3): 
     num = 3 
     if kmeans_clusters1[i] == num: 
      if l > kmeans_distances1[i][kmeans_clusters1[i]]: 
       l = kmeans_distances1[i][kmeans_clusters1[i]] 
      d['Cluster' + str(kmeans_clusters1[i])] = "distance: " + str(l)+ " "+ df.iloc[i]['text'] 
      print("Cluster " + str(kmeans_clusters1[i]) + ": " + desc + 
        "(distance: " + str(kmeans_distances1[i][kmeans_clusters1[i]]) + ")") 
      print('---') 
print("Cluster " + str(num) + " " + str(d.get('Cluster' + str(num)))) 

특정 클러스터 내에서 가장 거리가 먼 토큰이 가장 적합합니다.