【機器學習】樸素貝葉斯介紹及實例--對短信進行二分類 使用多項式分布

貝葉斯

首先什么是貝葉斯?

一個例子,現分別有 A、B 兩個容器,在容器 A 里分別有 7 個紅球和 3 個白球,在容器 B 里有 1 個紅球和 9
個白球,現已知從這兩個容器里任意抽出了一個球,且是紅球,問這個紅球是來自容器 A 的概率是多少? 假設已經抽出紅球為事件 B,選中容器 A
為事件 A,則有:P(B) = 8/20,P(A) = 1/2,P(B|A) = 7/10,按照公式,則有:P(A|B) =
(7/10)(1/2) / (8/20) = 0.875
在這里插入圖片描述
例如:一座別墅在過去的 20 年里一共發生過 2 次被盜,別墅的主人有一條狗,狗平均每周晚上叫 3 次,在盜賊入侵時狗叫的概率被估計為 0.9,問題是:在狗叫的時候發生入侵的概率是多少?
我們假設 A 事件為狗在晚上叫,B 為盜賊入侵,則以天為單位統計,P(A) = 3/7,P(B) = 2/(20
365) = 2/7300,P(A|B) = 0.9,按照公式很容易得出結果:P(B|A) = 0.9*(2/7300) / (3/7) = 0.00058

一般公式(解決更復雜的問題):
在這里插入圖片描述

樸素的概念:獨立性假設,假設各個特征之間是獨立不相關的

舉例 對應成獨立的時間概率:
在這里插入圖片描述

貝葉斯模型

  • 高斯分布樸素貝葉斯
  • 多項式分布樸素貝葉斯
  • 伯努利分布樸素貝葉斯

對短信進行二分類—>使用多項式分布樸素貝葉斯實例代碼:

導包加載數據

import warnings
warnings.filterwarnings('ignore')import numpy as npimport pandas as pdfrom sklearn.naive_bayes import GaussianNB,BernoulliNB,MultinomialNB 
sms = pd.read_csv('./SMSSpamCollection.csv',sep = '\t',header = None)
sms.columns = ['labels','message']
sms
labelsmessage
0hamGo until jurong point, crazy.. Available only ...
1hamOk lar... Joking wif u oni...
2spamFree entry in 2 a wkly comp to win FA Cup fina...
3hamU dun say so early hor... U c already then say...
4hamNah I don't think he goes to usf, he lives aro...
.........
5567spamThis is the 2nd time we have tried 2 contact u...
5568hamWill ü b going to esplanade fr home?
5569hamPity, * was in mood for that. So...any other s...
5570hamThe guy did some bitching but I acted like i'd...
5571hamRofl. Its true to its name

5572 rows × 2 columns

measurements = [{'city': 'Dubai', 'temperature': 33.},{'city': 'London', 'temperature': 12.},{'city': 'San Francisco', 'temperature': 18.},
]from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()display(vec.fit_transform(measurements).toarray())vec.get_feature_names()

array([[ 1., 0., 0., 33.],
[ 0., 1., 0., 12.],
[ 0., 0., 1., 18.]])

[‘city=Dubai’, ‘city=London’, ‘city=San Francisco’, ‘temperature’]

# 詞頻統計
from sklearn.feature_extraction.text import CountVectorizer 
X.shape

(5572,)

#Series,一維數據
X = sms['message']y = sms['labels']cv = CountVectorizer()
#參數ngram_range() 詞組例如turn on
# stop_word 停用詞cv.fit(X)#!!!特征提取特征轉換都是transform#word count:詞頻統計
X_wc = cv.transform(X)
X_wc

<5572x8713 sparse matrix of type ‘<class ‘numpy.int64’>’
with 74169 stored elements in Compressed Sparse Row format>

v_ = cv.vocabulary_
v_

{‘go’: 3571,
‘until’: 8084,
‘jurong’: 4374,
‘point’: 5958,
‘crazy’: 2338,
‘available’: 1316,
‘only’: 5571,

v_['its']

4253

##!!!!Serise的用法自帶索引查詢 使用-1需要加iloc
X.iloc[-1]

‘Rofl. Its true to its name’

# DataFrame,二維
# 詞頻沒有統計出來,數據格式不對
X = sms[['message']]y = sms['labels']cv = CountVectorizer()cv.fit(X)# word count:詞頻統計
X_wc = cv.transform(X)
X_wc

<1x1 sparse matrix of type ‘<class ‘numpy.int64’>’
with 1 stored elements in Compressed Sparse Row format>

使用量化的數據X_wc算法訓練

# X_wc 
# y
from sklearn.model_selection import train_test_split
# 稀松矩陣
X_train,X_test,y_train,y_test = train_test_split(X_wc,y,test_size = 0.2)
X_train

<4457x8713 sparse matrix of type ‘<class ‘numpy.int64’>’
with 59291 stored elements in Compressed Sparse Row format>

bNB = BernoulliNB()bNB.fit(X_train,y_train)bNB.score(X_test,y_test)

0.9847533632286996

mNB = MultinomialNB()mNB.fit(X_train,y_train)mNB.score(X_test,y_test)

0.9856502242152466

gNB = GaussianNB()gNB.fit(X_train.toarray(),y_train)gNB.score(X_test.toarray(),y_test)

0.9183856502242153

dense_data = X_wc.toarray()
dense_data.shape

(5572, 8713)

稀松矩陣存儲大小對比稠密矩陣 !!

np.save('./dense_data',dense_data) 
#稠密矩陣330m文件
from scipy import sparse 
sparse.save_npz('./sparse_data',X_wc)
# 稀松矩陣大部分是0,一小部分有對應值 存儲僅需幾百kb
X_wc

<5572x8713 sparse matrix of type ‘<class ‘numpy.int64’>’
with 74169 stored elements in Compressed Sparse Row format>

自然語言處理NLP

簡單的自然語言處理:詞頻統計,分類

復雜自然語言處理:語意理解,實時翻譯

import warnings
warnings.filterwarnings('ignore')
import numpy as npimport pandas as pdimport matplotlib.pyplot as plt
%matplotlib inlinefrom sklearn.naive_bayes import GaussianNB,BernoulliNB,MultinomialNB# Count :詞頻統計
# Tfidf:term frequencty inverse documnent frequency(詞頻統計的基礎上,進行了加權)
from sklearn.feature_extraction.text import CountVectorizer,TfidfVectorizer,TfidfTransformerfrom sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
from jieba import analyse 
sms = pd.read_csv('./SMSSpamCollection.csv',sep = '\t',header = None)
sms.columns = ['target','message']
sms.head()
targetmessage
0hamGo until jurong point, crazy.. Available only ...
1hamOk lar... Joking wif u oni...
2spamFree entry in 2 a wkly comp to win FA Cup fina...
3hamU dun say so early hor... U c already then say...
4hamNah I don't think he goes to usf, he lives aro...
X = sms['message']
y = sms['target'] 
# 哪些詞區分能力比較強:名字,動詞
ENGLISH_STOP_WORDS
# 中文停用詞:我,的,得,了,啊,呢,哼
# 處理中文分詞,jieba分詞 pip install jieba

frozenset({‘a’,
‘about’,
‘above’,
‘across’,
‘after’,
‘afterwards’,
‘again’,

len(ENGLISH_STOP_WORDS)

318

count_word = CountVectorizer()
X_cw = count_word.fit_transform(X)
v_ = count_word.vocabulary_
len(v_)

8713

count_word = CountVectorizer(stop_words=ENGLISH_STOP_WORDS)
X_cw = count_word.fit_transform(X)
v_ = count_word.vocabulary_
print(X_cw[10])
len(v_)

(0, 7588) 1
(0, 2299) 1

8444

count_word = CountVectorizer(stop_words='english')
X_cw = count_word.fit_transform(X)
v_ = count_word.vocabulary_
len(v_)

8444

X_dense = X_cw.toarray()
X_dense

array([[0, 0, 0, …, 0, 0, 0],
[0, 0, 0, …, 0, 0, 0],
[0, 0, 0, …, 0, 0, 0],
…,
[0, 0, 0, …, 0, 0, 0],
[0, 0, 0, …, 0, 0, 0],
[0, 0, 0, …, 0, 0, 0]], dtype=int64)

(X_dense[:,0] >=1).sum()

10

plt.hist(X_dense[:,0])

在這里插入圖片描述 (array([5562., 0., 0., 0., 0., 0., 0., 0., 0.,
10.]),
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),
<a list of 10 Patch objects>)

'''Convert a collection of raw documents to a matrix of TF-IDF features.Equivalent to :class:`CountVectorizer` followed by
:class:`TfidfTransformer`.'''
# TfidfVectorizer == CountVectorizer + TfidfTransformer
tf_idf = TfidfVectorizer()
X_tf_idf = tf_idf.fit_transform(X)
print(X_tf_idf[12])

(0, 4114) 0.09803359946740374
(0, 3373) 0.14023485782692063

v_ = tf_idf.vocabulary_
v_

{‘go’: 3571,
‘until’: 8084,
‘jurong’: 4374,
‘point’: 5958,
。。。

v2_ = {}
for k,v in v_.items():v2_[v] = k 
v2_[747]

‘81010’

from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X_tf_idf,y,test_size = 0.2) 
%%time
bNB = BernoulliNB()bNB.fit(X_train,y_train)print(bNB.score(X_test,y_test))

0.97847533632287
Wall time: 19.3 ms

%%time
gNB = GaussianNB()gNB.fit(X_train.toarray(),y_train)print(gNB.score(X_test.toarray(),y_test))

0.8914798206278027
Wall time: 1.99 s

測試是否好用?

X_test = ['Pls go ahead with watts. I just wanted to be sure.I check already lido only got 530 show in e afternoon. U finish work already?','Hello, my love. What are you doing?Find out from 30th August. www.areyouunique.co.uk',"Thanx 4 e brownie it's v nice... We tried to contact you re your reply to our offer of 750 mins 150 textand a new video phone call 08002988890 now or reply for free delivery tomorrow",'We tried to contact you re your reply to our offer of a Video Handset? To find out who it is call from a landline 09111032124 . PoBox12n146tf150p','precious things are very few in the world that is the reason there is only one you','for the world you are a person.for me you the whold world']X_test_tf_idf = tf_idf.transform(X_test)
X_test_tf_idf

<6x8713 sparse matrix of type ‘<class ‘numpy.float64’>’
with 111 stored elements in Compressed Sparse Row format>

# 第一條短信:兩條正常短信拼接
# 第二條短信:正常和垃圾短信拼接
# 第二條短信:正常和垃圾短信拼接
# 第二條短信:垃圾短信拼接
bNB.predict(X_test_tf_idf)

array([‘ham’, ‘ham’, ‘spam’, ‘spam’, ‘ham’, ‘ham’], dtype=’<U4’)

sklearn 中文本的處理

feature_extract特征‘萃取’


count_word = CountVectorizer(stop_words=ENGLISH_STOP_WORDS,ngram_range=(1,1))
X_cw = count_word.fit_transform(X)
v_ = count_word.vocabulary_
print(X_cw[10])
len(v_)

(0, 7588) 1
(0, 2299) 1
(0, 7934) 1

65436

v_= count_word.vocabulary_ 
d = {}
for k,v in v_.items():d[v] = k 
print(X[0])
print(X_cw[0])

Go until jurong point, crazy… Available only in bugis n great world la e buffet… Cine there got amore wat…
(0, 23208) 1

d[29530]

‘jurong point crazy’

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/456074.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/456074.shtml
英文地址,請注明出處:http://en.pswp.cn/news/456074.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

H.264碼流結構

a、對照&#xff1a;H.263的碼流結構H.263定義的碼流結構是分級結構&#xff0c;共四層。自上而下分別為&#xff1a;圖像層(picture layer)、塊組層(GOB layer)、宏塊層(macroblock layer)和塊層(block layer)。 PSC TR PTYPE PQUANT CPM PSBI TRB DBQUANT PEI PSPARE PEI…

Gartner分享物聯網和智慧城市最新數據

主題為“移我所想 Mobile is me”的2016世界移動大會上海展正在上海如火如荼的舉行&#xff0c;Gartner也在第一時間分享了最新的市場數據&#xff0c;包括企業級用戶最為關注的物聯網和智慧城市的調查預測報告&#xff0c;下面就一起來看看吧&#xff01; 智慧城市與物聯網 物…

python中格式化字符串

format格式字符串 語法&#xff1a; 它通過{}和:來代替%。 注意&#xff1a; 字符串的format函數可以接受無限個參數&#xff0c;位置可以不按順序&#xff0c;可以不用或者用多次&#xff0c;不過2.6不能為空{}&#xff0c;2.7才可以。 “映射”示例 通過位置 In [1]: {0},{…

讓360安全瀏覽器默認使用谷歌內核

瀏覽器默認內核的指定只需在head標簽中添加一行代碼即可&#xff1a; 若頁面需默認用極速核&#xff0c;增加標簽&#xff1a;<meta name"renderer" content"webkit"> 若頁面需默認用ie兼容內核&#xff0c;增加標簽&#xff1a;<meta name"…

作業幫電腦版在線使用_作業幫:創新科技驅動在線教育新模式

10月15日&#xff0c;在線教育領軍企業作業幫在中國校長大會在線教育論壇上&#xff0c;獨家發布《學習的真相&#xff1a;全國K12學情大數據及學習洞察》&#xff0c;宣布已推出作業幫直播課“名師大招”課程體系&#xff0c;集中展示多款面向K12人群的教育黑科技和硬件產品。…

【機器學習】DBSCAN聚類算法—優于Kmean—(理論+圖解+python代碼)

一、前言 二、DBSCAN聚類算法 三、參數選擇 四、DBSCAN算法迭代可視化展示 五、常用的評估方法&#xff1a;輪廓系數 六、用Python實現DBSCAN聚類算法 一、前言 去年學聚類算法的R語言的時候&#xff0c;有層次聚類、系統聚類、K-means聚類、K中心聚類&#xff0c;最后呢…

H264白皮書

理論上我是知道一點點的mpeg4的&#xff0c;但是貌似忘記了&#xff0c;本來要重新看mpeg4&#xff0c;結果有人告訴我h264肯定比mpeg4要好&#xff0c;結果就被派去看h264了&#xff0c;看完了一個什么白皮書以后&#xff0c;只好替h264吹噓一下了&#xff1a; 1。Intra pred…

python中的內建函數

內建函數 以下是目前我們已經滲透過的內建函數: 類型相關 int() 創建或者將其他數據轉化為整型float() 創建或者將其他數據轉化為浮點型bool() 創建或者將其他數據轉化為布爾型complex() 創建或者將其他數據轉化為復數str() 創建或者將其他數據轉化為字符串list() 創建或…

卡巴斯基:風險無國界 網絡安全從業者要與小網民保持一致

“互聯網沒有國界&#xff0c;每個國家碰到的問題基本上是類似的。對于網絡犯罪這件事&#xff0c;并不針對哪個國家&#xff0c;任何有弱點、有機會的地方&#xff0c;黑客都會去。”卡巴斯基公司CEO尤金卡巴斯基在接受未來網&#xff08;微信公眾號lovek618&#xff09;記者采…

js/jquery循環提取table單元格值

<table id"tbitem"><tr><td>測試數據1</td></tr><tr><td>測試數據2</td></tr><tr><td>測試數據3</td></tr><tr><td>測試數據4</td></tr><tr><td&g…

windows無法訪問指定設備路徑或文件_完全免費的文件數據恢復工具:Microsoft Windows File Recovery...

意外刪除文件的經歷是大多數人都遇到過&#xff0c;但是幸運的是有一種“后悔藥”可以吃&#xff0c;因為我們可以使用一些【數據恢復軟件】以找回一些已刪除的文件。市面上有很多這類型的軟件&#xff0c;例如EasyRecovery、DiskGenius、Recuva 等軟件。但是&#xff0c;功能強…

【機器學習】XGBoost集成算法——(理論+圖解+python代碼比較其他算法使用天池蒸汽數據)

一、集成算法思想 二、XGBoost基本思想 三、用python實現XGBoost算法 在競賽題中經常會用到XGBoost算法&#xff0c;用這個算法通常會使我們模型的準確率有一個較大的提升。既然它效果這么好&#xff0c;那么它從頭到尾做了一件什么事呢&#xff1f;以及它是怎么樣去做的呢&a…

H.264的技術優勢及其在H.323系統中的應用

一、引言 近年來&#xff0c;隨著我國通信網絡基礎設施的快速建設&#xff0c;視訊業務由于可以為處于多點的與會者提供音視頻等多種信息&#xff0c;節省大量費用&#xff0c;提高工作效率&#xff0c;因而發展迅速&#xff0c;并有望成為NGN的主要業務。視訊會議系統從產生至…

python中的列表

列表操作 一組有序數據的組合就是列表 創建列表 空列表 方式1&#xff1a;變量 []方式2&#xff1a; 變量 list() 具有一個數據的列表 變量 [值] 備注&#xff1a;列表中保存的每個都稱之為元素具有多個數據的列表 變量 [值,值,值....]普通操作 訪問列表中的元素 …

高通被歐盟指控壟斷 或將面臨高達25億美元罰款

在被韓國指控違反反壟斷規定后&#xff0c;高通近期又被歐盟指控以壟斷方式排擠競爭對手。在11月10日的聽證會上高通將回應有關指控。高通有可能因此遭受25億美元的巨額罰款。 歐盟之前就曾經指出&#xff0c;高通在2009至2011年以低于成本價售賣部分基帶芯片&#xff0c;將英國…

wireshark

wireshark使用&#xff1a; http://wenku.baidu.com/link?urljIT43RWZbHissG70TK_hqVKRO6KWNZ4nK9RfncaFA5p-mrmjxsNd2aIapcKTtDDAjG0mddEKiLtwbqpu3Z12bXStDiDevZUGWTPxop4mKhG wireshark開源代碼相關&#xff1a; http://blog.csdn.net/zx824/article/details/7207713 轉載于…

1萬條數據大概占多大空間_國漫丨2019年上半年漫畫數據報告

文 │ 骨朵國漫一、各漫畫平臺總體趨勢1、快看漫畫快看漫畫平臺2019年Q2各月評論數較Q1有較明顯的下滑&#xff0c;月評論數都在400萬條左右&#xff1b;收藏數方面&#xff0c;2019年2月達到了半年內最高值&#xff0c;為2660.1萬條。2、看漫畫、知音漫客等平臺(小明太極旗下)…

【機器學習】 LightGBM——優于XGBoost提升的集成算法(安裝+對比XGBoost改進+參數說明+python代碼實例)

中文官方文檔&#xff1a;http://lightgbm.apachecn.org/cn/latest/Installation-Guide.html 英文官方文檔&#xff1a;https://lightgbm.readthedocs.io/en/latest/ 一、lightGBM安裝 在anaconda中輸入&#xff1a;pip install lightGBM即可 輸入import lightgbm as lgb做測…

H.264簡單總結

&#xff08;quan整理&#xff09;一、視頻信息和信號的特點 < type"text/javascript">< type"text/javascript" src"http://pagead2.googlesyndication.com/pagead/show_ads.js"> 1&#xff0e;1直觀性 利用人的視覺系統&am…

輕量級代碼生成器-OnlyCoder 第一篇

程序猿利器&#xff1a;代碼生成器&#xff0c;使用代碼生成器已經好幾年了&#xff0c;增刪改查各種生成&#xff0c;從UI到DATA層均生成過。之前有使用過動軟的&#xff0c;T4模板等.... T4生成實體還是沒有問題的&#xff0c;但是生成MVC視圖就有點煩雜了&#xff0c;動軟給…