Ⅰ python3.5做分类时,混淆矩阵加在哪一步
preface:做着最近的任务,对数据处理,做些简单的提特征,用机器学习算法跑下程序得出结果,看看哪些特征的组合较好,这一系列流程必然要用到很多函数,故将自己常用函数记录上。应该说这些函数基本上都会用到,像是数据预处理,处理完了后特征提取、降维、训练预测、通过混淆矩阵看分类效果,得出报告。
1.输入
从数据集开始,提取特征转化为有标签的数据集,转为向量。拆分成训练集和测试集,这里不多讲,在上一篇博客中谈到用StratifiedKFold()函数即可。在训练集中有data和target开始。
2.处理
[python]view plain
defmy_preprocessing(train_data):
X_normalized=preprocessing.normalize(train_data,norm="l2",axis=0)#使用l2范式,对特征列进行正则
returnX_normalized
defmy_feature_selection(data,target):
fromsklearn.feature_selectionimportSelectKBest
fromsklearn.feature_selectionimportchi2
data_new=SelectKBest(chi2,k=50).fit_transform(data,target)
returndata_new
defmy_PCA(data):#datawithouttarget,justtraindata,withoutraintarget.
pca_sklearn=decomposition.PCA()
pca_sklearn.fit(data)
main_var=pca_sklearn.explained_variance_
printsum(main_var)*0.9
importmatplotlib.pyplotasplt
n=15
plt.plot(main_var[:n])
plt.show()
defclf_train(data,target):
fromsklearnimportsvm
#fromsklearn.linear_modelimportLogisticRegression
clf=svm.SVC(C=100,kernel="rbf",gamma=0.001)
clf.fit(data,target)
#clf_LR=LogisticRegression()
#clf_LR.fit(x_train,y_train)
#y_pred_LR=clf_LR.predict(x_test)
returnclf
defmy_confusion_matrix(y_true,y_pred):
fromsklearn.metricsimportconfusion_matrix
labels=list(set(y_true))
conf_mat=confusion_matrix(y_true,y_pred,labels=labels)
print"confusion_matrix(leftlabels:y_true,uplabels:y_pred):"
print"labels ",
foriinrange(len(labels)):
printlabels[i]," ",
foriinrange(len(conf_mat)):
printi," ",
forjinrange(len(conf_mat[i])):
printconf_mat[i][j],' ',
defmy_classification_report(y_true,y_pred):
fromsklearn.metricsimportclassification_report
print"classification_report(left:labels):"
printclassification_report(y_true,y_pred)
主要使用sklearn的preprocessing函数中的normalize()函数,默认参数为l2范式,对特征列进行正则处理。即每一个样例,处理标签,每行的平方和为1.
my_feature_selection()函数:
使用sklearn的feature_selection函数中SelectKBest()函数和chi2()函数,若是用词袋提取了很多维的稀疏特征,有必要使用卡方选取前k个有效的特征。
my_PCA()函数:
主要用来观察前多少个特征是主要特征,并且画图。看看前多少个特征占据主要部分。
clf_train()函数:
可用多种机器学习算法,如SVM, LR, RF, GBDT等等很多,其中像SVM需要调参数的,有专门调试参数的函数如StratifiedKFold()(见前几篇博客)。以达到最优。
my_confusion_matrix()函数:
主要是针对预测出来的结果,和原来的结果对比,算出混淆矩阵,不必自己计算。其对每个类别的混淆矩阵都计算出来了,并且labels参数默认是排序了的。
my_classification_report()函数:
主要通过sklearn.metrics函数中的classification_report()函数,针对每个类别给出详细的准确率、召回率和F-值这三个参数和宏平均值,用来评价算法好坏。另外ROC曲线的话,需要是对二分类才可以。多类别似乎不行。
Ⅱ 为什么我觉得python画图非常不清晰呢
这个可以通过设置DPI的大小来设置的,估计你用的是默认值吧
显示的话,可以试试figure中设置dpi
保存的话,可以试试 savefig中设置dpi
Ⅲ python矩阵画图
积分区域是个正方形,关于x轴对称,而x²y关于y是奇函数,所以积分完为零,就只剩下x的绝对值的积分了。
|x|关于x是偶函数,而积分区域也关于y轴对称,所以原积分就等于对y轴右侧部分积分的两倍,然后|x|可认为是|x|·1,也关于y是偶函数,则在整个区域对|x|的积分,就等于对第一象限部分积分的四倍,也这道题就变成:
积分区域为x+y=1和x轴,y轴围成的区域
在这一区域对x进行二重积分,然后乘4
Ⅳ python是否有绘制混淆矩阵的函数
肯定是公式有错,NaN是not a number的意思,肯定是某个地方写错了。不过,既然是matlab编程,为什么不使用神经网络工具...
Ⅳ python是否有绘制混淆矩阵的函数,怎么来实现
#-*-coding:UTF-8-*-
"""绘制混淆矩阵图"""
importmatplotlib.pyplotasplt
fromsklearn.metricsimportconfusion_matrix
defconfusion_matrix_plot_matplotlib(y_truth,y_predict,cmap=plt.cm.Blues):
"""Matplotlib绘制混淆矩阵图
parameters
----------
y_truth:真实的y的值,1darray
y_predict:预测的y的值,1darray
cmap:画混淆矩阵图的配色风格,使用cm.Blues,更多风格请参考官网
"""
cm=confusion_matrix(y_truth,y_predict)
plt.matshow(cm,cmap=cmap)#混淆矩阵图
plt.colorbar()#颜色标签
forxinrange(len(cm)):#数据标签
foryinrange(len(cm)):
plt.annotate(cm[x,y],xy=(x,y),horizontalalignment='center',verticalalignment='center')
plt.ylabel('Truelabel')#坐标轴标签
plt.xlabel('Predictedlabel')#坐标轴标签
plt.show()#显示作图结果
if__name__=='__main__':
y_truth=[1,0,1,1,1,1,1,1,1,1,0,0,0,0,0]
y_predict=[1,0,0,1,0,1,1,1,1,1,0,1,0,1,0]
confusion_matrix_plot_matplotlib(y_truth,y_predict)
Ⅵ python为什么画布上画图看不见
这基本上是因为你创建画布后没有用创建的画布绘制图
Ⅶ 关于python 画图的问题,我有一串码完全看不懂,麻烦大家帮我看一下。
首先,确定三角形的位置需要三个点。代码里给出的myPoints = [[-100,-50],[0,100],[100,-50]]就是这三个点的位置,你可以在坐标轴里画一个x,y轴,找一下就知道了。如果只是想让三角形倒过来,就重新给它三个点[[-100,100],[100,100],[0,-50]]。
其次,三角形的边长,就是两个点之间的直线距离。从代码里可以看到,(-100,-50),(100,-50)这两个点是在同一条横向的线上,它们的距离是200.所以想把三角形的尺寸扩大两倍,就需要把边长扩大,给出新的点[[-200,200],[200,200],[0,-100]]
综上,修改main函数中的myPoints,即可达到你的需求:倒置三角形,尺寸扩大两倍
def main():
myTurtle = turtle.Turtle()
myWin = turtle.Screen()
myPoints = [[-200,200],[200,200],[0,-100]]
sierpinski(myPoints,3,myTurtle)
myWin.exitonclick()
再解释几个问题:
myTurtle.up() 和myTurtle.down()
可以把myTurtle看做是画笔,myTurtle.up()就表示把画笔从画布上抬起,也就是不跟画布接触。myTurtle.down()也就可以看成是画笔跟画布接触。
sierpinski是定义的一个递归画三角形的方法,degree可以理解成递归的深度,也就是说在一个三角形内可以再画几个小三角形(不包括中间的三角形)。代码里degree 是3,你可以运行一下代码,看看效果。
希望能帮到你,有疑问请追问!
Ⅷ 如何在Python写的混淆矩阵
将labels、y_true 、y_pred替换为你自己的数据即可。
Ⅸ 如何用python画好confusion matrix
在做分类的时候,经常需要画混淆矩阵,下面我们使用python的matplotlib包,scikit-learning机器学习库也同样提供了例子:, 但是这样的图并不能满足我们的要求,
首先是刻度的显示是在方格的中间,这需要隐藏刻度,其次是如何把每个label显示在每个方块的中间, 其次是如何在每个方格中显示accuracy数值, 最后是如何在横坐标和纵坐标显示label的名字,在label name比较长的时候,如何处理显示问题。
[python] view plain
'''''compute confusion matrix
labels.txt: contain label name.
predict.txt: predict_label true_label
'''
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
import numpy as np
#load labels.
labels = []
file = open('labels.txt', 'r')
lines = file.readlines()
for line in lines:
labels.append(line.strip())
file.close()
y_true = []
y_pred = []
#load true and predict labels.
file = open('predict.txt', 'r')
lines = file.readlines()
for line in lines:
y_true.append(int(line.split(" ")[1].strip()))
y_pred.append(int(line.split(" ")[0].strip()))
file.close()
tick_marks = np.array(range(len(labels))) + 0.5
def plot_confusion_matrix(cm, title='Confusion Matrix', cmap = plt.cm.binary):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
xlocations = np.array(range(len(labels)))
plt.xticks(xlocations, labels, rotation=90)
plt.yticks(xlocations, labels)
plt.ylabel('True label')
plt.xlabel('Predicted label')
cm = confusion_matrix(y_true, y_pred)
print cm
np.set_printoptions(precision=2)
cm_normalized = cm.astype('float')/cm.sum(axis=1)[:, np.newaxis]
print cm_normalized
plt.figure(figsize=(12,8), dpi=120)
#set the fontsize of label.
#for label in plt.gca().xaxis.get_ticklabels():
# label.set_fontsize(8)
#text portion
ind_array = np.arange(len(labels))
x, y = np.meshgrid(ind_array, ind_array)
for x_val, y_val in zip(x.flatten(), y.flatten()):
c = cm_normalized[y_val][x_val]
if (c > 0.01):
plt.text(x_val, y_val, "%0.2f" %(c,), color='red', fontsize=7, va='center', ha='center')
#offset the tick
plt.gca().set_xticks(tick_marks, minor=True)
plt.gca().set_yticks(tick_marks, minor=True)
plt.gca().xaxis.set_ticks_position('none')
plt.gca().yaxis.set_ticks_position('none')
plt.grid(True, which='minor', linestyle='-')
plt.gcf().subplots_adjust(bottom=0.15)
plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix')
#show confusion matrix
plt.show()