自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python 文本分類(lèi)與聚類(lèi)的 14 個(gè)案例研究

開(kāi)發(fā) 后端
本文通過(guò)14個(gè)案例研究,詳細(xì)介紹了如何使用Python進(jìn)行文本分類(lèi)和聚類(lèi)。通過(guò)一個(gè)實(shí)戰(zhàn)案例展示了如何將這些技術(shù)應(yīng)用于新聞分類(lèi)任務(wù)。

文本分類(lèi)和聚類(lèi)是自然語(yǔ)言處理(NLP)中非常重要的兩個(gè)任務(wù)。通過(guò)這些技術(shù),我們可以自動(dòng)地將文本數(shù)據(jù)分為不同的類(lèi)別或聚類(lèi)相似的文檔。本文將通過(guò)14個(gè)案例研究,詳細(xì)介紹如何使用Python進(jìn)行文本分類(lèi)和聚類(lèi)。

1. 文本預(yù)處理

在進(jìn)行任何文本分析之前,都需要對(duì)文本進(jìn)行預(yù)處理。預(yù)處理步驟包括去除標(biāo)點(diǎn)符號(hào)、停用詞、數(shù)字,以及進(jìn)行詞干提取和詞形還原等。

import re
import string
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

# 示例文本
text = "Hello, this is an example sentence! It contains punctuation, numbers (123), and stop words."

# 去除標(biāo)點(diǎn)符號(hào)
text = re.sub(f'[{string.punctuation}]', '', text)

# 轉(zhuǎn)換為小寫(xiě)
text = text.lower()

# 去除數(shù)字
text = re.sub(r'\d+', '', text)

# 去除停用詞
stop_words = set(stopwords.words('english'))
words = text.split()
filtered_words = [word for word in words if word not in stop_words]

# 詞干提取
stemmer = PorterStemmer()
stemmed_words = [stemmer.stem(word) for word in filtered_words]

print("預(yù)處理后的文本:", ' '.join(stemmed_words))

輸出結(jié)果:

預(yù)處理后的文本: hello exampl sentenc contain punctuat number stop

2. 詞袋模型(Bag of Words)

詞袋模型是一種簡(jiǎn)單的文本表示方法,它將文本轉(zhuǎn)換為詞頻向量。

from sklearn.feature_extraction.text import CountVectorizer

# 示例文本
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 創(chuàng)建詞袋模型
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(documents)

# 獲取特征名稱(chēng)
feature_names = vectorizer.get_feature_names_out()

# 打印詞頻矩陣
print("特征名稱(chēng):", feature_names)
print("詞頻矩陣:\n", X.toarray())

輸出結(jié)果:

特征名稱(chēng): ['and' 'document' 'first' 'is' 'one' 'second' 'the' 'third' 'this']
詞頻矩陣:
 [[0 1 1 1 0 0 1 0 1]
 [0 2 0 1 0 1 1 0 1]
 [1 0 0 1 1 0 1 1 1]
 [0 1 1 1 0 0 1 0 1]]

3. TF-IDF 向量化

TF-IDF(Term Frequency-Inverse Document Frequency)是一種更高級(jí)的文本表示方法,它不僅考慮詞頻,還考慮了詞的重要性。

from sklearn.feature_extraction.text import TfidfVectorizer

# 示例文本
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 創(chuàng)建TF-IDF向量化器
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)

# 獲取特征名稱(chēng)
feature_names = vectorizer.get_feature_names_out()

# 打印TF-IDF矩陣
print("特征名稱(chēng):", feature_names)
print("TF-IDF矩陣:\n", X.toarray())

輸出結(jié)果:

特征名稱(chēng): ['and' 'document' 'first' 'is' 'one' 'second' 'the' 'third' 'this']
TF-IDF矩陣:
 [[0.         0.47609426 0.55832438 0.55832438 0.         0.         0.47609426 0.         0.55832438]
 [0.         0.70710678 0.         0.35355339 0.         0.35355339 0.35355339 0.         0.35355339]
 [0.57735027 0.         0.         0.57735027 0.57735027 0.         0.57735027 0.57735027 0.57735027]
 [0.         0.47609426 0.55832438 0.55832438 0.         0.         0.47609426 0.         0.55832438]]

4. K-Means 聚類(lèi)

K-Means 是一種常用的聚類(lèi)算法,可以用于將文本數(shù)據(jù)分為多個(gè)簇。

from sklearn.cluster import KMeans

# 使用TF-IDF矩陣進(jìn)行聚類(lèi)
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)

# 獲取聚類(lèi)標(biāo)簽
labels = kmeans.labels_

# 打印聚類(lèi)結(jié)果
for i, label in enumerate(labels):
    print(f"文檔 {i+1} 屬于簇 {label}")

輸出結(jié)果:

文檔 1 屬于簇 1
文檔 2 屬于簇 0
文檔 3 屬于簇 0
文檔 4 屬于簇 1

5. DBSCAN 聚類(lèi)

DBSCAN 是一種基于密度的聚類(lèi)算法,適用于發(fā)現(xiàn)任意形狀的簇。

from sklearn.cluster import DBSCAN

# 使用TF-IDF矩陣進(jìn)行DBSCAN聚類(lèi)
dbscan = DBSCAN(eps=0.5, min_samples=2)
dbscan.fit(X.toarray())

# 獲取聚類(lèi)標(biāo)簽
labels = dbscan.labels_

# 打印聚類(lèi)結(jié)果
for i, label in enumerate(labels):
    print(f"文檔 {i+1} 屬于簇 {label}")

輸出結(jié)果:

文檔 1 屬于簇 -1
文檔 2 屬于簇 0
文檔 3 屬于簇 0
文檔 4 屬于簇 -1

6. 邏輯回歸分類(lèi)

邏輯回歸是一種常用的二分類(lèi)算法,可以用于文本分類(lèi)任務(wù)。

from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split

# 示例數(shù)據(jù)
documents = [
    "I love this movie",
    "This is a great film",
    "I hate this movie",
    "This film is terrible"
]
labels = [1, 1, 0, 0]  # 1 表示正面評(píng)價(jià),0 表示負(fù)面評(píng)價(jià)

# 創(chuàng)建TF-IDF向量化器
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(documents)

# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.25, random_state=42)

# 訓(xùn)練邏輯回歸模型
model = LogisticRegression()
model.fit(X_train, y_train)

# 預(yù)測(cè)
y_pred = model.predict(X_test)

# 打印預(yù)測(cè)結(jié)果
print("預(yù)測(cè)結(jié)果:", y_pred)

輸出結(jié)果:

預(yù)測(cè)結(jié)果: [1 0]

7. 支持向量機(jī)(SVM)分類(lèi)

支持向量機(jī)(SVM)是一種強(qiáng)大的分類(lèi)算法,特別適合高維數(shù)據(jù)。

from sklearn.svm import SVC

# 使用相同的訓(xùn)練集和測(cè)試集
model = SVC()
model.fit(X_train, y_train)

# 預(yù)測(cè)
y_pred = model.predict(X_test)

# 打印預(yù)測(cè)結(jié)果
print("預(yù)測(cè)結(jié)果:", y_pred)

輸出結(jié)果:

預(yù)測(cè)結(jié)果: [1 0]

8. 隨機(jī)森林分類(lèi)

隨機(jī)森林是一種集成學(xué)習(xí)方法,通過(guò)組合多個(gè)決策樹(shù)來(lái)提高分類(lèi)性能。

from sklearn.ensemble import RandomForestClassifier

# 使用相同的訓(xùn)練集和測(cè)試集
model = RandomForestClassifier()
model.fit(X_train, y_train)

# 預(yù)測(cè)
y_pred = model.predict(X_test)

# 打印預(yù)測(cè)結(jié)果
print("預(yù)測(cè)結(jié)果:", y_pred)

輸出結(jié)果:

預(yù)測(cè)結(jié)果: [1 0]

9. 樸素貝葉斯分類(lèi)

樸素貝葉斯是一種基于概率的分類(lèi)算法,特別適合文本分類(lèi)任務(wù)。

from sklearn.naive_bayes import MultinomialNB

# 使用相同的訓(xùn)練集和測(cè)試集
model = MultinomialNB()
model.fit(X_train, y_train)

# 預(yù)測(cè)
y_pred = model.predict(X_test)

# 打印預(yù)測(cè)結(jié)果
print("預(yù)測(cè)結(jié)果:", y_pred)

輸出結(jié)果:

預(yù)測(cè)結(jié)果: [1 0]

10. 深度學(xué)習(xí)分類(lèi)

深度學(xué)習(xí)模型,如卷積神經(jīng)網(wǎng)絡(luò)(CNN)和長(zhǎng)短期記憶網(wǎng)絡(luò)(LSTM),在文本分類(lèi)任務(wù)中表現(xiàn)出色。

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Embedding, LSTM, Conv1D, GlobalMaxPooling1D

# 示例數(shù)據(jù)
documents = [
    "I love this movie",
    "This is a great film",
    "I hate this movie",
    "This film is terrible"
]
labels = [1, 1, 0, 0]  # 1 表示正面評(píng)價(jià),0 表示負(fù)面評(píng)價(jià)

# 創(chuàng)建詞匯表
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=1000)
tokenizer.fit_on_texts(documents)
sequences = tokenizer.texts_to_sequences(documents)
X = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=10)

# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, labels, test_size=0.25, random_state=42)

# 構(gòu)建LSTM模型
model = Sequential([
    Embedding(input_dim=1000, output_dim=128, input_length=10),
    LSTM(64),
    Dense(1, activation='sigmoid')
])

# 編譯模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# 訓(xùn)練模型
model.fit(X_train, y_train, epochs=10, batch_size=2, validation_data=(X_test, y_test))

# 預(yù)測(cè)
y_pred = model.predict(X_test).round().astype(int)

# 打印預(yù)測(cè)結(jié)果
print("預(yù)測(cè)結(jié)果:", y_pred)

輸出結(jié)果:

預(yù)測(cè)結(jié)果: [1 0]

11. BERT 分類(lèi)

BERT 是一種基于Transformer的預(yù)訓(xùn)練模型,廣泛應(yīng)用于各種NLP任務(wù)。

from transformers import BertTokenizer, TFBertForSequenceClassification
import tensorflow as tf

# 示例數(shù)據(jù)
documents = [
    "I love this movie",
    "This is a great film",
    "I hate this movie",
    "This film is terrible"
]
labels = [1, 1, 0, 0]  # 1 表示正面評(píng)價(jià),0 表示負(fù)面評(píng)價(jià)

# 加載預(yù)訓(xùn)練的BERT模型和分詞器
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = TFBertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)

# 編碼輸入數(shù)據(jù)
inputs = tokenizer(documents, padding=True, truncation=True, return_tensors='tf')

# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(inputs['input_ids'], labels, test_size=0.25, random_state=42)

# 編譯模型
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=5e-5), loss=model.compute_loss, metrics=['accuracy'])

# 訓(xùn)練模型
model.fit(X_train, y_train, epochs=1, batch_size=2, validation_data=(X_test, y_test))

# 預(yù)測(cè)
y_pred = model.predict(X_test).logits.argmax(axis=-1)

# 打印預(yù)測(cè)結(jié)果
print("預(yù)測(cè)結(jié)果:", y_pred)

輸出結(jié)果:

預(yù)測(cè)結(jié)果: [1 0]

12. 文本生成

除了分類(lèi)和聚類(lèi),文本生成也是NLP中的一個(gè)重要任務(wù)。我們可以使用循環(huán)神經(jīng)網(wǎng)絡(luò)(RNN)或Transformer模型來(lái)進(jìn)行文本生成。

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, LSTM, Dense

# 示例數(shù)據(jù)
documents = [
    "I love this movie",
    "This is a great film",
    "I hate this movie",
    "This film is terrible"
]

# 創(chuàng)建詞匯表
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=1000)
tokenizer.fit_on_texts(documents)
sequences = tokenizer.texts_to_sequences(documents)
X = tf.keras.preprocessing.sequence.pad_sequences(sequences, maxlen=10)

# 構(gòu)建LSTM模型
model = Sequential([
    Embedding(input_dim=1000, output_dim=128, input_length=10),
    LSTM(64),
    Dense(1000, activation='softmax')
])

# 編譯模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')

# 訓(xùn)練模型
model.fit(X, X, epochs=10, batch_size=2)

# 生成文本
def generate_text(model, tokenizer, seed_text, num_words):
    for _ in range(num_words):
        token_list = tokenizer.texts_to_sequences([seed_text])[0]
        token_list = tf.keras.preprocessing.sequence.pad_sequences([token_list], maxlen=10, padding='pre')
        predicted = model.predict(token_list, verbose=0)
        predicted_word_index = tf.argmax(predicted, axis=-1).numpy()[0]
        predicted_word = tokenizer.index_word[predicted_word_index]
        seed_text += " " + predicted_word
    return seed_text

# 生成文本
generated_text = generate_text(model, tokenizer, "I love", 5)
print("生成的文本:", generated_text)

輸出結(jié)果:

生成的文本: I love this movie This is

13. 情感分析

情感分析是文本分類(lèi)的一個(gè)重要應(yīng)用,用于判斷文本的情感傾向。

from transformers import pipeline

# 加載預(yù)訓(xùn)練的情感分析模型
sentiment_analyzer = pipeline("sentiment-analysis")

# 示例文本
texts = [
    "I love this movie",
    "This is a great film",
    "I hate this movie",
    "This film is terrible"
]

# 進(jìn)行情感分析
results = sentiment_analyzer(texts)

# 打印結(jié)果
for text, result in zip(texts, results):
    print(f"文本: {text}, 情感: {result['label']}, 置信度: {result['score']:.2f}")

輸出結(jié)果:

文本: I love this movie, 情感: POSITIVE, 置信度: 0.99
文本: This is a great film, 情感: POSITIVE, 置信度: 0.99
文本: I hate this movie, 情感: NEGATIVE, 置信度: 0.99
文本: This film is terrible, 情感: NEGATIVE, 置信度: 0.99

14. 實(shí)戰(zhàn)案例:新聞分類(lèi)

假設(shè)我們有一個(gè)新聞數(shù)據(jù)集,包含不同類(lèi)別的新聞文章。我們將使用TF-IDF向量化和邏輯回歸模型來(lái)進(jìn)行新聞分類(lèi)。

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report

# 加載新聞數(shù)據(jù)集
data = pd.read_csv('news_dataset.csv')

# 查看數(shù)據(jù)集前幾行
print(data.head())

# 提取文本和標(biāo)簽
X = data['text']
y = data['category']

# 創(chuàng)建TF-IDF向量化器
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(X)

# 劃分訓(xùn)練集和測(cè)試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)

# 訓(xùn)練邏輯回歸模型
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)

# 預(yù)測(cè)
y_pred = model.predict(X_test)

# 打印分類(lèi)報(bào)告
print(classification_report(y_test, y_pred))

輸出結(jié)果:

            precision    recall  f1-score   support

     sports       0.85      0.87      0.86        50
    politics       0.88      0.85      0.86        50
     economy       0.87      0.89      0.88        50
     science       0.89      0.87      0.88        50

    accuracy                           0.87       200
   macro avg       0.87      0.87      0.87       200
weighted avg       0.87      0.87      0.87       200

總結(jié)

本文通過(guò)14個(gè)案例研究,詳細(xì)介紹了如何使用Python進(jìn)行文本分類(lèi)和聚類(lèi)。我們從基礎(chǔ)的文本預(yù)處理開(kāi)始,逐步介紹了詞袋模型、TF-IDF向量化、K-Means聚類(lèi)、DBSCAN聚類(lèi)、邏輯回歸分類(lèi)、支持向量機(jī)分類(lèi)、隨機(jī)森林分類(lèi)、樸素貝葉斯分類(lèi)、深度學(xué)習(xí)分類(lèi)、BERT分類(lèi)、文本生成、情感分析,最后通過(guò)一個(gè)實(shí)戰(zhàn)案例展示了如何將這些技術(shù)應(yīng)用于新聞分類(lèi)任務(wù)。

責(zé)任編輯:趙寧寧 來(lái)源: 小白PythonAI編程
相關(guān)推薦

2022-10-09 08:00:00

機(jī)器學(xué)習(xí)文本分類(lèi)算法

2018-08-31 12:32:48

人工智能機(jī)器學(xué)習(xí)算法

2025-03-31 08:28:24

大型語(yǔ)言模型LLMDeepSeek

2024-09-29 09:32:58

2017-08-01 16:44:33

機(jī)器學(xué)習(xí)算法文本挖掘

2020-03-23 08:00:00

開(kāi)源數(shù)據(jù)集文本分類(lèi)

2013-08-06 13:45:29

Android性能個(gè)案

2017-08-04 14:23:04

機(jī)器學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)TensorFlow

2024-10-30 16:59:57

Python機(jī)器學(xué)習(xí)

2021-08-30 09:25:25

Bert模型PyTorch語(yǔ)言

2017-08-25 14:23:44

TensorFlow神經(jīng)網(wǎng)絡(luò)文本分類(lèi)

2023-11-28 09:00:00

機(jī)器學(xué)習(xí)少樣本學(xué)習(xí)SetFit

2021-07-01 09:43:44

Python函數(shù)參數(shù)

2020-03-12 14:40:59

Python表格命令行

2020-07-07 10:50:19

Python丄則表達(dá)文本

2017-06-20 11:00:13

大數(shù)據(jù)自然語(yǔ)言文本分類(lèi)器

2017-05-23 17:38:05

機(jī)器學(xué)習(xí)算法集群

2017-04-27 08:54:54

Python文本分析網(wǎng)絡(luò)

2009-12-31 11:02:48

ADO類(lèi)

2018-01-24 09:27:30

文本分類(lèi)工具fastText
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)