Python圖像識別實戰(zhàn)(五):卷積神經(jīng)網(wǎng)絡CNN模型圖像二分類預測結(jié)果評價(附源碼和實現(xiàn)效果)

前面我介紹了可視化的一些方法以及機器學習在預測方面的應用历葛,分為分類問題(預測值是離散型)和回歸問題(預測值是連續(xù)型)(具體見之前的文章)缤剧。

從本期開始吹艇,我將做一個關于圖像識別的系列文章夹攒,讓讀者慢慢理解python進行圖像識別的過程晒骇、原理和方法,每一篇文章從實現(xiàn)功能镰吆、實現(xiàn)代碼帘撰、實現(xiàn)效果三個方面進行展示。

實現(xiàn)功能:

卷積神經(jīng)網(wǎng)絡CNN模型圖像二分類預測結(jié)果評價

實現(xiàn)代碼:

import os

from PILimport Image

import numpyas np

import matplotlib.pyplotas plt

import tensorflowas tf

from tensorflow.kerasimport datasets, layers, models

from collectionsimport Counter

from sklearn.metricsimport precision_recall_curve

from sklearn.metricsimport roc_curve, auc

from sklearn.metricsimport roc_auc_score

import itertools

from pylabimport mpl

import seabornas sns

class Solution():

#==================讀取圖片=================================

? ? def read_image(self,paths):

os.listdir(paths)

filelist = []

for root, dirs, filesin os.walk(paths):

for filein files:

if os.path.splitext(file)[1] ==".png":

filelist.append(os.path.join(root, file))

print(filelist)

return filelist

#==================圖片數(shù)據(jù)轉(zhuǎn)化為數(shù)組==========================

? ? def im_array(self,paths):

M=[]

for filenamein paths:

im=Image.open(filename)

im_L=im.convert("L")#模式L

? ? ? ? ? ? Core=im_L.getdata()

arr1=np.array(Core,dtype='float32')/255.0

? ? ? ? ? ? list_img=arr1.tolist()

M.extend(list_img)

return M

def CNN_model(self,train_images, train_lables):

# ============構(gòu)建卷積神經(jīng)網(wǎng)絡并保存=========================

? ? ? ? model = models.Sequential()

model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(128, 128, 1)))# 過濾器個數(shù)万皿,卷積核尺寸摧找,激活函數(shù),輸入形狀

? ? ? ? model.add(layers.MaxPooling2D((2, 2)))# 池化層

? ? ? ? model.add(layers.Conv2D(64, (3, 3), activation='relu'))

model.add(layers.MaxPooling2D((2, 2)))

model.add(layers.Conv2D(64, (3, 3), activation='relu'))

model.add(layers.Flatten())# 降維

? ? ? ? model.add(layers.Dense(64, activation='relu'))# 全連接層

? ? ? ? model.add(layers.Dense(2, activation='softmax'))# 注意這里參數(shù)牢硅,我只有兩類圖片蹬耘,所以是2.

? ? ? ? model.summary()# 顯示模型的架構(gòu)

? ? ? ? model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

return model

if __name__=='__main__':

Object1=Solution()

# =================數(shù)據(jù)讀取===============

? ? path1="D:\DCTDV2\dataset\\train\\"

? ? test1 ="D:\DCTDV2\dataset\\test\\"

? ? pathDir = os.listdir(path1)

print(pathDir)

pathDir=pathDir[1:5]

print(pathDir)

for ain pathDir:

path2=path1+a

test2=test1+a

filelist_1=Object1.read_image(path1+"Norm")

filelist_2=Object1.read_image(path2)

filelist_all=filelist_1+filelist_2

M=Object1.im_array(filelist_all)

train_images=np.array(M).reshape(len(filelist_all),128,128)#輸出驗證一下(400, 128, 128)

? ? ? ? label=[0]*len(filelist_1)+[1]*len(filelist_2)

train_lables=np.array(label)#數(shù)據(jù)標簽

? ? ? ? train_images = train_images[..., np.newaxis]#數(shù)據(jù)圖片

? ? ? ? print(train_images.shape)#輸出驗證一下(400, 128, 128, 1)

? ? ? ? print(train_lables.shape)

# ===================準備測試數(shù)據(jù)==================

? ? ? ? filelist_1T = Object1.read_image(test1+"Norm")

filelist_2T = Object1.read_image(test2)

filelist_allT = filelist_1T + filelist_2T

print(filelist_allT)

N = Object1.im_array(filelist_allT)

dict_label = {0:'norm', 1:'IgaK'}

test_images = np.array(N).reshape(len(filelist_allT), 128, 128)

label = [0] *len(filelist_1T) + [1] *len(filelist_2T)

test_lables = np.array(label)# 數(shù)據(jù)標簽

? ? ? ? test_images = test_images[..., np.newaxis]# 數(shù)據(jù)圖片

? ? ? ? print(test_images.shape)# 輸出驗證一下(100, 128, 128, 1)

? ? ? ? print(test_lables.shape)

# #===================訓練模型=============

? ? ? ? model=Object1.CNN_model(train_images, train_lables)

CnnModel=model.fit(train_images, train_lables, epochs=20)

# model.save('D:\電池條帶V2\model\my_model.h5')? # 保存為h5模型

? ? ? ? # tf.keras.models.save_model(model,"F:\python\moxing\model")#這樣是pb模型

? ? ? ? print("模型保存成功!")

# history列表

? ? ? ? print(CnnModel.history.keys())

font = {'family':'Times New Roman','size':12,}

sns.set(font_scale=1.2)

plt.plot(CnnModel.history['loss'])

plt.title('model loss')

plt.ylabel('loss')

plt.xlabel('epoch')

plt.savefig('D:\\DCTDV2\\result\\V1\\loss' +"\\" +'%s.tif' % a,bbox_inches='tight',dpi=600)

plt.show()

plt.plot(CnnModel.history['accuracy'])

plt.title('model accuracy')

plt.ylabel('accuracy')

plt.xlabel('epoch')

plt.savefig('D:\\DCTDV2\\result\\V1\\accuracy' +"\\" +'%s.tif' % a,bbox_inches='tight',dpi=600)

plt.show()

# #===================預測圖像=============

? ? ? ? predict_label=[]

prob_label=[]

for iin test_images:

i=np.array([i])

predictions_single=model.predict(i)

print(np.argmax(predictions_single))

out_c_1 = np.array(predictions_single)[:, 1]

prob_label.extend(out_c_1)

predict_label.append(np.argmax(predictions_single))

print(prob_label)

print(predict_label)

print(list(test_lables))

count = Counter(predict_label)

print(count)

TP = FP = FN = TN =0

? ? ? ? for iin range(len(predict_label)):

if predict_label[i]==1:

if list(test_lables)[i]==1:

TP=TP+1

? ? ? ? ? ? ? ? elif list(test_lables)[i]==0:

FP=FP+1

? ? ? ? ? ? elif predict_label[i]==0:

if list(test_lables)[i]==1:

FN=FN+1

? ? ? ? ? ? ? ? elif list(test_lables)[i]==0:

TN=TN+1

? ? ? ? print(TP,FP,FN,TN)

deathc_recall=TP/(TP+FN)

savec_recall=TN/(FP+TN)

print(deathc_recall)

print(savec_recall)

print("--------------------")

cm = np.arange(4).reshape(2, 2)

cm[0, 0] = TN

cm[0, 1] = FP

cm[1, 0] = FN

cm[1, 1] = TP

classes = [0, 1]

plt.figure()

plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)

plt.title('Confusion matrix')

tick_marks = np.arange(len(classes))

plt.xticks(tick_marks, classes, rotation=0)

plt.yticks(tick_marks, classes)

thresh = cm.max() /2.

? ? ? ? for i, jin itertools.product(range(cm.shape[0]), range(cm.shape[1])):

plt.text(j, i, cm[i, j], horizontalalignment="center", color="red" if cm[i, j] > threshelse "black")

plt.tight_layout()

plt.ylabel('True label')

plt.xlabel('Predicted label')

plt.savefig('D:\\DCTDV2\\result\\V1\\cm' +"\\" +'%s.tif' % a,bbox_inches='tight',dpi=600)

plt.show()

fpr, tpr, thresholds = roc_curve(list(test_lables), prob_label, pos_label=1)

Auc_score = roc_auc_score(list(test_lables), predict_label)

Auc = auc(fpr, tpr)

print(Auc_score, Auc)

plt.plot(fpr, tpr, 'b', label='AUC = %0.2f' % Auc)# 生成ROC曲線

? ? ? ? plt.legend(loc='lower right')

plt.plot([0, 1], [0, 1], 'r--')

plt.xlim([0, 1])

plt.ylim([0, 1])

plt.ylabel('True positive rate')

plt.xlabel('False positive rate')

plt.savefig('D:\\DCTDV2\\result\\V1\\roc' +"\\" +'%s.tif' % a,bbox_inches='tight',dpi=600)

plt.show()

plt.figure()

precision, recall, thresholds = precision_recall_curve(list(test_lables), predict_label)

plt.title('Precision/Recall Curve')# give plot a title

? ? ? ? plt.xlabel('Recall')# make axis labels

? ? ? ? plt.ylabel('Precision')

plt.plot(precision, recall)

plt.savefig('D:\\DCTDV2\\result\\V1\\pr' +"\\" +'%s.tif' % a,bbox_inches='tight',dpi=600)

plt.show()

實現(xiàn)效果:

由于數(shù)據(jù)為非公開數(shù)據(jù)减余,僅展示幾個圖像的效果综苔,有問題可以后臺聯(lián)系我。

本人讀研期間發(fā)表5篇SCI數(shù)據(jù)挖掘相關論文位岔,現(xiàn)在在某研究院從事數(shù)據(jù)挖掘相關工作如筛,對數(shù)據(jù)挖掘有一定的認知和理解,會不定期分享一些關于python機器學習抒抬、深度學習杨刨、數(shù)據(jù)挖掘基礎知識與案例。 致力于只做原創(chuàng)擦剑,以最簡單的方式理解和學習妖胀,關注我一起交流成長。 關注V訂閱號:數(shù)據(jù)雜壇可在后臺聯(lián)系我獲取相關數(shù)據(jù)集和源碼惠勒,送有關數(shù)據(jù)分析赚抡、數(shù)據(jù)挖掘、機器學習纠屋、深度學習相關的電子書籍涂臣。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市巾遭,隨后出現(xiàn)的幾起案子肉康,更是在濱河造成了極大的恐慌,老刑警劉巖灼舍,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異涨薪,居然都是意外死亡骑素,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門刚夺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來献丑,“玉大人末捣,你說我怎么就攤上這事〈撮希” “怎么了箩做?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長妥畏。 經(jīng)常有香客問我邦邦,道長,這世上最難降的妖魔是什么醉蚁? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任燃辖,我火速辦了婚禮,結(jié)果婚禮上网棍,老公的妹妹穿的比我還像新娘黔龟。我一直安慰自己,他們只是感情好滥玷,可當我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布氏身。 她就那樣靜靜地躺著,像睡著了一般惑畴。 火紅的嫁衣襯著肌膚如雪蛋欣。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天桨菜,我揣著相機與錄音豁状,去河邊找鬼。 笑死倒得,一個胖子當著我的面吹牛泻红,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播霞掺,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼谊路,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了菩彬?” 一聲冷哼從身側(cè)響起缠劝,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎骗灶,沒想到半個月后惨恭,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡耙旦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年脱羡,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡锉罐,死狀恐怖帆竹,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情脓规,我是刑警寧澤栽连,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站侨舆,受9級特大地震影響秒紧,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜态罪,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一噩茄、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧复颈,春花似錦绩聘、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至帜讲,卻和暖如春衅谷,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背似将。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工获黔, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人在验。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓玷氏,卻偏偏與公主長得像,于是被迫代替她去往敵國和親腋舌。 傳聞我的和親對象是個殘疾皇子盏触,可洞房花燭夜當晚...
    茶點故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容