資料分析模型之樸素貝葉斯模型
阿新 • • 發佈:2020-10-25
模型思想
該分類器的實現思想⾮常簡單,即通過已知類別的訓練資料集,計算樣本的先驗概率,然後利⽤⻉葉斯概率公式測算未知類別樣本屬於某個類別的後驗概率,最終以最⼤後驗概率所對應的類別作為樣本的預測值。
先驗概率
先驗概率:指根據以往經驗和分析得到的概率,如全概率公式,它往往作為"由因求果"問題中的"因"出現的概率。
後驗概率
後驗概率:是資訊理論的基本概念之一。在一個通訊系統中,在收到某個訊息之後,接收端所瞭解到的該訊息傳送的概率稱為後驗概率。
後驗概率的計算要以先驗概率為基礎。後驗概率可以根據通過貝葉斯公式,用先驗概率和似然函式計算出來。
高斯貝葉斯分類器
高斯貝葉斯分類器:適用於資料集的自變數X都是連續的數值型,通常會優先使用高斯貝葉斯分類器
多項式貝葉斯分類器
多項式貝葉斯分佈器:適用於資料集的自變數X都是離散的數值型,通常會優先使用多項式貝葉斯分類器
伯努利貝葉斯分類器
伯努利貝葉斯分類器:適用於資料集中的自變數X都是0-1的二元值,通常會優先使用伯努利貝葉斯分類器
高斯貝葉斯分類器
# 讀⼊資料 skin = pd.read_excel(r'C:\Users\Administrator\Desktop\Skin_Segment.xlsx') # 樣本拆分 X_train,X_test,y_train,y_test = model_selection.train_test_split(skin.iloc[:,:3], skin.y, test_size = 0.25, random_state=1234) # 調⽤⾼斯樸素⻉葉斯分類器的“類” gnb = naive_bayes.GaussianNB() # 模型擬合 gnb.fit(X_train, y_train) # 模型在測試資料集上的預測 gnb_pred = gnb.predict(X_test) # 構建混淆矩陣 cm = pd.crosstab(gnb_pred,y_test) # 繪製熱力圖 sns.heatmap(cm, annot = True, cmap = 'GnBu', fmt = 'd') # 去除x軸和y軸標籤 plt.xlabel('Real') plt.ylabel('Predict') # 顯示圖形 plt.show() print('模型的準確率為:\n',metrics.accuracy_score(y_test,gnb_pred))
多項式貝葉斯分類器
# 讀取資料 mushrooms = pd.read_csv(r'C:\Users\Administrator\Desktop\mushrooms.csv') # 將字元型資料做因⼦化處理,將其轉換為整數型資料 columns = mushrooms.columns[1:] for column in columns: mushrooms[column] = pd.factorize(mushrooms[column])[0] # 將資料集拆分為訓練集合測試集 Predictors = mushrooms.columns[1:] X_train,X_test,y_train,y_test = model_selection.train_test_split(mushrooms[Predictors], mushrooms['type'], test_size = 0.25, random_state = 10) # 構建多項式⻉葉斯分類器的“類” mnb = naive_bayes.MultinomialNB() # 基於訓練資料集的擬合 mnb.fit(X_train, y_train) # 基於測試資料集的預測 mnb_pred = mnb.predict(X_test) # 構建混淆矩陣 cm = pd.crosstab(mnb_pred,y_test) # 繪製熱力圖 sns.heatmap(cm, annot = True, cmap = 'GnBu', fmt = 'd') # 去除x軸和y軸標籤 plt.xlabel('') plt.ylabel('') # 顯示圖形 plt.show() # 模型的預測準確率 print('模型的準確率為:\n',metrics.accuracy_score(y_test, mnb_pred))
伯努利貝葉斯分類器
jieba模組
Python中針對中文進行欄位的分解(需要自定義詞庫,停止詞詞庫)
# 讀⼊評論資料
evaluation = pd.read_excel(r'Contents.xlsx',sheetname=0)
# 運⽤正則表示式,將評論中的數字和英⽂去除
evaluation.Content = evaluation.Content.str.replace('[0-9a-zA-Z]','')
# 載入⾃定義詞庫
jieba.load_userdict(r'all_words.txt')
# 讀⼊停⽌詞
with open(r'mystopwords.txt', encoding='UTF-8') as words:
stop_words = [i.strip() for i in words.readlines()]
# 構造切詞的⾃定義函式,並在切詞過程中刪除停⽌詞
def cut_word(sentence):
words = [i for i in jieba.lcut(sentence) if i not in stop_words]
# 切完的詞⽤空格隔開
result = ' '.join(words)
return(result)
# 調⽤⾃定義函式,並對評論內容進⾏批量切詞
words = evaluation.Content.apply(cut_word)
# 計算每個詞在各評論內容中的次數,並將稀疏度為99%以上的詞刪除
counts = CountVectorizer(min_df = 0.01)
# ⽂檔詞條矩陣
dtm_counts = counts.fit_transform(words).toarray()
# 矩陣的列名稱
columns = counts.get_feature_names()
# 將矩陣轉換為資料框,即X變數
X = pd.DataFrame(dtm_counts, columns=columns)
# 情感標籤變數
y = evaluation.Type
# 將資料集拆分為訓練集和測試集
X_train,X_test,y_train,y_test = model_selection.train_test_split(X,y,test_size = 0.25,random_state=1)
# 構建伯努利⻉葉斯分類器
bnb = naive_bayes.BernoulliNB()
# 模型在訓練資料集上的擬合
bnb.fit(X_train,y_train)
# 模型在測試資料集上的預測
bnb_pred = bnb.predict(X_test)
# 構建混淆矩陣
cm = pd.crosstab(bnb_pred,y_test)
# 繪製混淆矩陣圖
sns.heatmap(cm, annot = True, cmap = 'GnBu', fmt = 'd')
# 去除x軸和y軸標籤
plt.xlabel('Real')
plt.ylabel('Predict')
# 顯示圖形
plt.show()