多类分类和概率预测

Multiclass Classification and probability prediction

import pandas as pd
import numpy
from sklearn import cross_validation
from sklearn.naive_bayes import GaussianNB

fi = "df.csv"
# Open the file for reading and read in data
file_handler = open(fi, "r")
data = pd.read_csv(file_handler, sep=",")
file_handler.close()

# split the data into training and test data
train, test = cross_validation.train_test_split(data,test_size=0.6, random_state=0)
# initialise Gaussian Naive Bayes
naive_b = GaussianNB()


train_features = train.ix[:,0:127]
train_label = train.iloc[:,127]

test_features = test.ix[:,0:127]
test_label = test.iloc[:,127]

naive_b.fit(train_features, train_label)
test_data = pd.concat([test_features, test_label], axis=1)
test_data["p_malw"] = naive_b.predict_proba(test_features)

print "test_data\n",test_data["p_malw"]
print "Accuracy:", naive_b.score(test_features,test_label)

我编写这段代码是为了接受来自 128 列的 csv 文件的输入,其中 127 列是特征,第 128 列是 class 标签。

我想预测样本属于每个 class 的概率(有 5 个 classes (1-5))并将其打印在矩阵中并确定 class 基于预测的样本。 predict_proba() 未提供所需的输出。请建议所需的更改。

GaussianNB.predict_proba returns 模型中每个 class 的样本概率。在您的情况下,它应该 return 一个包含五列且行数与测试数据相同的结果。您可以使用 naive_b.classes_ 验证哪个列对应于哪个 class 。因此,不清楚您为什么说这不是所需的输出。也许,您的问题来自您将 predict proba 的输出分配给数据框列这一事实。尝试:

pred_prob = naive_b.predict_proba(test_features)

而不是

test_data["p_malw"] = naive_b.predict_proba(test_features)

并使用 pred_prob.shape 验证其形状。第二个维度应该是5.

如果你想要每个样本的预测标签,你可以使用预测方法,然后使用混淆矩阵来查看有多少标签被正确预测。

from sklearn.metrics import confusion_matrix

naive_B.fit(train_features, train_label)

pred_label = naive_B.predict(test_features)

confusion_m = confusion_matrix(test_label, pred_label)
confusion_m

这里有一些有用的读物​​。

sklearn GaussianNB - http://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html#sklearn.naive_bayes.GaussianNB.predict_proba

sklearn confusion_matrix - http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html