? ? ? ?大家好,我是帶我去滑雪!
? ? ? ?文本分類是一種機(jī)器學(xué)習(xí)和自然語言處理(NLP)任務(wù),旨在將給定的文本數(shù)據(jù)分配到預(yù)定義的類別或標(biāo)簽中。其目標(biāo)是為文本數(shù)據(jù)提供自動(dòng)分類和標(biāo)注,使得可以根據(jù)其內(nèi)容或主題進(jìn)行組織、排序和分析。文本分類在各種應(yīng)用場(chǎng)景中廣泛應(yīng)用,包括情感分析、垃圾郵件過濾、新聞分類、推薦系統(tǒng)等。
? ? ? ?文本分類的關(guān)鍵步驟包括:
- 數(shù)據(jù)準(zhǔn)備:準(zhǔn)備訓(xùn)練集和測(cè)試集的文本數(shù)據(jù),每個(gè)文本數(shù)據(jù)都經(jīng)過標(biāo)記或分類。
- 特征提?。簭奈谋緮?shù)據(jù)中提取有用的特征來表示文本。常見的特征提取方法包括詞袋模型(Bag-of-Words Model)、TF-IDF(Term Frequency-Inverse Document Frequency)、詞嵌入(Word Embeddings)等。
- 訓(xùn)練模型:使用已標(biāo)記的訓(xùn)練數(shù)據(jù)來訓(xùn)練分類模型。常見的機(jī)器學(xué)習(xí)算法包括樸素貝葉斯(Naive Bayes)、支持向量機(jī)(Support Vector Machines,SVM)、決策樹(Decision Trees)、隨機(jī)森林(Random Forests)等。最近,深度學(xué)習(xí)方法如卷積神經(jīng)網(wǎng)絡(luò)(Convolutional Neural Networks,CNN)和循環(huán)神經(jīng)網(wǎng)絡(luò)(Recurrent Neural Networks,RNN)也被廣泛應(yīng)用于文本分類任務(wù)。
- 模型評(píng)估:使用預(yù)留的測(cè)試數(shù)據(jù)對(duì)訓(xùn)練好的模型進(jìn)行評(píng)估,計(jì)算分類模型的準(zhǔn)確性、精確度、召回率等指標(biāo)。
- 預(yù)測(cè)和應(yīng)用:使用已訓(xùn)練的模型對(duì)新的未標(biāo)記文本數(shù)據(jù)進(jìn)行分類和預(yù)測(cè)。
? ? ? ?本期首先利用python抓取百度貼吧中的評(píng)論獲得文本數(shù)據(jù),再對(duì)文本數(shù)據(jù)進(jìn)行中文分詞、數(shù)據(jù)清洗、特征提取、TF-IDF權(quán)重計(jì)算等數(shù)據(jù)預(yù)處理,再進(jìn)行一定的數(shù)據(jù)分析和數(shù)據(jù)可視化,最后運(yùn)用樸素貝葉斯、神經(jīng)網(wǎng)絡(luò)、支持向量機(jī)、隨機(jī)森林、邏輯回歸、K近鄰、決策樹、梯度提升共計(jì)8種機(jī)器學(xué)習(xí)對(duì)文本數(shù)據(jù)進(jìn)行分類。
目錄
1、抓取百度貼吧評(píng)論獲取文本數(shù)據(jù)
(1)代碼
(2)部分?jǐn)?shù)據(jù)展示
2、數(shù)據(jù)預(yù)處理
(1)中文分詞
(2)文本情感打分
(3)將文本數(shù)據(jù)轉(zhuǎn)化為向量
(4)計(jì)算TF-IDF權(quán)重
?3、數(shù)據(jù)分析與可視化
(1)統(tǒng)計(jì)得分區(qū)間數(shù)量
(2)得分區(qū)間數(shù)據(jù)可視化
(3)繪制詞云圖
(4)關(guān)鍵詞TOP10
(5)計(jì)算積極評(píng)論與消極評(píng)論數(shù)量并數(shù)據(jù)可視化
4、使用8種機(jī)器學(xué)習(xí)對(duì)文本數(shù)據(jù)進(jìn)行分類
(1)隨機(jī)劃分,按總樣本數(shù)的20%劃分,即測(cè)試集(784個(gè))與訓(xùn)練集(3135個(gè))
(2)調(diào)用模型,并對(duì)比測(cè)試集精度
1、抓取百度貼吧評(píng)論獲取文本數(shù)據(jù)
(1)代碼
import requests
import time
from bs4 import BeautifulSoup
def get_html(url):
??? try:
??????? kv = {'user-agent':'Mozilla/4.0'} #偽裝客戶端
??????? r = requests.get(url,headers = kv,timeout=30)
??????? r.raise_for_status()
??????? r.encoding = 'UTF-8'
??????? #print(r.text[:1000])
??????? return r.text
??? except:
??????? return "ERROR"
def get_content(url):
??? comments = []?
??? html = get_html(url)
??? soup = BeautifulSoup(html,'lxml')
??? #with open('b.txt','a+',encoding='utf-8') as f1:
??????????? #f1.write(soup.prettify())
??? liTags = soup.find_all('li', attrs={'class': 'j_thread_list clearfix thread_item_box'})
??? for li in liTags:
??????? comment = {}?
??????? try:
??????????? comment['title'] = li.find('a',attrs={'class':'j_th_tit'}).text.strip()
??????????? comment['link'] = "http://tieba.baidu.com" + li.find('a',attrs={'class': 'j_th_tit'})['href']
??????????? comment['name'] = li.find('span',attrs={'class': 'tb_icon_author'}).text.strip()
??????????? comment['time'] = li.find('span', attrs={'class': 'pull-right is_show_create_time'}).text.strip()
??????????? comment['replyNum'] = li.find('span', attrs={'class': 'threadlist_rep_num center_text'}).text.strip()
??????????? comments.append(comment)
??????? except:
??????????? print('出了點(diǎn)小問題')
??? return comments
def Out2File(dict):
??? with open('大學(xué)吧的評(píng)論最新.txt','a+',encoding='utf-8') as f:
??????? for comment in dict:
??????????? f.write('標(biāo)題: {} \t 鏈接:{} \t 發(fā)帖人:{} \t 發(fā)帖時(shí)間:{} \t 回復(fù)數(shù)量: {} \n'.format(
??????????????? comment['title'], comment['link'], comment['name'], comment['time'], comment['replyNum']))
??????? print('當(dāng)前頁面爬取完成')
???????
def main(base_url, deep):
??? url_list = [] #存取需要爬取的帖子鏈接
??? for i in range(0, deep):
??????? url_list.append(base_url + '&pn=' + str(50 * i))
??? print('所有的網(wǎng)頁已經(jīng)下載到了本地,開始篩選信息。。。。')
??? #循環(huán)寫入數(shù)據(jù)
??? for url in url_list:
??????? content = get_content(url)
??????? Out2File(content)
??? print('所有信息都已經(jīng)保存完畢!')
base_url = 'http://tieba.baidu.com/f?kw=大學(xué)&ie=utf-8&'
deep =200
if __name__ == '__main__':
main(base_url,deep)
輸出結(jié)果:
所有的網(wǎng)頁已經(jīng)下載到了本地,開始篩選信息。。。。
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成
當(dāng)前頁面爬取完成? ? ? ? ? ? ?
(2)部分?jǐn)?shù)據(jù)展示
1 | 好好畫畫啦 |
2 | 求各專業(yè)大佬 |
3 | 歡迎報(bào)考北郵 |
4 | 話費(fèi)充值需要dd |
5 | 兼職有沒有來的 |
6 | 在校大學(xué)生一枚 |
7 | 滴滴,喜歡的看過來 |
8 | 大學(xué)生進(jìn)?。。?/td> |
9 | 有什么快速掙錢的好方法? |
10 | 大學(xué),要掙米,來,???帶一手 |
11 | 大學(xué)宿舍限電是普遍現(xiàn)象嗎,一般限多少瓦 |
12 | 你們認(rèn)為大學(xué)生打工,什么工作最好 |
13 | 家人們?cè)摬辉?/td> |
14 | 兼職介紹,有沒有 |
15 | 穩(wěn)穩(wěn)的一天 |
16 | 創(chuàng)建一個(gè)資源共享群,親們留下你們的微信,我拉你們進(jìn)群 |
17 | 假期的小工作 |
18 | 尋說明書系統(tǒng)說明,撰寫選手 |
19 | 加QQ!?。?. |
20 | 有兼職群?jiǎn)?/td> |
2、數(shù)據(jù)預(yù)處理
(1)中文分詞
? ? ? ? 爬取到的評(píng)論,使用Python爬取了中文數(shù)據(jù)集之后,首先需要對(duì)數(shù)據(jù)集進(jìn)行中文分詞處理。由于英文中的詞與詞之間是采用空格關(guān)聯(lián)的,按照空格可以直接劃分詞組,所以不需要進(jìn)行分詞處理,而中文漢字之間是緊密相連的,并且存在語義,詞與詞之間沒有明顯的分隔點(diǎn),所以需要借助中文分詞技術(shù)將語料中的句子按空格分割,變成一段段詞序列。使用中文分詞技術(shù)及Jiaba中文分詞工具。
? ? ? ?分詞后的評(píng)論并不是所有的詞都與文檔內(nèi)容相關(guān),往往存在一些表意能力很差的輔助性詞語,比如中文詞組“我們”、“的”、“可以”等,英文詞匯“a”、“the”等。這類詞在自然語言處理或數(shù)據(jù)挖掘中被稱為停用詞(Stop Words),它們是需要進(jìn)行過濾的。通常借用停用詞表或停用詞字典進(jìn)行過濾,這里所用的停用詞表可以在文末進(jìn)行獲取。
?import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import networkx as nx
plt.rcParams['font.sans-serif'] = ['KaiTi']? #指定默認(rèn)字體 SimHei黑體
plt.rcParams['axes.unicode_minus'] = False?? #解決保存圖像是負(fù)號(hào)'
import jieba
stop_list? = pd.read_csv("停用詞.txt",index_col=False,quoting=3,sep="\t",names=['stopword'], encoding='utf-8')
#Jieba分詞函數(shù)
def txt_cut(juzi):
??? lis=[w for w in jieba.lcut(juzi) if w not in stop_list.values]
??? return (" ").join(lis)
df=pd.read_csv('E:/工作/碩士/data.csv',encoding="ANSI")
df['cutword']=df['PL'].astype('str').apply(txt_cut)
df=df[['PL','cutword']]
df
輸出結(jié)果:
(2)文本情感打分
import pandas as pd
data1 = pd.read_csv('E:/工作/碩士/博客//data.csv',encoding="ANSI")
from snownlp import SnowNLP
data1['emotion'] = data1['PL'].apply(lambda x:SnowNLP(x).sentiments)
data1.to_excel('評(píng)論情感打分值.xlsx',index=False)#保存數(shù)據(jù),具體數(shù)據(jù)看表格
? ? ? 部分結(jié)果展示:
序號(hào) | PL | emotion |
1 | 周末了,同學(xué)們,哪里可以下單機(jī)游戲玩? | 0.936292288 |
2 | 大學(xué)生等一個(gè) | 0.753614865 |
3 | 每位同學(xué)順利畢業(yè)??是我最大的心愿?? | 0.994685253 |
4 | 了解過咸魚吧 | 0.5 |
5 | 學(xué)習(xí)通看完了嗎,沒看完找我呀 | 0.761398932 |
6 | 特涼列骯刪 | 0.066063183 |
7 | 有沒有安徽的 | 0.77536362 |
8 | 寄快遞也可以賺錢,你們滿意嘛? | 0.112413565 |
9 | 618可以組隊(duì)的羊毛群,(超紅口令很早就知道) | 0.100694453 |
10 | 大家晚上好 | 0.529099344 |
11 | 同學(xué)們大家好 | 0.87008235 |
12 | 放縱的代價(jià) | 0.738870215 |
13 | 大學(xué)生第一次上臺(tái)演講ppt | 0.853786676 |
14 | 有沒有正常的 | 0.353878603 |
15 | 純綠色搬磚,多勞多得 | 0.154165573 |
(3)將文本數(shù)據(jù)轉(zhuǎn)化為向量
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
#取出X和y
X = df['text']
y = df['label']
#創(chuàng)建一個(gè)TfidfVectorizer的實(shí)例
vectorizer = TfidfVectorizer()
#使用Tfidf將文本轉(zhuǎn)化為向量
X = vectorizer.fit_transform(X)
#看看特征形狀
X.shape
(4)計(jì)算TF-IDF權(quán)重
data1 = {'word': vectorizer.get_feature_names_out(),
??????? 'tfidf': X.toarray().sum(axis=0).tolist()}
df1 = pd.DataFrame(data1).sort_values(by="tfidf" ,ascending=False,ignore_index=True)
df1
? ? ? ?部分結(jié)果展示:
?3、數(shù)據(jù)分析與可視化
(1)統(tǒng)計(jì)得分區(qū)間數(shù)量
from itertools import groupby
score_list =data1['emotion']
step = 0.1
for k, g in groupby(sorted(score_list), key=lambda x: x//step):
print('{}-{}: {}'.format(k*step, (k+1)*step+1, len(list(g))))
輸出結(jié)果:
(2)得分區(qū)間數(shù)據(jù)可視化
%matplotlib inline
from matplotlib import pyplot as plt
from matplotlib import font_manager
a = ["0-0.1", "0.1-0.2","0.2-0.3","0.3-0.4","0.4-0.5","0.5-0.6","0.6-0.7","0.7-0.8","0.8-0.9","0.9-1"]
b = [265,248,259,329,348,319,329,375,439,1064]
plt.figure(figsize=(20,8),dpi=300)
my_font=font_manager.FontProperties(fname=r"C:\Windows\Fonts\STSONG.TTF",size=12)
rects=plt.bar(a,b,width=0.3,color=['red','green','blue','cyan','yellow','gray'])
plt.xticks(a,fontproperties=my_font,rotation=45)
plt.xlabel("情感得分區(qū)間",fontproperties=my_font,fontsize=20)
plt.ylabel("數(shù)量",fontproperties=my_font,fontsize=20) #rotation='horizontal'
#plt.grid(alpha=0.5)
for rect in rects:
??? y=rect.get_height()
??? x=rect.get_x()+rect.get_width()/2
??? plt.text(x,y+0.5,str(y),ha="center",fontsize=15)
plt.title("情感分區(qū)間條形圖",fontproperties=my_font,fontsize=20)
plt.savefig("squares2.png",
??????????? bbox_inches ="tight",
??????????? pad_inches = 1,
??????????? transparent = True,
??????????? facecolor ="w",
??????????? edgecolor ='w',
??????????? dpi=300,
??????????? orientation ='landscape')
輸出結(jié)果:
(3)繪制詞云圖
from wordcloud import WordCloud
import jieba
w = WordCloud(font_path="msyh.ttc",background_color="white",max_words=500,width=1000,height=600)?? #font_path="msyh.ttc",設(shè)置字體,否則顯示不出來
text = ''
for s in data1['PL']:
??? text += s
data_cut = ' '.join(jieba.lcut(text))
w.generate(data_cut)
image = w.to_file('詞云圖.png')
輸出結(jié)果:
(4)關(guān)鍵詞TOP10
from jieba import analyse
key_words = jieba.analyse.extract_tags(sentence=text, topK=10, withWeight=True, allowPOS=())
key_words
輸出結(jié)果:
(5)計(jì)算積極評(píng)論與消極評(píng)論數(shù)量并數(shù)據(jù)可視化
#計(jì)算積極評(píng)論與消極評(píng)論各自的數(shù)目
pos = 0
neg = 0
for i in data1['emotion']:
??? if i >= 0.5:
??????? pos += 1
??? else:
??????? neg += 1
print('積極評(píng)論,消極評(píng)論數(shù)目分別為:')
pos,neg
輸出結(jié)果:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus'] = False
pie_labels='postive','negative'
plt.pie([pos,neg],labels=pie_labels,autopct='%1.1f%%',shadow=True)
plt.savefig("squares3.png",
??????????? bbox_inches ="tight",
????? ??????pad_inches = 1,
??????????? transparent = True,
??????????? facecolor ="w",
??????????? edgecolor ='w',
??????????? dpi=300,
??????????? orientation ='landscape')
輸出結(jié)果:
4、使用8種機(jī)器學(xué)習(xí)對(duì)文本數(shù)據(jù)進(jìn)行分類
(1)隨機(jī)劃分,按總樣本數(shù)的20%劃分,即測(cè)試集(784個(gè))與訓(xùn)練集(3135個(gè))
?X_train, X_test, y_train, y_test =train_test_split(X,y,test_size=0.2,stratify=y,random_state = 0)
#可以檢查一下劃分后數(shù)據(jù)形狀
X_train.shape,X_test.shape, y_train.shape, y_test.shape
(2)調(diào)用模型,并對(duì)比測(cè)試集精度
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
model1?=??LogisticRegression(C=1e10,max_iter=10000) model2?=?MultinomialNB() model3?=?KNeighborsClassifier(n_neighbors=50) model4?=?DecisionTreeClassifier(random_state=77) model5=?RandomForestClassifier(n_estimators=500,??max_features='sqrt',random_state=10) model6?=?GradientBoostingClassifier(random_state=123) model9?=?SVC(kernel="rbf",?random_state=77) model10?=?MLPClassifier(hidden_layer_sizes=(16,8),?random_state=77,?max_iter=10000) model_list=[model1,model2,model3,model4,model5,model6,model9,model10] model_name=['邏輯回歸','樸素貝葉斯','K近鄰','決策樹','隨機(jī)森林','梯度提升','支持向量機(jī)','神經(jīng)網(wǎng)絡(luò)']scores=[] for?i?in?range(len(model_list)): ????model_C=model_list[i] ????name=model_name[i] ????model_C.fit(X_train,?y_train) ????s=model_C.score(X_test,?y_test) ????scores.append(s) ????print(f'{name}方法在測(cè)試集的準(zhǔn)確率為{round(s,3)}')plt.figure(figsize=(7,3),dpi=128) sns.barplot(y=model_name,x=scores,orient="h") plt.xlabel('模型準(zhǔn)確率') plt.ylabel('模型名稱') plt.xticks(fontsize=10,rotation=45) plt.title("不同模型文本分類準(zhǔn)確率對(duì)比") plt.savefig("squares4.png", ????????????bbox_inches?="tight", ????????????pad_inches?=?1, ????????????transparent?=?True, ????????????facecolor?="w", ????????????edgecolor?='w', ????????????dpi=300, ????????????orientation?='landscape')輸出結(jié)果:
需要數(shù)據(jù)集的家人們可以去百度網(wǎng)盤(永久有效)獲?。?/p>
鏈接:https://pan.baidu.com/s/1E59qYZuGhwlrx6gn4JJZTg?pwd=2138
提取碼:2138?
更多優(yōu)質(zhì)內(nèi)容持續(xù)發(fā)布中,請(qǐng)移步主頁查看。
若有問題可郵箱聯(lián)系:1736732074@qq.com?
博主的WeChat:TCB1736732074文章來源:http://www.zghlxwxcb.cn/news/detail-516315.html
? ?點(diǎn)贊+關(guān)注,下次不迷路!文章來源地址http://www.zghlxwxcb.cn/news/detail-516315.html
到了這里,關(guān)于python數(shù)據(jù)分析之利用多種機(jī)器學(xué)習(xí)方法實(shí)現(xiàn)文本分類、情感預(yù)測(cè)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!