前面我介紹了可視化的一些方法以及機器學習在預測方面的應用历葛,分為分類問題(預測值是離散型)和回歸問題(預測值是連續(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ù)挖掘、機器學習纠屋、深度學習相關的電子書籍涂臣。