keras訓(xùn)練曲線(xiàn),混淆矩陣,CNN層輸出可視化實(shí)例
訓(xùn)練曲線(xià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)練曲線(xiàn),混淆矩陣,CNN層輸出可視化實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python3中超級(jí)好用的日志模塊-loguru模塊使用詳解
loguru默認(rèn)的輸出格式是上面的內(nèi)容,有時(shí)間、級(jí)別、模塊名、行號(hào)以及日志信息,不需要手動(dòng)創(chuàng)建?logger,直接使用即可,另外其輸出還是彩色的,看起來(lái)會(huì)更加友好,這篇文章主要介紹了python3中超級(jí)好用的日志模塊-loguru模塊使用詳解,需要的朋友可以參考下2022-11-11
通過(guò)python連接Linux命令行代碼實(shí)例
這篇文章主要介紹了通過(guò)python連接Linux命令行代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
Python使用百度翻譯開(kāi)發(fā)平臺(tái)實(shí)現(xiàn)英文翻譯為中文功能示例
這篇文章主要介紹了Python使用百度翻譯開(kāi)發(fā)平臺(tái)實(shí)現(xiàn)英文翻譯為中文功能,結(jié)合實(shí)例形式分析了Python使用request請(qǐng)求與百度翻譯API接口交互實(shí)現(xiàn)翻譯功能相關(guān)操作技巧,需要的朋友可以參考下2019-08-08
python3實(shí)現(xiàn)讀取chrome瀏覽器cookie
這里給大家分享的是python3讀取chrome瀏覽器的cookie(CryptUnprotectData解密)的代碼,主要思路是讀取到的cookies被封裝成字典,可以直接給requests使用。2016-06-06
python報(bào)錯(cuò): ''list'' object has no attribute ''shape''的解決
這篇文章主要介紹了python報(bào)錯(cuò): 'list' object has no attribute 'shape'的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-07-07

