一、任務(wù)目標(biāo)
python代碼寫將 HarryPorter 電子書作為語料庫,分別使用詞袋模型,TF-IDF模型和Word2Vec模型進(jìn)行文本向量化。
1. 首先將數(shù)據(jù)預(yù)處理,Word2Vec 訓(xùn)練時(shí)要求考慮每個(gè)單詞前后的五個(gè)詞匯,地址為
作為其上下文 ,生成的向量維度為50維
2.分別搜索 courtroom 和 wizard 這兩個(gè)詞語義最近的5個(gè)單詞
3.對(duì)wizard 和witch 這兩個(gè)單詞在二維平面上進(jìn)行可視化
內(nèi)容補(bǔ)充:
什么是對(duì)他們進(jìn)行向量化?
當(dāng)涉及將文本數(shù)據(jù)轉(zhuǎn)換為計(jì)算機(jī)可以處理的形式時(shí),常用的方法之一是文本向量化。文本向量化是將文本文檔轉(zhuǎn)換為數(shù)值向量的過程,以便計(jì)算機(jī)可以理解和處理。
?
詞袋模型(Bag of Words Model):
- 詞袋模型是一種簡(jiǎn)單而常用的文本向量化方法。
- 在詞袋模型中,每個(gè)文檔被表示為一個(gè)向量,其中每個(gè)維度對(duì)應(yīng)于詞匯表中的一個(gè)詞。
- 文檔向量的每個(gè)維度表示對(duì)應(yīng)詞在文檔中出現(xiàn)的頻次(或者可以是二進(jìn)制值,表示是否出現(xiàn))。
- 這意味著詞袋模型忽略了單詞的順序和上下文,只關(guān)注詞的出現(xiàn)頻率。
?
TF-IDF模型(Term Frequency-Inverse Document Frequency Model):
- TF-IDF是一種用于評(píng)估一個(gè)詞對(duì)于一個(gè)文檔在語料庫中的重要性的統(tǒng)計(jì)方法。
- 與詞袋模型類似,TF-IDF模型也將文檔表示為向量,但是每個(gè)維度的值是基于詞的TF-IDF得分。
- Term Frequency(TF)表示詞在文檔中出現(xiàn)的頻率,而Inverse Document Frequency(IDF)表示詞的稀有程度或信息量。
- TF-IDF的計(jì)算方法是將TF與IDF相乘,以突出顯示在文檔中頻繁出現(xiàn)但在整個(gè)語料庫中稀有的詞語。
?
Word2Vec模型:
- Word2Vec是一種用于將詞語表示為連續(xù)向量空間中的向量的技術(shù)。
- Word2Vec模型基于分布式假設(shè),即在語料庫中,具有相似上下文的詞在向量空間中應(yīng)該具有相似的表示。
- Word2Vec模型通常通過訓(xùn)練神經(jīng)網(wǎng)絡(luò)來學(xué)習(xí)詞向量,其中每個(gè)詞都被表示為一個(gè)密集的向量,稱為嵌入(embedding)。
- 通過Word2Vec,詞向量可以捕捉到詞語之間的語義和語法關(guān)系,例如,語義上相似的詞在向量空間中會(huì)更加接近。
二、代碼部分?
nltk.download('punkt')
nltk.download('stopwords')
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from gensim.models import Word2Vec
from gensim.models import TfidfModel
from gensim.corpora import Dictionary
import matplotlib.pyplot as plt
# 導(dǎo)入停用詞
stop_words = set(stopwords.words('english'))
# 加載數(shù)據(jù)
corpus_file = '/Users/zhengyawen/Downloads/HarryPorter.txt'
with open(corpus_file, 'r', encoding='utf-8') as file:
data = file.read()
# 預(yù)處理數(shù)據(jù)
sentences = [word_tokenize(sentence.lower()) for sentence in data.split('.')]
preprocessed_sentences = []
for sentence in sentences:
valid_words = []
for word in sentence:
if word.isalpha() and word not in stop_words:
valid_words.append(word)
preprocessed_sentences.append(valid_words)
# 構(gòu)建Word2Vec模型
w2v_model = Word2Vec(sentences=preprocessed_sentences, vector_size=50, window=5, min_count=1, sg=0)
# 獲取單詞向量
vector_courtroom = w2v_model.wv['courtroom']
vector_wizard = w2v_model.wv['wizard']
# 搜索與“courtroom”和“wizard”最相似的5個(gè)單詞
similar_words_courtroom = w2v_model.wv.most_similar('courtroom', topn=5)
similar_words_wizard = w2v_model.wv.most_similar('wizard', topn=5)
print("Word2Vec模型:")
print("單詞 courtroom 的向量:", vector_courtroom)
print("單詞 wizard 的向量:", vector_wizard)
print("語義最近的5個(gè)單詞 (courtroom):")
for word, similarity in similar_words_courtroom:
print(f"{word}: {similarity}")
print("\n語義最近的5個(gè)單詞 (wizard):")
for word, similarity in similar_words_wizard:
print(f"{word}: {similarity}")
# 構(gòu)建詞袋模型
dictionary = Dictionary(preprocessed_sentences)
corpus = [dictionary.doc2bow(sentence) for sentence in preprocessed_sentences]
tfidf_model = TfidfModel(corpus)
corpus_tfidf = tfidf_model[corpus]
# 可視化Word2Vec模型中wizard和witch的向量
words_to_plot = ['wizard', 'witch']
word_vectors = [w2v_model.wv[word] for word in words_to_plot]
# 可視化
plt.figure(figsize=(10, 6))
for i, word in enumerate(words_to_plot):
plt.scatter(word_vectors[i][0], word_vectors[i][1], label=word)
plt.xlabel('Dimension 1')
plt.ylabel('Dimension 2')
plt.title('Visualization of Word Vectors')
plt.legend()
plt.show()
三、代碼運(yùn)行結(jié)果
文章來源:http://www.zghlxwxcb.cn/news/detail-850620.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-850620.html
到了這里,關(guān)于【自然語言】使用詞袋模型,TF-IDF模型和Word2Vec模型進(jìn)行文本向量化的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!