![](/img/trans.png)
[英]Understanding the `ngram_range` argument in a CountVectorizer in sklearn
[英]Retain original document element index of argument passed through sklearn's CountVectorizer() in order to access corresponding part of speech tag
我有一個帶有句子的數據框和每個單詞的相應詞性標記(下面是我正在使用的數據的摘錄(數據來自SNLI語料庫)。對於我收藏的每個句子,我想提取 unigrams以及該詞的相應后置標簽。
例如,如果我有以下內容:
vectorizer_unigram = CountVectorizer(analyzer='word', ngram_range=(1, 1), stop_words = 'english')
doc = {'sent' : ['Two women are embracing while holding to go packages .'], 'tags' : ['NUM NOUN AUX VERB SCONJ VERB PART VERB NOUN PUNCT']}
sentence = vectorizer_unigram.fit(doc['sent'])
sentence_unigrams = sentence.get_feature_names_out()
然后我會得到以下 unigrams output:
array(['embracing', 'holding', 'packages', 'women'], dtype=object)
但我不知道如何在這之后保留詞性標簽。 我嘗試用 unigrams 做一個查找版本,但因為它們可能與句子中的單詞不同(例如,如果你做sentence.split(' ')
)你不一定得到相同的標記。 關於如何提取 unigrams 並保留相應詞性標記的任何建議?
在查看了sklearn
CountVectorizer class的源代碼,特別是fit function 之后,我不相信 class 有任何方法可以跟蹤原始文檔元素索引相對於提取的一元特征:其中一元特征不一定具有相同的令牌。 除了下面提供的簡單解決方案外,您可能還必須依賴其他一些方法/庫才能獲得所需的結果。 如果有一個特定的案例失敗了,我建議將其添加到您的問題中,因為它可能會幫助人們為您的問題找到解決方案。
from sklearn.feature_extraction.text import CountVectorizer
vectorizer_unigram = CountVectorizer(analyzer='word', ngram_range=(1, 1), stop_words = 'english')
doc = {'sent': ['Two women are embracing while holding to go packages .'],
'tags': ['NUM NOUN AUX VERB SCONJ VERB PART VERB NOUN PUNCT']}
sentence = vectorizer_unigram.fit(doc['sent'])
sentence_unigrams = sentence.get_feature_names_out()
sent_token_list = doc['sent'][0].split()
tags_token_list = doc['tags'][0].split()
sentence_tags = []
for unigram in sentence_unigrams:
for i in range(len(sent_token_list)):
if sent_token_list[i] == unigram:
sentence_tags.append(tags_token_list[i])
print(sentence_unigrams)
# Output: ['embracing' 'holding' 'packages' 'women']
print(sentence_tags)
# Output: ['VERB', 'VERB', 'NOUN', 'NOUN']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.