keras绘制acc和loss曲线图实例


Posted in Python onJune 15, 2020

我就废话不多说了,大家还是直接看代码吧!

#加载keras模块
from __future__ import print_function
import numpy as np
np.random.seed(1337) # for reproducibility

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD, Adam, RMSprop
from keras.utils import np_utils
import matplotlib.pyplot as plt
%matplotlib inline

#写一个LossHistory类,保存loss和acc
class LossHistory(keras.callbacks.Callback):
 def on_train_begin(self, logs={}):
  self.losses = {'batch':[], 'epoch':[]}
  self.accuracy = {'batch':[], 'epoch':[]}
  self.val_loss = {'batch':[], 'epoch':[]}
  self.val_acc = {'batch':[], 'epoch':[]}

 def on_batch_end(self, batch, logs={}):
  self.losses['batch'].append(logs.get('loss'))
  self.accuracy['batch'].append(logs.get('acc'))
  self.val_loss['batch'].append(logs.get('val_loss'))
  self.val_acc['batch'].append(logs.get('val_acc'))

 def on_epoch_end(self, batch, logs={}):
  self.losses['epoch'].append(logs.get('loss'))
  self.accuracy['epoch'].append(logs.get('acc'))
  self.val_loss['epoch'].append(logs.get('val_loss'))
  self.val_acc['epoch'].append(logs.get('val_acc'))

 def loss_plot(self, loss_type):
  iters = range(len(self.losses[loss_type]))
  plt.figure()
  # acc
  plt.plot(iters, self.accuracy[loss_type], 'r', label='train acc')
  # loss
  plt.plot(iters, self.losses[loss_type], 'g', label='train loss')
  if loss_type == 'epoch':
   # val_acc
   plt.plot(iters, self.val_acc[loss_type], 'b', label='val acc')
   # val_loss
   plt.plot(iters, self.val_loss[loss_type], 'k', label='val loss')
  plt.grid(True)
  plt.xlabel(loss_type)
  plt.ylabel('acc-loss')
  plt.legend(loc="upper right")
  plt.show()
#变量初始化
batch_size = 128 
nb_classes = 10
nb_epoch = 20

# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = mnist.load_data()

X_train = X_train.reshape(60000, 784)
X_test = X_test.reshape(10000, 784)
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

#建立模型 使用Sequential()
model = Sequential()
model.add(Dense(512, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))

#打印模型
model.summary()

#训练与评估
#编译模型
model.compile(loss='categorical_crossentropy',
    optimizer=RMSprop(),
    metrics=['accuracy'])
#创建一个实例history
history = LossHistory()

#迭代训练(注意这个地方要加入callbacks)
model.fit(X_train, Y_train,
   batch_size=batch_size, nb_epoch=nb_epoch,
   verbose=1, 
   validation_data=(X_test, Y_test),
   callbacks=[history])

#模型评估
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])

#绘制acc-loss曲线
history.loss_plot('epoch')

keras绘制acc和loss曲线图实例

补充知识:keras中自定义验证集的性能评估(ROC,AUC)

在keras中自带的性能评估有准确性以及loss,当需要以auc作为评价验证集的好坏时,就得自己写个评价函数了:

from sklearn.metrics import roc_auc_score
from keras import backend as K

# AUC for a binary classifier
def auc(y_true, y_pred):
 ptas = tf.stack([binary_PTA(y_true,y_pred,k) for k in np.linspace(0, 1, 1000)],axis=0)
 pfas = tf.stack([binary_PFA(y_true,y_pred,k) for k in np.linspace(0, 1, 1000)],axis=0)
 pfas = tf.concat([tf.ones((1,)) ,pfas],axis=0)
 binSizes = -(pfas[1:]-pfas[:-1])
 s = ptas*binSizes
 return K.sum(s, axis=0)
#------------------------------------------------------------------------------------
# PFA, prob false alert for binary classifier
def binary_PFA(y_true, y_pred, threshold=K.variable(value=0.5)):
 y_pred = K.cast(y_pred >= threshold, 'float32')
 # N = total number of negative labels
 N = K.sum(1 - y_true)
 # FP = total number of false alerts, alerts from the negative class labels
 FP = K.sum(y_pred - y_pred * y_true)
 return FP/N
#-----------------------------------------------------------------------------------
# P_TA prob true alerts for binary classifier
def binary_PTA(y_true, y_pred, threshold=K.variable(value=0.5)):
 y_pred = K.cast(y_pred >= threshold, 'float32')
 # P = total number of positive labels
 P = K.sum(y_true)
 # TP = total number of correct alerts, alerts from the positive class labels
 TP = K.sum(y_pred * y_true)
 return TP/P
 
#接着在模型的compile中设置metrics
#如下例子,我用的是RNN做分类
from keras.models import Sequential
from keras.layers import Dense, Dropout
import keras
from keras.layers import GRU

model = Sequential()
model.add(keras.layers.core.Masking(mask_value=0., input_shape=(max_lenth, max_features))) #masking用于变长序列输入
model.add(GRU(units=n_hidden_units,activation='selu',kernel_initializer='orthogonal', recurrent_initializer='orthogonal',
    bias_initializer='zeros', kernel_regularizer=regularizers.l2(0.01), recurrent_regularizer=regularizers.l2(0.01),
    bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None,
    bias_constraint=None, dropout=0.5, recurrent_dropout=0.0, implementation=1, return_sequences=False,
    return_state=False, go_backwards=False, stateful=False, unroll=False)) 
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
    optimizer='adam',
    metrics=[auc]) #写入自定义评价函数

接下来就自己作预测了...

方法二:

from sklearn.metrics import roc_auc_score
import keras
class RocAucMetricCallback(keras.callbacks.Callback):
 def __init__(self, predict_batch_size=1024, include_on_batch=False):
  super(RocAucMetricCallback, self).__init__()
  self.predict_batch_size=predict_batch_size
  self.include_on_batch=include_on_batch
 
 def on_batch_begin(self, batch, logs={}):
  pass
 
 def on_batch_end(self, batch, logs={}):
  if(self.include_on_batch):
   logs['roc_auc_val']=float('-inf')
   if(self.validation_data):
    logs['roc_auc_val']=roc_auc_score(self.validation_data[1], 
             self.model.predict(self.validation_data[0],
                  batch_size=self.predict_batch_size))
 def on_train_begin(self, logs={}):
  if not ('roc_auc_val' in self.params['metrics']):
   self.params['metrics'].append('roc_auc_val')
 
 def on_train_end(self, logs={}):
  pass
 
 def on_epoch_begin(self, epoch, logs={}):
  pass
 
 def on_epoch_end(self, epoch, logs={}):
  logs['roc_auc_val']=float('-inf')
  if(self.validation_data):
   logs['roc_auc_val']=roc_auc_score(self.validation_data[1], 
            self.model.predict(self.validation_data[0],
                 batch_size=self.predict_batch_size))
import numpy as np
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.layers import GRU
import keras
from keras.callbacks import EarlyStopping
from sklearn.metrics import roc_auc_score
from keras import metrics
 
cb = [
 my_callbacks.RocAucMetricCallback(), # include it before EarlyStopping!
 EarlyStopping(monitor='roc_auc_val',patience=300, verbose=2,mode='max')
]
model = Sequential()
model.add(keras.layers.core.Masking(mask_value=0., input_shape=(max_lenth, max_features)))
# model.add(Embedding(input_dim=max_features+1, output_dim=64,mask_zero=True))
model.add(GRU(units=n_hidden_units,activation='selu',kernel_initializer='orthogonal', recurrent_initializer='orthogonal',
    bias_initializer='zeros', kernel_regularizer=regularizers.l2(0.01), recurrent_regularizer=regularizers.l2(0.01),
    bias_regularizer=None, activity_regularizer=None, kernel_constraint=None, recurrent_constraint=None,
    bias_constraint=None, dropout=0.5, recurrent_dropout=0.0, implementation=1, return_sequences=False,
    return_state=False, go_backwards=False, stateful=False, unroll=False)) #input_shape=(max_lenth, max_features),
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
 
model.compile(loss='binary_crossentropy',
    optimizer='adam',
    metrics=[auc]) #这里就可以写其他评估标准
model.fit(x_train, y_train, batch_size=train_batch_size, epochs=training_iters, verbose=2,
   callbacks=cb,validation_split=0.2,
   shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0)

亲测有效!

以上这篇keras绘制acc和loss曲线图实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python获取远程文件大小的函数代码分享
May 13 Python
解决windows下Sublime Text 2 运行 PyQt 不显示的方法分享
Jun 18 Python
Python入门篇之面向对象
Oct 20 Python
Python批量转换文件编码格式
May 17 Python
Python数据类型详解(三)元祖:tuple
May 08 Python
基于循环神经网络(RNN)的古诗生成器
Mar 26 Python
Python简单获取二维数组行列数的方法示例
Dec 21 Python
Python FTP文件定时自动下载实现过程解析
Nov 12 Python
以SQLite和PySqlite为例来学习Python DB API
Feb 05 Python
对tensorflow中tf.nn.conv1d和layers.conv1d的区别详解
Feb 11 Python
10个python3常用排序算法详细说明与实例(快速排序,冒泡排序,桶排序,基数排序,堆排序,希尔排序,归并排序,计数排序)
Mar 17 Python
matlab中二维插值函数interp2的使用详解
Apr 22 Python
Python定义一个函数的方法
Jun 15 #Python
python是怎么被发明的
Jun 15 #Python
Keras 利用sklearn的ROC-AUC建立评价函数详解
Jun 15 #Python
Python如何在windows环境安装pip及rarfile
Jun 15 #Python
keras训练曲线,混淆矩阵,CNN层输出可视化实例
Jun 15 #Python
Python3 requests模块如何模仿浏览器及代理
Jun 15 #Python
keras读取训练好的模型参数并把参数赋值给其它模型详解
Jun 15 #Python
You might like
PHP新手上路(八)
2006/10/09 PHP
PHP 中的批处理的实现
2007/06/14 PHP
PHP 正则表达式常用函数
2014/08/17 PHP
PHP配置把错误日志以邮件方式发送方法(Windows系统)
2015/06/23 PHP
PHP面向对象程序设计方法实例详解
2016/12/24 PHP
PHP写的简单数字验证码实例
2017/05/23 PHP
thinkPHP5分页功能实现方法分析
2017/10/25 PHP
基于jquery库的tab新形式使用
2012/11/16 Javascript
jquery弹出层类代码分享
2013/12/27 Javascript
基于jquery的simpleValidate简易验证插件
2014/01/31 Javascript
JavaScript对象之深度克隆介绍
2014/12/08 Javascript
node.js中使用socket.io的方法
2014/12/15 Javascript
jquery操作select方法汇总
2015/02/05 Javascript
sso跨域写cookie的一段js脚本(推荐)
2016/05/25 Javascript
javascript实现滚动效果的数字时钟实例
2016/07/21 Javascript
easyui中combotree循环获取父节点至根节点并输出路径实现方法
2016/11/10 Javascript
bootstrap multiselect 多选功能实现方法
2017/06/05 Javascript
JS实现自动轮播图效果(自适应屏幕宽度+手机触屏滑动)
2017/06/19 Javascript
JS实现定时任务每隔N秒请求后台setInterval定时和ajax请求问题
2017/10/15 Javascript
使用Sonarqube扫描Javascript代码的示例
2018/12/26 Javascript
Angular 2使用路由自定义弹出组件toast操作示例
2019/05/10 Javascript
layui 监听select选择 获取当前select的ID名称方法
2019/09/24 Javascript
js利用拖放实现添加删除
2020/08/27 Javascript
[01:38]2018DOTA2亚洲邀请赛主赛事第二日现场采访 神秘商人痛陈生计不易
2018/04/05 DOTA
跟老齐学Python之让人欢喜让人忧的迭代
2014/10/02 Python
Python KMeans聚类问题分析
2018/02/23 Python
python学生管理系统代码实现
2020/04/05 Python
对python中数据集划分函数StratifiedShuffleSplit的使用详解
2018/12/11 Python
应用心理学个人的求职信
2013/12/08 职场文书
档案接收函
2014/01/13 职场文书
初中优秀班集体申报材料
2014/05/01 职场文书
中共广东省委常委会党的群众路线教育实践活动整改方案
2014/09/23 职场文书
创业计划书之熟食店
2019/10/16 职场文书
Python必备技巧之字符数据操作详解
2022/03/23 Python
Python matplotlib绘制雷达图
2022/04/13 Python
Nginx开源可视化配置工具NginxConfig使用教程
2022/06/21 Servers