国产精品电影_久久视频免费_欧美日韩国产激情_成年人视频免费在线播放_日本久久亚洲电影_久久都是精品_66av99_九色精品美女在线_蜜臀a∨国产成人精品_冲田杏梨av在线_欧美精品在线一区二区三区_麻豆mv在线看

用 Gensim 打造完整 NLP 流水線:從文本預處理到語義搜索的系統實踐

發布于 2025-11-10 08:41
瀏覽
0收藏

在自然語言處理(NLP)領域,很多人會問:如何從零開始,構建一個真正可用的 NLP 流水線?

常見的教程往往只聚焦于某一個環節,比如“訓練一個 Word2Vec 模型”或者“跑一次 LDA 主題建模”。但在真實項目中,往往需要一個系統性的流程:從原始文本 → 預處理 → 特征建模 → 相似度分析 → 語義搜索 → 可視化。

今天分享的就是這樣一個完整的 端到端 NLP 流水線,基于 Gensim 構建,并且包含:

  • 文本預處理與語料構建
  • Word2Vec 詞向量建模與相似度分析
  • LDA 主題建模與主題可視化
  • TF-IDF 文檔相似度建模
  • 語義搜索與文檔分類
  • 模型評估(Coherence Score)

本文將完整保留所有代碼,并配上逐段講解,方便你直接運行或復用到自己的項目中。

1. 環境準備與依賴安裝

在 Google Colab 或本地 Python 環境中運行,先安裝依賴。

!pip install --upgrade scipy==1.11.4
!pip install gensim==4.3.2 nltk wordcloud matplotlib seaborn pandas numpy scikit-learn
!pip install --upgrade setuptools


print("Please restart runtime after installation!")
print("Go to Runtime > Restart runtime, then run the next cell")


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from wordcloud import WordCloud
import warnings
warnings.filterwarnings('ignore')


from gensim import corpora, models, similarities
from gensim.models import Word2Vec, LdaModel, TfidfModel, CoherenceModel
from gensim.parsing.preprocessing import preprocess_string, strip_tags, strip_punctuation, strip_multiple_whitespaces, strip_numeric, remove_stopwords, strip_short


import nltk
nltk.download('punkt', quiet=True)
nltk.download('stopwords', quiet=True)
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize

?? 說明

  • 固定??scipy==1.11.4?? 與??gensim==4.3.2??,避免兼容問題;
  • ??nltk?? 用于分詞和停用詞處理;
  • ??WordCloud??? 和??Seaborn?? 負責可視化;
  • 設置 warnings 忽略掉無關提示,輸出更干凈。

2. 構建統一的 NLP 流水線類

我們將所有步驟封裝進一個 AdvancedGensimPipeline 類,方便調用和復用。

class AdvancedGensimPipeline:
   def __init__(self):
       self.dictionary = None
       self.corpus = None
       self.lda_model = None
       self.word2vec_model = None
       self.tfidf_model = None
       self.similarity_index = None
       self.processed_docs = None
      
   def create_sample_corpus(self):
       """Create a diverse sample corpus for demonstration"""
       documents = [           
           "Data science combines statistics, programming, and domain expertise to extract insights",
           "Big data analytics helps organizations make data-driven decisions at scale",
           "Cloud computing provides scalable infrastructure for modern applications and services",
           "Cybersecurity protects digital systems from threats and unauthorized access attempts",
           "Software engineering practices ensure reliable and maintainable code development",
           "Database management systems store and organize large amounts of structured information",
           "Python programming language is widely used for data analysis and machine learning",
           "Statistical modeling helps identify patterns and relationships in complex datasets",
           "Cross-validation techniques ensure robust model performance evaluation and selection",
           "Recommendation systems suggest relevant items based on user preferences and behavior",
           "Text mining extracts valuable insights from unstructured textual data sources",
           "Image classification assigns predefined categories to visual content automatically",
           "Reinforcement learning trains agents through interaction with dynamic environments"
       ]
       return documents

?? 說明這里我們用一組涵蓋 數據科學、機器學習、推薦系統、云計算、安全 的文檔作為示例語料,保證后續的模型有足夠多樣的主題。

3. 文本預處理

對原始文本做清洗、分詞、去停用詞等處理。

def preprocess_documents(self, documents):
       """Advanced document preprocessing using Gensim filters"""
       print("Preprocessing documents...")
      
       CUSTOM_FILTERS = [
           strip_tags, strip_punctuation, strip_multiple_whitespaces,
           strip_numeric, remove_stopwords, strip_short, lambda x: x.lower()
       ]
      
       processed_docs = []
       for doc in documents:
           processed = preprocess_string(doc, CUSTOM_FILTERS)
          
           stop_words = set(stopwords.words('english'))
           processed = [word for word in processed if word notin stop_words and len(word) > 2]
          
           processed_docs.append(processed)
      
       self.processed_docs = processed_docs
       print(f"Processed {len(processed_docs)} documents")
       return processed_docs

?? 說明

  • 使用 Gensim 內置過濾器去掉標點、數字、HTML 標簽等;
  • 用 NLTK 的停用詞表進一步清洗;
  • 最終得到干凈的 token 列表。

4. 構建字典與語料庫

def create_dictionary_and_corpus(self):
       """Create Gensim dictionary and corpus"""
       print("Creating dictionary and corpus...")
      
       self.dictionary = corpora.Dictionary(self.processed_docs)
       self.dictionary.filter_extremes(no_below=2, no_above=0.8)
       self.corpus = [self.dictionary.doc2bow(doc) for doc in self.processed_docs]
      
       print(f"Dictionary size: {len(self.dictionary)}")
       print(f"Corpus size: {len(self.corpus)}")

?? 說明

  • ??Dictionary?? 是詞典,把單詞映射為唯一 ID;
  • ??doc2bow?? 將文檔轉為稀疏向量(Bag of Words);
  • ??filter_extremes?? 去掉太稀有或太頻繁的詞。

5. Word2Vec 詞向量建模與相似度分析

def train_word2vec_model(self):
       """Train Word2Vec model for word embeddings"""
       print("Training Word2Vec model...")
      
       self.word2vec_model = Word2Vec(
           sentences=self.processed_docs,
           vector_size=100,
           window=5,
           min_count=2,
           workers=4,
           epochs=50
       )
       print("Word2Vec model trained successfully")
      
   def analyze_word_similarities(self):
       """Analyze word similarities using Word2Vec"""
       print("\n=== Word2Vec Similarity Analysis ===")
      
       test_words = ['machine', 'data', 'learning', 'computer']
      
       for word in test_words:
           if word in self.word2vec_model.wv:
               similar_words = self.word2vec_model.wv.most_similar(word, topn=3)
               print(f"Words similar to '{word}': {similar_words}")
      
       try:
           if all(w in self.word2vec_model.wv for w in ['machine', 'computer', 'data']):
               analogy = self.word2vec_model.wv.most_similar(
                   positive=['computer', 'data'],
                   negative=['machine'],
                   topn=1
               )
               print(f"Analogy result: {analogy}")
       except:
           print("Not enough vocabulary for complex analogies")

?? 說明

  • ??vector_size=100?? 表示每個詞被嵌入 100 維空間;
  • ??most_similar?? 可找出語義上最接近的詞;
  • 類比分析示例:computer + data - machine ≈ ?。

6. LDA 主題建模與可視化

def train_lda_model(self, num_topics=5):
       """Train LDA topic model"""
       print(f"\nTraining LDA model with {num_topics} topics...")
      
       self.lda_model = LdaModel(
           corpus=self.corpus,
           id2word=self.dictionary,
           num_topics=num_topics,
           random_state=42,
           passes=20,
           alpha='auto'
       )
       print("LDA model trained successfully")
      
   def analyze_topics(self, num_words=5):
       """Display discovered topics"""
       print("\n=== LDA Topics ===")
       topics = self.lda_model.print_topics(num_words=num_words)
       for idx, topic in topics:
           print(f"Topic {idx}: {topic}")
       return topics
      
   def visualize_topics(self):
       """Visualize topic distributions with word clouds"""
       print("\nGenerating topic word clouds...")
       fig, axes = plt.subplots(1, 3, figsize=(15, 5))
      
       for i, ax in enumerate(axes.flatten()):
           if i >= self.lda_model.num_topics:
               break
           words = dict(self.lda_model.show_topic(i, topn=15))
           wc = WordCloud(width=400, height=300, background_color='white')
           wc.generate_from_frequencies(words)
           ax.imshow(wc, interpolation='bilinear')
           ax.set_title(f'Topic {i}')
           ax.axis('off')
      
       plt.tight_layout()
       plt.show()

?? 說明

  • LDA 可將文檔分解為多個主題分布;
  • ??alpha='auto'?? 讓模型自動調節主題稀疏度;
  • 通過WordCloud可直觀展示每個主題的核心詞。

7. TF-IDF 相似度建模與語義搜索

def build_tfidf_similarity_index(self):
       """Build TF-IDF similarity index for documents"""
       print("\nBuilding TF-IDF similarity index...")
       self.tfidf_model = TfidfModel(self.corpus)
       corpus_tfidf = self.tfidf_model[self.corpus]
       self.similarity_index = similarities.MatrixSimilarity(corpus_tfidf)
       print("Similarity index created")
      
   def perform_semantic_search(self, query, topn=3):
       """Perform semantic search using TF-IDF"""
       print(f"\n=== Semantic Search Results for: '{query}' ===")
      
       query_processed = preprocess_string(query)
       query_bow = self.dictionary.doc2bow(query_processed)
       query_tfidf = self.tfidf_model[query_bow]
       similarities_scores = self.similarity_index[query_tfidf]
      
       ranked_results = sorted(enumerate(similarities_scores), key=lambda x: -x[1])[:topn]
       for idx, score in ranked_results:
           print(f"Document {idx}: {score:.3f}")
       return ranked_results

?? 說明

  • 通過 TF-IDF 計算文檔間的余弦相似度;
  • 可以對任意查詢做語義搜索,找出最相關的文檔。

8. 模型評估與文檔分類

def evaluate_topic_coherence(self):
       """Evaluate topic coherence for LDA model"""
       print("\nEvaluating topic coherence...")
       coherence_model = CoherenceModel(
           model=self.lda_model,
           texts=self.processed_docs,
           dictionary=self.dictionary,
           coherence='c_v'
       )
       coherence = coherence_model.get_coherence()
       print(f"Topic coherence score: {coherence:.3f}")
       return coherence
      
   def classify_document(self, doc_index):
       """Classify document into most probable topic"""
       print(f"\nClassifying document {doc_index}...")
       doc_bow = self.corpus[doc_index]
       topics = self.lda_model.get_document_topics(doc_bow)
       topics_sorted = sorted(topics, key=lambda x: -x[1])
       print(f"Document {doc_index} topics: {topics_sorted}")
       return topics_sorted[0] if topics_sorted elseNone

?? 說明

  • ??Coherence Score?? 衡量主題模型效果(越高越好);
  • ??classify_document?? 可給定某篇文檔,輸出其最可能的主題分類。

9. 主函數運行

def main():
   print("=== Advanced NLP Pipeline Demonstration ===\n")
   pipeline = AdvancedGensimPipeline()

   documents = pipeline.create_sample_corpus()
   print("Sample documents:")
   for i, doc in enumerate(documents[:3]):
       print(f"Doc {i}: {doc}")
   print("...")

   processed_docs = pipeline.preprocess_documents(documents)
   pipeline.create_dictionary_and_corpus()

   pipeline.train_word2vec_model()
   pipeline.analyze_word_similarities()

   pipeline.train_lda_model(num_topics=3)
   pipeline.analyze_topics(num_words=7)
   pipeline.visualize_topics()

   pipeline.build_tfidf_similarity_index()
   pipeline.perform_semantic_search("machine learning algorithms", topn=2)

   pipeline.evaluate_topic_coherence()
   pipeline.classify_document(0)

if __name__ == "__main__":
   main()

運行后你會看到:

  • Word2Vec輸出相似詞與類比結果;
  • LDA打印主題分布并生成詞云;
  • 語義搜索給出最相關的文檔;
  • 主題一致性分數;
  • 文檔分類結果。

總結與展望

這篇文章展示了如何用 Gensim 構建一個 端到端 NLP 流水線

  1. 文本預處理:清洗 + 分詞 + 去停用詞
  2. 特征建模:BoW、TF-IDF、Word2Vec、LDA
  3. 相似度分析:TF-IDF + 語義搜索
  4. 主題建模:LDA 主題發現 + 可視化
  5. 模型評估:Coherence Score
  6. 下游任務:語義搜索、文檔分類

在實際業務中,你可以:

  • 用它做企業知識庫的語義檢索
  • 用 LDA 主題建模做用戶評論主題分析
  • 用 Word2Vec 發現行業詞匯的語義關系
  • 用 TF-IDF + 相似度模型做文本聚類與推薦

這套流水線的優勢是:靈活、可擴展、貼近實際。你可以隨時替換為更大規模的數據集,也可以接入更強的嵌入模型(如 BERT、FastText),形成混合方案。


本文轉載自???Halo咯咯??    作者:基咯咯

收藏
回復
舉報
回復
相關推薦
日韩欧美一区二区久久婷婷| 久久一级电影| 国产精品乱码人人做人人爱 | 激情在线视频| 久久久久久**毛片大全| 日韩精品一区在线视频| 欧美久久99| 欧美美女18p| 欧美色图另类| 久久久www成人免费毛片麻豆| 国产欧美一区二区在线播放| 日本久久免费| 亚洲一卡二卡三卡四卡无卡久久| 一区二区三区三区在线| 首页亚洲中字| 91精品国产综合久久精品app| 日本在线播放一区| 综合综合综合综合综合网| 在线不卡一区二区| 激情综合网五月激情| 国产老肥熟一区二区三区| 欧美日韩久久一区二区| 丁香五月网久久综合| 香蕉久久夜色精品国产使用方法| 亚洲精品一区在线观看| 四虎影院观看视频在线观看| 欧美三级日韩三级| 久久久久中文字幕| 91最新在线| 日韩欧美你懂的| 欧美momandson| 99免费在线视频观看| 久久国产日韩| 丰满人妻中伦妇伦精品app| 欧美午夜电影网| 亚洲人体视频| 91精品国产综合久久香蕉922| 日韩理论在线| 亚洲精品日产aⅴ| 国内精品久久久久久久影视简单| 欧美va在线播放| 三级av在线播放| 色噜噜狠狠成人中文综合| 天天干天天玩天天操| 国产精品久久三| 最近免费中文字幕中文高清百度| 日韩高清不卡一区二区三区| 国产综合色香蕉精品| **女人18毛片一区二区| 成人妇女免费播放久久久| 手机在线观看av| 国产一区二区免费电影| 99国产精品一区二区| 综合激情国产一区| 一区在线影院| 久久久欧美精品| 亚洲综合丁香| 老司机午夜激情| 欧美黄色性视频| 亚洲中文字幕无码专区| 亚洲精品视频在线看| 亚洲1区在线| 免费毛片小视频| 亚洲精品久久久久| 黄色在线网站| 国产精品美女免费看| 欧美国产精品中文字幕| 亚洲色图官网| 日韩精品在线观看av| 欧美日韩亚洲激情| 国语精品视频| 久久免费一区| 最新久久zyz资源站| 日韩美女网站| 亚洲欧洲在线播放| 亚洲三级网页| 成年人视频在线免费| 欧美成人一区二区三区片免费 | 成人在线一区二区| 亚洲图片一区二区| 九色porny自拍视频在线播放| 日韩欧美自拍偷拍| 成人h动漫免费观看网站| 亚洲韩国在线| 日韩一区二区麻豆国产| 青青青爽久久午夜综合久久午夜 | 妺妺窝人体色www在线小说| 日韩在线观看免费高清| 亚洲国产成人在线| 爽爽淫人综合网网站| 日韩电影免费观看高清完整版在线观看| 视色,视色影院,视色影库,视色网| 2020国产精品视频| 欧美女孩性生活视频| 成人av在线一区二区三区| 秋霞综合在线视频| 中文字幕视频免费在线观看| 欧美黑人xxx| 久久久亚洲综合| 先锋影音网一区二区| 青青青在线观看视频| 亚洲精品一区二区三区影院| 午夜视频一区| 啦啦啦中文在线观看日本| 国产精品欧美激情| 午夜精品久久久久久久99水蜜桃 | 麻豆精品视频在线| 日本免费视频在线观看| 黄色永久免费网站| 日韩欧美国产电影| 伊人久久大香线蕉| 超碰网在线观看| 国产精品视频免费在线观看| 8x福利精品第一导航| 国产精品免费视频观看| 免费在线成人网| 女同一区二区| 亚洲日本在线天堂| 久久成人综合网| 制服诱惑一区二区| 欧美伊人久久| 波多野结衣欧美| 99re66热这里只有精品4| 大地资源网3页在线观看| 在线免费观看视频黄| 亚洲精品天堂成人片av在线播放| 国产一区免费观看| 18成人免费观看网站下载| 久久亚洲精品视频| 91黄色免费版| 久久人人超碰精品| 97欧美在线视频| jizz内谢中国亚洲jizz| 亚洲熟妇无码av在线播放| 午夜欧美不卡精品aaaaa| 日韩欧美一区二区不卡| 国产精品美女一区二区三区| 91精品观看| 欧美大片免费| 成人午夜激情| 免费一级特黄毛片| 国产男女猛烈无遮挡91| 日韩精品中文字幕久久臀| 国产精品全国免费观看高清| 亚洲国产成人tv| 国产一区二区三区四区老人| а√天堂www在线а√天堂视频| 亚洲午夜在线观看| 91日本视频在线| 国产精品揄拍500视频| 国产精品三级网站| 国产精品中文在线| 欧美日韩一区在线观看视频| 天堂在线亚洲视频| 亚洲人成网站77777在线观看| 国产成人黄色| 亚洲小说欧美另类社区| 精彩视频一区二区| 成人一区二区三区视频| 国产精品乱码人人做人人爱| 欧美色道久久88综合亚洲精品| 一本色道久久综合亚洲精品按摩| 欧美精品一区二区三区高清aⅴ | 成人福利网站在线观看| 欧美日本国产在线| 4p变态网欧美系列| 国产精品18久久久久久首页狼| 国产精品高清免费在线观看| 美女啪啪无遮挡免费久久网站| 欧美zozozo| 日韩电影第一页| 久久香蕉频线观| 2019中文字幕全在线观看| 2019中文字幕在线观看| 国产综合在线视频| 久久激情视频免费观看| 综合网中文字幕| 一区二区欧美日韩视频| 在线观看国产精品91| 欧美精品18videosex性欧美| 青青青青在线视频| 久久精品国产精品国产精品污| 热re91久久精品国99热蜜臀| 91精品久久久久久蜜桃| 麻豆成人av| 理论片鲁丝二区爱情网| 日本电影在线观看| 国内精品久久久久久久影视麻豆| 91在线国内视频| 这里只有精品视频| 久久综合狠狠| 成人欧美一区二区三区1314| 欧美激情国内偷拍| 成 年 人 黄 色 大 片大 全| 国产午夜精品一区理论片| 国产福利一区二区三区在线播放| 亚洲视频久久| 欧美日韩精品国产| 成人午夜小视频| 超碰96在线|