
一、樸素貝葉斯及其原理。
貝葉斯公式P(A|B) = P(B|A)*P(A)/P(B) 其中:P(A|B) 是B的后驗概率,是我們計算出來的。 P(B)是先驗概率,是統(tǒng)計出來的。同樣P(B|A)*P(A)也是可以統(tǒng)計出來的。這樣,貝葉斯公式提供了一種方法,讓我們利用可以統(tǒng)計出來的先驗概率推算出后驗概率,而后驗概率我們可以用來分類。
假設 abcd表示四個單詞出現(xiàn)在文章中這個事件?,F(xiàn)在知道一篇文章中abcd出現(xiàn)的概率。求這篇文章的類別。我們可以依次計算文章屬于各個類別的后驗概率,然后取后驗概率最大的類,作為該文章的類別。在求解后驗概率的時候,會出現(xiàn)一個問題,就是計算量過于龐大。P(A|a,b,c,d) = P(a,b,c,d|A)*P(A)/P(a,b,c,d) 此時,P(a,b,c,d)和P(a,b,c,d|A)不容易統(tǒng)計出來。我們不可能每次去文章里掃描一遍,效率太低。也不容易根據(jù)P(a) P(b) P(c) P(d) 算出來,因為一篇文章中的單詞出現(xiàn)的概率,是相互影響的,比如cs和電子競技同時出現(xiàn)的可能性更大,此時不能簡單的把他們的概率相乘。假設cs出現(xiàn)過的地方,電子競技都出現(xiàn)了,他們出現(xiàn)的概率都是1/2,此時把他們相乘,就成了1/4,這是不對的。
我們假設,各個單詞出現(xiàn)在文章中的事件是相互獨立的。既a出現(xiàn)和b出不出現(xiàn)沒有關系。這時候上面的計算就簡單了,直接相乘就可以了,同時我們只需要比較大小,而P(a,b,c,d)在各個類別后驗概率計算的時候都是相等的,直接省略掉就行。由于相互獨立,根據(jù)概率模型 P(a,b,c,d|A) = P(a|A)*P(b|A)*P(c|A)*P(d|A). 但是,這個假設明顯是不成立的。所以這樣的計算方式叫做天真貝葉斯,翻譯過來就是樸素貝葉斯。如果不樸素,也能算,但是要復雜不少。盡管這個假設往往是不成立的,但是樸素貝葉斯仍然能夠有好的效果。
二、具體例子
在我們統(tǒng)計單詞出現(xiàn)概率和文章屬于哪一類的概率的時候,有不同的統(tǒng)計粒度。我們可以按單詞為粒度統(tǒng)計,單詞出現(xiàn)一次就算一次,而文章屬于某類的概率算成文章詞數(shù)除以總體的詞數(shù)。這種方式叫做多項式模型。另一種方式是單詞只要出現(xiàn)在文章中就算出現(xiàn),不考慮單詞出現(xiàn)次數(shù),而文章的概率以文章的篇數(shù)除以總的篇數(shù)來算。這樣的叫伯努利模型。
2.1多項式模型
1)基本原理
在多項式模型中, 設某文檔d=(t1,t2,…,tk),tk是該文檔中出現(xiàn)過的單詞,允許重復,則
先驗概率P(c)= 類c下單詞總數(shù)/整個訓練樣本的單詞總數(shù)
類條件概率P(tk|c)=(類c下單詞tk在各個文檔中出現(xiàn)過的次數(shù)之和+1)/(類c下單詞總數(shù)+|V|)
V是訓練樣本的單詞表(即抽取單詞,單詞出現(xiàn)多次,只算一個),|V|則表示訓練樣本包含多少種單詞。 P(tk|c)可以看作是單詞tk在證明d屬于類c上提供了多大的證據(jù),而P(c)則可以認為是類別c在整體上占多大比例(有多大可能性)。
2)舉例
給定一組分好類的文本訓練數(shù)據(jù),如下:
docId
doc
類別
In c=China?
1
Chinese Beijing Chinese
yes
2
Chinese Chinese Shanghai
yes
3
Chinese Macao
yes
4
Tokyo Japan Chinese
no
給定一個新樣本Chinese Chinese Chinese Tokyo Japan,對其進行分類。該文本用屬性向量表示為d=(Chinese, Chinese, Chinese, Tokyo, Japan),類別集合為Y={yes, no}。
類yes下總共有8個單詞,類no下總共有3個單詞,訓練樣本單詞總數(shù)為11,因此P(yes)=8/11, P(no)=3/11。類條件概率計算如下:
P(Chinese | yes)=(5+1)/(8+6)=6/14=3/7
P(Japan | yes)=P(Tokyo | yes)= (0+1)/(8+6)=1/14
P(Chinese|no)=(1+1)/(3+6)=2/9
P(Japan|no)=P(Tokyo| no) =(1+1)/(3+6)=2/9
分母中的8,是指yes類別下textc的長度,也即訓練樣本的單詞總數(shù),6是指訓練樣本有Chinese,Beijing,Shanghai, Macao, Tokyo, Japan 共6個單詞,3是指no類下共有3個單詞。
有了以上類條件概率,開始計算后驗概率:
P(yes | d)=(3/7)3×1/14×1/14×8/11=108/184877≈0.00058417
P(no | d)= (2/9)3×2/9×2/9×3/11=32/216513≈0.00014780
比較大小,即可知道這個文檔屬于類別china。
2.2伯努利模型
1)基本原理
P(c)= 類c下文件總數(shù)/整個訓練樣本的文件總數(shù)
P(tk|c)=(類c下包含單詞tk的文件數(shù)+1)/(類c下單詞總數(shù)+2)
2)舉例
使用前面例子中的數(shù)據(jù),模型換成伯努利模型。
類yes下總共有3個文件,類no下有1個文件,訓練樣本文件總數(shù)為11,因此P(yes)=3/4, P(Chinese | yes)=(3+1)/(3+2)=4/5,條件概率如下:
P(Japan | yes)=P(Tokyo | yes)=(0+1)/(3+2)=1/5
P(Beijing | yes)= P(Macao|yes)= P(Shanghai |yes)=(1+1)/(3+2)=2/5
P(Chinese|no)=(1+1)/(1+2)=2/3
P(Japan|no)=P(Tokyo| no) =(1+1)/(1+2)=2/3
P(Beijing| no)= P(Macao| no)= P(Shanghai | no)=(0+1)/(1+2)=1/3
有了以上類條件概率,開始計算后驗概率,
P(yes|d)=P(yes)×P(Chinese|yes)×P(Japan|yes)×P(Tokyo|yes)×(1-P(Beijing|yes))×(1-P(Shanghai|yes))×(1-P(Macao|yes))=3/4×4/5×1/5×1/5×(1-2/5) ×(1-2/5)×(1-2/5)=81/15625≈0.005
P(no|d)= 1/4×2/3×2/3×2/3×(1-1/3)×(1-1/3)×(1-1/3)=16/729≈0.022
因此,這個文檔不屬于類別china。
在上面的例子中,之所以加上了1,2,或者|V|,是因為,有些單詞在我們的統(tǒng)計中可能一次都沒出現(xiàn),但是在我們要進行分類的樣本里是出現(xiàn)了的。如果你直接把概率算成0,那連乘之后,概率都為0,已經(jīng)失去了意義。為了避免這種現(xiàn)象,我們把分子分母都加個常數(shù),做平滑處理。這樣算概率的時候才不會都為0 . 即使我們做了平滑處理,還是可能出現(xiàn)0,因為很多小數(shù)連乘,得到的概率本身就非常非常小,在計算機里不停的舍去精度,最后都變成了0. 此時可以對計算的概率取對數(shù)。 因為我們只比較大小,取對數(shù)之后大小關系是不會改變的。log(a*b*c*d) = log(a)+log(b)+log(c)+log(d), 這時候就不會出現(xiàn)下溢出。
三、R語言實現(xiàn)
我使用R語言實現(xiàn)了兩遍。第一遍是對數(shù)碼類產(chǎn)品的文章進行分類。效果不是特別理想,尤其是手機和MP3類別的文章錯判的概率太大。感覺是手機和MP3中出現(xiàn)的屏幕、清晰度等詞匯在相機類別下也出現(xiàn)的很多。家用電器類和電腦類就沒有什么錯判。因為文章第一行都是爬蟲抓來的數(shù)據(jù)來源,所以都給去掉了。
為了搞清楚代碼是不是寫對了,對代碼稍作修改,對另外一組體育類新聞進行了分類。結果又出問題了,在乘以先驗概率后,幾乎所有的類別都判成了游泳。結果,我把條件概率不乘以先驗概率,分類的正確率達到了98%,當然測試數(shù)據(jù)比較少。對體育類分類的時候,還改進了一點代碼,就是不把文章整個存下來了,只存了table,也就是單詞出現(xiàn)的次數(shù)。至于去除停止詞,之前沒有加上,程序運行速度賊快,加上去除停止詞之后,速度就巨慢了,希望分詞包以后能提供這個功能,在分詞的時候就去掉stopwords . 不過我加上之后,對數(shù)碼的分類效果確實有幫助。
<code>library(Rwordseg) #加載分詞工具包 該包需要安裝java 和Rjava
#加載停止詞
stopwords <- readLines("D:\\baiduyundownload\\ml\\R\\my_stopword.txt",encoding="UTF-8")
#去除停止詞的方法
removeStopword <- function(x,stopwords){
return(x[!(x %in% stopwords)])
}
#將文件讀成單詞向量
readAll <- function(dir,stopwords){
files <- list.files(dir)
words <- c()
for(file in files){
lines <- readLines(paste(dir,file,sep="\\"),encoding="UTF-8")
lines <- lines[-1]
temp <- unlist(segmentCN(lines))
temp <- removeStopword(temp,stopwords)
words <- append(words,temp)
}
return(words)
}
dir <- "D:\\baiduyundownload\\ml\\R\\digital\\camera"
camera <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\digital\\computer"
computer <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\digital\\household"
household <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\digital\\mobile"
mobile <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\digital\\MP3"
MP3 <- readAll(dir,stopwords)
model <- list("camera"=camera,"computer"=computer,"household"=household,"mobile"=mobile,
"MP3"=MP3)
#save(model,file="D:model.RData") 因為讀取所有文本在R里非常慢,可以考慮把模型存起來
#下次要使用的時候load("D:model.RData"),就會自動有model對象數(shù)據(jù)分析培訓
#先驗概率
xianyan <- function(model,class){
x <- sapply(model,length)
total <- sum(x)
y <- x[class]
ret <- y/total
names(ret) <- class
return(ret)
}
#條件概率
tiaojian <- function(model,class,words){
wordSet <- model[class]
table <- table(wordSet)
x <- table[words]
x[is.na(x)] <- 0
x <- x + 1
y <- length(wordSet)+length(table)
return(sum(log(x/y)))
#return(prod(x/y))
}
#多項式分類
duoxiangshi <- function(dir,fileName,model,stopwords){
lines <- readLines(paste(dir,file,sep="\\"),encoding="UTF-8")
lines <- lines[-1]
article <- unlist(segmentCN(lines))
article <- removeStopword(article,stopwords)
classes <- names(model)
xianyanP <- xianyan(model,classes)
maxP <- -Inf
calculateClass <- ""
for(class in classes){
temp <- xianyanP[class]*tiaojian(model,class,article)
if(maxP <= temp){
maxP <- temp
calculateClass <- class
}
}
cat(fileName," is classified to ",calculateClass,"\n")
}
dir <- "D:\\baiduyundownload\\ml\\R\\test"
files <- list.files(dir)
for(file in files){
duoxiangshi(dir,file,model,stopwords)
}</code>
下面是體育類
<code>library(Rwordseg)
#添加從搜狗上下載的txt詞庫,注意要是UTF-8 或者GBK編碼的,直接下載的是ansi編碼的,沒用
#另外可以直接安裝搜狗scel詞庫,改一下dicttype即可。詞庫一旦安裝,以后R里都可以用,不用每次都安裝
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\f1專用詞庫.txt",dictname="f1",
dicttype="text")
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\籃球詞庫.txt",dictname="basketball",
dicttype="text")
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\乒乓球.txt",dictname="pingpong",
dicttype="text")
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\斯諾克.txt",dictname="snok",
dicttype="text")
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\體育愛好者.txt",dictname="sports",
dicttype="text")
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\網(wǎng)球詞匯.txt",dictname="vollyball",
dicttype="text")
installDict(dictpath="D:\\baiduyundownload\\ml\\R\\足球詞匯大全.txt",dictname="football",
dicttype="text")
#卸載詞庫
#uninstallDict(removedict='f1')
stopwords <- readLines("D:\\baiduyundownload\\ml\\R\\my_stopword.txt",encoding="UTF-8")
removeStopword <- function(x,stopwords){
return(x[!(x %in% stopwords)])
}
#將文件讀成 單詞統(tǒng)計table
readAll <- function(dir,stopwords){
files <- list.files(dir)
words <- c()
for(file in files){
lines <- scan(paste(dir,file,sep="\\"),what=list(""),encoding="UTF-8")
temp <- unlist(segmentCN(unlist(lines)))
temp <- removeStopword(temp,stopwords)
words <- append(words,temp)
}
return(table(words))
}
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\badminton"
badminton <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\basketball"
basketball <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\billiards"
billiards <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\f1"
f1 <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\football"
football <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\golf"
golf <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\pingpong"
pingpong <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\swim"
swim <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\tennis"
tennis <- readAll(dir,stopwords)
dir <- "D:\\baiduyundownload\\ml\\R\\sport\\volleyball"
volleyball <- readAll(dir,stopwords)
model <- list("badminton"=badminton,"basketball"=basketball,
"billiards"=billiards,"f1"=f1,"football"=football,"golf"=golf,
"pingpong"=pingpong,"swim"=swim,"tennis"=tennis,"volleyball"=volleyball)
save(model,file="D:sport.RData")
#計算先驗概率,返回的是向量,每個文章類別的先驗概率
xianyan <- function(model,class){
x <- sapply(model,sum)
total <- sum(x)
y <- x[class]
ret <- y/total
names(ret) <- class
return(ret)
}
#傳入一個單詞和類別,返回條件概率
tiaojian <- function(model,class,words){
table <- model[[class]]
x <- table[words]
x[is.na(x)] <- 0
x <- x + 1
y <- sum(table)+length(table)
return(sum(log(x/y)))
#return(prod(x/y)) 連乘會下溢出,邊成0
}
#進行多項式分類
duoxiangshi <- function(dir,fileName,model,stopwords){
lines <- scan(paste(dir,file,sep="\\"),what=list(""),encoding="UTF-8")
article <- unlist(segmentCN(lines[[1]]))
article <- removeStopword(article,stopwords)
classes <- names(model)
xianyanP <- xianyan(model,classes)
maxP <- -Inf
calculateClass <- ""
for(class in classes){
#temp <- xianyanP[class]*tiaojian(model,class,article) 這里不乘先驗概率效果更好
#也許應該考慮伯努利模型,按文檔算,我的先驗概率應該是一樣的
temp <- tiaojian(model,class,article)
if(maxP <= temp){
maxP <- temp
calculateClass <- class
}
}
cat(fileName," is classified to ",calculateClass,"\n")
}
dir <- "D:\\baiduyundownload\\ml\\R\\test2"
files <- list.files(dir)
for(file in files){
duoxiangshi(dir,file,model,stopwords)
}</code>
分類結果如下:
badminton11 (1).txt is classified to badminton
badminton11 (2).txt is classified to badminton
badminton11 (3).txt is classified to badminton
badminton11 (4).txt is classified to badminton
badminton11 (5).txt is classified to badminton
badminton11 (6).txt is classified to badminton
basket21.txt is classified to basketball
basket22.txt is classified to basketball
basket23.txt is classified to basketball
basket24.txt is classified to basketball
basket25.txt is classified to basketball
basket26.txt is classified to basketball
basket27.txt is classified to basketball
f1 (1).txt is classified to f1
f1 (2).txt is classified to f1
f1 (3).txt is classified to f1
f1 (4).txt is classified to f1
f1 (5).txt is classified to f1………………………………
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關鍵? 在循環(huán)神經(jīng)網(wǎng)絡(RNN)家族中,長短期記憶網(wǎng)絡(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準備指南? ? 在數(shù)據(jù)驅動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務的價值轉化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預測分析中的應用:從數(shù)據(jù)查詢到趨勢預判? ? 在數(shù)據(jù)驅動決策的時代,預測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準 ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領域中,準確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認證作為國內(nèi)權威的數(shù)據(jù)分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應對策略? 長短期記憶網(wǎng)絡(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學方法在市場調(diào)研數(shù)據(jù)中的深度應用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉日期:解鎖數(shù)據(jù)處理的關鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準確性的基礎 ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03