Ⅰ 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()