記事のディレクトリ
テキストの類似性と分類
- テキストの尺度との間の類似性
- これは、テキスト機能を使用して用語頻度を表し、
- 頻度や単語がテキストで表示された回数
- NLTK実現単語頻度統計
テキストの類似ケース:
import nltk
from nltk import FreqDist
text1 = 'I like the movie so much '
text2 = 'That is a good movie '
text3 = 'This is a great one '
text4 = 'That is a really bad movie '
text5 = 'This is a terrible movie'
text = text1 + text2 + text3 + text4 + text5
words = nltk.word_tokenize(text)
freq_dist = FreqDist(words)
print(freq_dist['is'])
# 输出结果:
# 4
# 取出常用的n=5个单词
n = 5
# 构造“常用单词列表”
most_common_words = freq_dist.most_common(n)
print(most_common_words)
# 输出结果:
# [('a', 4), ('movie', 4), ('is', 4), ('This', 2), ('That', 2)]
def lookup_pos(most_common_words):
"""
查找常用单词的位置
"""
result = {}
pos = 0
for word in most_common_words:
result[word[0]] = pos
pos += 1
return result
# 记录位置
std_pos_dict = lookup_pos(most_common_words)
print(std_pos_dict)
# 输出结果:
# {'movie': 0, 'is': 1, 'a': 2, 'That': 3, 'This': 4}
# 新文本
new_text = 'That one is a good movie. This is so good!'
# 初始化向量
freq_vec = [0] * n
# 分词
new_words = nltk.word_tokenize(new_text)
# 在“常用单词列表”上计算词频
for new_word in new_words:
if new_word in list(std_pos_dict.keys()):
freq_vec[std_pos_dict[new_word]] += 1
print(freq_vec)
# 输出结果:
# [1, 2, 1, 1, 1]
テキスト分類
TF-IDF(用語頻度 - 逆文書頻度)
- TF、用語頻度(単語頻度)は、単語がファイルに表示された回数を表します
- IDF、逆文書頻度(逆文書頻度)は、一般に単語の重要性を測定するために使用されます。
TF-IDF = TF * IDF
[画像のダンプはチェーンが失敗し、発信局は、直接アップロード(IMG-iTeE7TKD-1579959553196)(... /画像/ TF.png)ダウン画像を保存することが推奨され、セキュリティチェーン機構を有していてもよいです]
[画像のダンプはチェーンが失敗し、発信局は、直接アップロード(IMG-b3gOQecn-1579959553197)(... /画像/ IDF.png)ダウン画像を保存することが推奨され、セキュリティチェーン機構を有していてもよいです]
- 例の仮定:
回数は、言葉は3、その後、TF = 3/100 = 0.03のために猫100個の単語を含むドキュメントに表示されます。
10,000,000ドキュメントの総サンプル、前記出現文書数1000猫、IDF =ログ(10,000,000 /千)= 4
TF-IDF = TF IDF = 0.03 4 = 0.12
- NLTKは、TF-IDFを達成します
TextCollection.tf_idf()
ケース:
from nltk.text import TextCollection
text1 = 'I like the movie so much '
text2 = 'That is a good movie '
text3 = 'This is a great one '
text4 = 'That is a really bad movie '
text5 = 'This is a terrible movie'
# 构建TextCollection对象
tc = TextCollection([text1, text2, text3,
text4, text5])
new_text = 'That one is a good movie. This is so good!'
word = 'That'
tf_idf_val = tc.tf_idf(word, new_text)
print('{}的TF-IDF值为:{}'.format(word, tf_idf_val))
結果:
That的TF-IDF值为:0.02181644599700369