keras訓(xùn)練曲線,混淆矩陣,CNN層輸出可視化實(shí)例
訓(xùn)練曲線
def show_train_history(train_history, train_metrics, validation_metrics): plt.plot(train_history.history[train_metrics]) plt.plot(train_history.history[validation_metrics]) plt.title('Train History') plt.ylabel(train_metrics) plt.xlabel('Epoch') plt.legend(['train', 'validation'], loc='upper left') # 顯示訓(xùn)練過(guò)程 def plot(history): plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) show_train_history(history, 'acc', 'val_acc') plt.subplot(1, 2, 2) show_train_history(history, 'loss', 'val_loss') plt.show()
效果:
plot(history)
混淆矩陣
def plot_confusion_matrix(cm, classes, title='Confusion matrix', cmap=plt.cm.jet): cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, '{:.2f}'.format(cm[i, j]), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() # 顯示混淆矩陣 def plot_confuse(model, x_val, y_val): predictions = model.predict_classes(x_val) truelabel = y_val.argmax(axis=-1) # 將one-hot轉(zhuǎn)化為label conf_mat = confusion_matrix(y_true=truelabel, y_pred=predictions) plt.figure() plot_confusion_matrix(conf_mat, range(np.max(truelabel)+1))
其中y_val以one-hot形式輸入
效果:
x_val.shape # (25838, 48, 48, 1) y_val.shape # (25838, 7) plot_confuse(model, x_val, y_val)
CNN層輸出可視化
# 卷積網(wǎng)絡(luò)可視化 def visual(model, data, num_layer=1): # data:圖像array數(shù)據(jù) # layer:第n層的輸出 data = np.expand_dims(data, axis=0) # 開(kāi)頭加一維 layer = keras.backend.function([model.layers[0].input], [model.layers[num_layer].output]) f1 = layer([data])[0] num = f1.shape[-1] plt.figure(figsize=(8, 8)) for i in range(num): plt.subplot(np.ceil(np.sqrt(num)), np.ceil(np.sqrt(num)), i+1) plt.imshow(f1[0, :, :, i] * 255, cmap='gray') plt.axis('off') plt.show()
num_layer : 顯示第n層的輸出
效果
visual(model, data, 1) # 卷積層 visual(model, data, 2) # 激活層 visual(model, data, 3) # 規(guī)范化層 visual(model, data, 4) # 池化層
補(bǔ)充知識(shí):Python sklearn.cross_validation.train_test_split及混淆矩陣實(shí)現(xiàn)
sklearn.cross_validation.train_test_split隨機(jī)劃分訓(xùn)練集和測(cè)試集
一般形式:
train_test_split是交叉驗(yàn)證中常用的函數(shù),功能是從樣本中隨機(jī)的按比例選取train data和testdata,形式為:
X_train,X_test, y_train, y_test =
cross_validation.train_test_split(train_data,train_target,test_size=0.4, random_state=0)
參數(shù)解釋?zhuān)?/strong>
train_data:所要?jiǎng)澐值臉颖咎卣骷?/p>
train_target:所要?jiǎng)澐值臉颖窘Y(jié)果
test_size:樣本占比,如果是整數(shù)的話(huà)就是樣本的數(shù)量
random_state:是隨機(jī)數(shù)的種子。
隨機(jī)數(shù)種子:其實(shí)就是該組隨機(jī)數(shù)的編號(hào),在需要重復(fù)試驗(yàn)的時(shí)候,保證得到一組一樣的隨機(jī)數(shù)。比如你每次都填1,其他參數(shù)一樣的情況下你得到的隨機(jī)數(shù)組是一樣的。但填0或不填,每次都會(huì)不一樣。隨機(jī)數(shù)的產(chǎn)生取決于種子,隨機(jī)數(shù)和種子之間的關(guān)系遵從以下兩個(gè)規(guī)則:種子不同,產(chǎn)生不同的隨機(jī)數(shù);種子相同,即使實(shí)例不同也產(chǎn)生相同的隨機(jī)數(shù)。
示例
fromsklearn.cross_validation import train_test_split train= loan_data.iloc[0: 55596, :] test= loan_data.iloc[55596:, :] # 避免過(guò)擬合,采用交叉驗(yàn)證,驗(yàn)證集占訓(xùn)練集20%,固定隨機(jī)種子(random_state) train_X,test_X, train_y, test_y = train_test_split(train, target, test_size = 0.2, random_state = 0) train_y= train_y['label'] test_y= test_y['label']
plot_confusion_matrix.py(混淆矩陣實(shí)現(xiàn)實(shí)例)
print(__doc__) import numpy as np import matplotlib.pyplot as plt from sklearn import svm, datasets from sklearn.cross_validation import train_test_split from sklearn.metrics import confusion_matrix # import some data to play with iris = datasets.load_iris() X = iris.data y = iris.target # Split the data into a training set and a test set X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Run classifier, using a model that is too regularized (C too low) to see # the impact on the results classifier = svm.SVC(kernel='linear', C=0.01) y_pred = classifier.fit(X_train, y_train).predict(X_test) def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues): plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(iris.target_names)) plt.xticks(tick_marks, iris.target_names, rotation=45) plt.yticks(tick_marks, iris.target_names) plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') # Compute confusion matrix cm = confusion_matrix(y_test, y_pred) np.set_printoptions(precision=2) print('Confusion matrix, without normalization') print(cm) plt.figure() plot_confusion_matrix(cm) # Normalize the confusion matrix by row (i.e by the number of samples # in each class) cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print('Normalized confusion matrix') print(cm_normalized) plt.figure() plot_confusion_matrix(cm_normalized, title='Normalized confusion matrix') plt.show()
以上這篇keras訓(xùn)練曲線,混淆矩陣,CNN層輸出可視化實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Django之PopUp的具體實(shí)現(xiàn)方法
今天小編就為大家分享一篇Django之PopUp的具體實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-08-08Pandas實(shí)現(xiàn)解析JSON數(shù)據(jù)與導(dǎo)出的示例詳解
其實(shí)使用pandas解析JSON?Dataset要方便得多,所以這篇文章主要為大家介紹了Pandas實(shí)現(xiàn)解析JSON數(shù)據(jù)與導(dǎo)出的具體方法,需要的小伙伴可以收藏一下2023-07-07Python+騰訊云服務(wù)器實(shí)現(xiàn)每日自動(dòng)健康打卡
本文主要介紹了通過(guò)Python+騰訊云服務(wù)器實(shí)現(xiàn)每日自動(dòng)健康打卡,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12Python解方程組 scipy.optimize.fsolve()函數(shù)如何求解帶有循環(huán)求和的方程式
這篇文章主要介紹了Python解方程組 scipy.optimize.fsolve()函數(shù)如何求解帶有循環(huán)求和的方程式,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-06-06Python實(shí)現(xiàn)DHCP請(qǐng)求方式
這篇文章主要介紹了Python實(shí)現(xiàn)DHCP請(qǐng)求方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06python list的index()和find()的實(shí)現(xiàn)
這篇文章主要介紹了python list的index()和find()的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11python3實(shí)現(xiàn)無(wú)權(quán)最短路徑的方法
這篇文章主要介紹了python3實(shí)現(xiàn)無(wú)權(quán)最短路徑的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05