ML之NB:利用朴素贝叶斯NB算法(CountVectorizer+不去除停用词)对fetch_20newsgroups数据集(20类新闻文本)进行分类预测、评估

简介: ML之NB:利用朴素贝叶斯NB算法(CountVectorizer+不去除停用词)对fetch_20newsgroups数据集(20类新闻文本)进行分类预测、评估

输出结果

image.png


image.png


设计思路

image.png

核心代码

class MultinomialNB Found at: sklearn.naive_bayes

class MultinomialNB(BaseDiscreteNB):

   """

   Naive Bayes classifier for multinomial models

 

   The multinomial Naive Bayes classifier is suitable for classification with

   discrete features (e.g., word counts for text classification). The

   multinomial distribution normally requires integer feature counts. However,

   in practice, fractional counts such as tf-idf may also work.

 

   Read more in the :ref:`User Guide <multinomial_naive_bayes>`.

 

   Parameters

   ----------

   alpha : float, optional (default=1.0)

   Additive (Laplace/Lidstone) smoothing parameter

   (0 for no smoothing).

 

   fit_prior : boolean, optional (default=True)

   Whether to learn class prior probabilities or not.

   If false, a uniform prior will be used.

 

   class_prior : array-like, size (n_classes,), optional (default=None)

   Prior probabilities of the classes. If specified the priors are not

   adjusted according to the data.

 

   Attributes

   ----------

   class_log_prior_ : array, shape (n_classes, )

   Smoothed empirical log probability for each class.

 

   intercept_ : property

   Mirrors ``class_log_prior_`` for interpreting MultinomialNB

   as a linear model.

 

   feature_log_prob_ : array, shape (n_classes, n_features)

   Empirical log probability of features

   given a class, ``P(x_i|y)``.

 

   coef_ : property

   Mirrors ``feature_log_prob_`` for interpreting MultinomialNB

   as a linear model.

 

   class_count_ : array, shape (n_classes,)

   Number of samples encountered for each class during fitting. This

   value is weighted by the sample weight when provided.

 

   feature_count_ : array, shape (n_classes, n_features)

   Number of samples encountered for each (class, feature)

   during fitting. This value is weighted by the sample weight when

   provided.

 

   Examples

   --------

   >>> import numpy as np

   >>> X = np.random.randint(5, size=(6, 100))

   >>> y = np.array([1, 2, 3, 4, 5, 6])

   >>> from sklearn.naive_bayes import MultinomialNB

   >>> clf = MultinomialNB()

   >>> clf.fit(X, y)

   MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)

   >>> print(clf.predict(X[2:3]))

   [3]

 

   Notes

   -----

   For the rationale behind the names `coef_` and `intercept_`, i.e.

   naive Bayes as a linear classifier, see J. Rennie et al. (2003),

   Tackling the poor assumptions of naive Bayes text classifiers, ICML.

 

   References

   ----------

   C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to

   Information Retrieval. Cambridge University Press, pp. 234-265.

  http://nlp.stanford.edu/IR-book/html/htmledition/naive-bayes-text-

    classification-1.html

   """

   def __init__(self, alpha=1.0, fit_prior=True, class_prior=None):

       self.alpha = alpha

       self.fit_prior = fit_prior

       self.class_prior = class_prior

 

   def _count(self, X, Y):

       """Count and smooth feature occurrences."""

       if np.any((X.data if issparse(X) else X) < 0):

           raise ValueError("Input X must be non-negative")

       self.feature_count_ += safe_sparse_dot(Y.T, X)

       self.class_count_ += Y.sum(axis=0)

 

   def _update_feature_log_prob(self, alpha):

       """Apply smoothing to raw counts and recompute log probabilities"""

       smoothed_fc = self.feature_count_ + alpha

       smoothed_cc = smoothed_fc.sum(axis=1)

       self.feature_log_prob_ = np.log(smoothed_fc) - np.log(smoothed_cc.

        reshape(-1, 1))

 

   def _joint_log_likelihood(self, X):

       """Calculate the posterior log probability of the samples X"""

       check_is_fitted(self, "classes_")

       X = check_array(X, accept_sparse='csr')

       return safe_sparse_dot(X, self.feature_log_prob_.T) + self.class_log_prior_


相关文章
|
3天前
|
机器学习/深度学习 算法
【机器学习】比较朴素贝叶斯算法与逻辑回归算法
【5月更文挑战第10天】【机器学习】比较朴素贝叶斯算法与逻辑回归算法
|
15天前
|
算法 数据可视化 前端开发
r语言有限正态混合模型EM算法的分层聚类、分类和密度估计及可视化(下)
r语言有限正态混合模型EM算法的分层聚类、分类和密度估计及可视化
|
15天前
|
算法 数据可视化 数据挖掘
r语言有限正态混合模型EM算法的分层聚类、分类和密度估计及可视化(上)
r语言有限正态混合模型EM算法的分层聚类、分类和密度估计及可视化
|
17天前
|
编解码 算法 数据可视化
【视频】时间序列分类方法:动态时间规整算法DTW和R语言实现
【视频】时间序列分类方法:动态时间规整算法DTW和R语言实现
|
17天前
|
机器学习/深度学习 数据采集 算法
共享单车需求量数据用CART决策树、随机森林以及XGBOOST算法登记分类及影响因素分析
共享单车需求量数据用CART决策树、随机森林以及XGBOOST算法登记分类及影响因素分析
|
3天前
|
算法 数据安全/隐私保护 计算机视觉
基于二维CS-SCHT变换和LABS方法的水印嵌入和提取算法matlab仿真
该内容包括一个算法的运行展示和详细步骤,使用了MATLAB2022a。算法涉及水印嵌入和提取,利用LAB色彩空间可能用于隐藏水印。水印通过二维CS-SCHT变换、低频系数处理和特定解码策略来提取。代码段展示了水印置乱、图像处理(如噪声、旋转、剪切等攻击)以及水印的逆置乱和提取过程。最后,计算并保存了比特率,用于评估水印的稳健性。
|
4天前
|
存储 算法 数据可视化
基于harris角点和RANSAC算法的图像拼接matlab仿真
本文介绍了使用MATLAB2022a进行图像拼接的流程,涉及Harris角点检测和RANSAC算法。Harris角点检测寻找图像中局部曲率变化显著的点,RANSAC则用于排除噪声和异常点,找到最佳匹配。核心程序包括自定义的Harris角点计算函数,RANSAC参数设置,以及匹配点的可视化和仿射变换矩阵计算,最终生成全景图像。
|
4天前
|
算法 Serverless
m基于遗传优化的LDPC码NMS译码算法最优归一化参数计算和误码率matlab仿真
MATLAB 2022a仿真实现了遗传优化的归一化最小和(NMS)译码算法,应用于低密度奇偶校验(LDPC)码。结果显示了遗传优化的迭代过程和误码率对比。遗传算法通过选择、交叉和变异操作寻找最佳归一化因子,以提升NMS译码性能。核心程序包括迭代优化、目标函数计算及性能绘图。最终,展示了SNR与误码率的关系,并保存了关键数据。
13 1
|
5天前
|
算法 调度
考虑需求响应的微网优化调度模型【粒子群算法】【matlab】
考虑需求响应的微网优化调度模型【粒子群算法】【matlab】
|
5天前
|
运维 算法
基于改进遗传算法的配电网故障定位(matlab代码)
基于改进遗传算法的配电网故障定位(matlab代码)