1. 程式人生 > >How to Use Metrics for Deep Learning with Keras in Python

How to Use Metrics for Deep Learning with Keras in Python

The Keras library provides a way to calculate and report on a suite of standard metrics when training deep learning models.

In addition to offering standard metrics for classification and regression problems, Keras also allows you to define and report on your own custom metrics when training deep learning models. This is particularly useful if you want to keep track of a performance measure that better captures the skill of your model during training.

In this tutorial, you will discover how to use the built-in metrics and how to define and use your own metrics when training deep learning models in Keras.

After completing this tutorial, you will know:

  • How Keras metrics work and how you can use them when training your models.
  • How to use regression and classification metrics in Keras with worked examples.
  • How to define and use your own custom metric in Keras with a worked example.

Let’s get started.

Metrics and How to Use Custom Metrics for Deep Learning with Keras in Python

Metrics and How to Use Custom Metrics for Deep Learning with Keras in Python
Photo by Indi Samarajiva, some rights reserved.

Tutorial Overview

This tutorial is divided into 4 parts; they are:

  1. Keras Metrics
  2. Keras Regression Metrics
  3. Keras Classification Metrics
  4. Custom Metrics in Keras

Keras Metrics

Keras allows you to list the metrics to monitor during the training of your model.

You can do this by specifying the “metrics” argument and providing a list of function names (or function name aliases) to the compile() function on your model.

For example:

1 model.compile(...,metrics=['mse'])

The specific metrics that you list can be the names of Keras functions (like mean_squared_error) or string aliases for those functions (like ‘mse‘).

Metric values are recorded at the end of each epoch on the training dataset. If a validation dataset is also provided, then the metric recorded is also calculated for the validation dataset.

All metrics are reported in verbose output and in the history object returned from calling the fit() function. In both cases, the name of the metric function is used as the key for the metric values. In the case of metrics for the validation dataset, the “val_” prefix is added to the key.

Both loss functions and explicitly defined Keras metrics can be used as training metrics.

Keras Regression Metrics

Below is a list of the metrics that you can use in Keras on regression problems.

  • Mean Squared Error: mean_squared_error, MSE or mse
  • Mean Absolute Error: mean_absolute_error, MAE, mae
  • Mean Absolute Percentage Error: mean_absolute_percentage_error, MAPE, mape
  • Cosine Proximity: cosine_proximity, cosine

The example below demonstrates these 4 built-in regression metrics on a simple contrived regression problem.

12345678910111213141516171819 from numpy import arrayfrom keras.models import Sequentialfrom keras.layers import Densefrom matplotlib import pyplot# prepare sequenceX=array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])# create modelmodel=Sequential()model.add(Dense(2,input_dim=1))model.add(Dense(1))model.compile(loss='mse',optimizer='adam',metrics=['mse','mae','mape','cosine'])# train modelhistory=model.fit(X,X,epochs=500,batch_size=len(X),verbose=2)# plot metricspyplot.plot(history.history['mean_squared_error'])pyplot.plot(history.history['mean_absolute_error'])pyplot.plot(history.history['mean_absolute_percentage_error'])pyplot.plot(history.history['cosine_proximity'])pyplot.show()

Running the example prints the metric values at the end of each epoch.

1234567891011 ...Epoch 96/1000s - loss: 1.0596e-04 - mean_squared_error: 1.0596e-04 - mean_absolute_error: 0.0088 - mean_absolute_percentage_error: 3.5611 - cosine_proximity: -1.0000e+00Epoch 97/1000s - loss: 1.0354e-04 - mean_squared_error: 1.0354e-04 - mean_absolute_error: 0.0087 - mean_absolute_percentage_error: 3.5178 - cosine_proximity: -1.0000e+00Epoch 98/1000s - loss: 1.0116e-04 - mean_squared_error: 1.0116e-04 - mean_absolute_error: 0.0086 - mean_absolute_percentage_error: 3.4738 - cosine_proximity: -1.0000e+00Epoch 99/1000s - loss: 9.8820e-05 - mean_squared_error: 9.8820e-05 - mean_absolute_error: 0.0085 - mean_absolute_percentage_error: 3.4294 - cosine_proximity: -1.0000e+00Epoch 100/1000s - loss: 9.6515e-05 - mean_squared_error: 9.6515e-05 - mean_absolute_error: 0.0084 - mean_absolute_percentage_error: 3.3847 - cosine_proximity: -1.0000e+00

A line plot of the 4 metrics over the training epochs is then created.

Line Plot of Built-in Keras Metrics for Regression

Line Plot of Built-in Keras Metrics for Regression

Note that the metrics were specified using string alias values [‘mse‘, ‘mae‘, ‘mape‘, ‘cosine‘] and were referenced as key values on the history object using their expanded function name.

We could also specify the metrics using their expanded name, as follows:

1 model.compile(loss='mse',optimizer='adam',metrics=['mean_squared_error','mean_absolute_error','mean_absolute_percentage_error','cosine_proximity'])

We can also specify the function names directly if they are imported into the script.

12 from keras import metricsmodel.compile(loss='mse',optimizer='adam',metrics=[metrics.mean_squared_error,metrics.mean_absolute_error,metrics.mean_absolute_percentage_error,metrics.cosine_proximity])

You can also use the loss functions as metrics.

For example, you could use the Mean squared Logarithmic Error (mean_squared_logarithmic_error, MSLE or msle) loss function as a metric as follows:

1 model.compile(loss='mse',optimizer='adam',metrics=['msle'])

Keras Classification Metrics

Below is a list of the metrics that you can use in Keras on classification problems.

  • Binary Accuracy: binary_accuracy, acc
  • Categorical Accuracy: categorical_accuracy, acc
  • Sparse Categorical Accuracy: sparse_categorical_accuracy
  • Top k Categorical Accuracy: top_k_categorical_accuracy (requires you specify a k parameter)
  • Sparse Top k Categorical Accuracy: sparse_top_k_categorical_accuracy (requires you specify a k parameter)

Accuracy is special.

Regardless of whether your problem is a binary or multi-class classification problem, you can specify the ‘acc‘ metric to report on accuracy.

Below is an example of a binary classification problem with the built-in accuracy metric demonstrated.

1234567891011121314151617 from numpy import arrayfrom keras.models import Sequentialfrom keras.layers import Densefrom matplotlib import pyplot# prepare sequenceX=array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])y=array([0,0,0,0,0,1,1,1,1,1])# create modelmodel=Sequential()model.add(Dense(2,input_dim=1))model.add(Dense(1,activation='sigmoid'))model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['acc'])# train modelhistory=model.fit(X,y,epochs=400,batch_size=len(X),verbose=2)# plot metricspyplot.plot(history.history['acc'])pyplot.show()

Running the example reports the accuracy at the end of each training epoch.

1234567891011 ...Epoch 396/4000s - loss: 0.5934 - acc: 0.9000Epoch 397/4000s - loss: 0.5932 - acc: 0.9000Epoch 398/4000s - loss: 0.5930 - acc: 0.9000Epoch 399/4000s - loss: 0.5927 - acc: 0.9000Epoch 400/4000s - loss: 0.5925 - acc: 0.9000

A line plot of accuracy over epoch is created.

Line Plot of Built-in Keras Metrics for Classification

Line Plot of Built-in Keras Metrics for Classification

Custom Metrics in Keras

You can also define your own metrics and specify the function name in the list of functions for the “metrics” argument when calling the compile() function.

A metric I often like to keep track of is Root Mean Square Error, or RMSE.

You can get an idea of how to write a custom metric by examining the code for an existing metric.

12 def mean_squared_error(y_true,y_pred):returnK.mean(K.square(y_pred-y_true),axis=-1)

K is the backend used by Keras.

From this example and other examples of loss functions and metrics, the approach is to use standard math functions on the backend to calculate the metric of interest.

For example, we can write a custom metric to calculate RMSE as follows:

1234 from keras import backenddef rmse(y_true,y_pred):returnbackend.sqrt(backend.mean(backend.square(y_pred-y_true),axis=-1))

You can see the function is the same code as MSE with the addition of the sqrt() wrapping the result.

We can test this in our regression example as follows. Note that we simply list the function name directly rather than providing it as a string or alias for Keras to resolve.

123456789101112131415161718192021 from numpy import arrayfrom keras.models import Sequentialfrom keras.layers import Densefrom matplotlib import pyplotfrom keras import backenddef rmse(y_true,y_pred):returnbackend.sqrt(backend.mean(backend.square(y_pred-y_true),axis=-1))# prepare sequenceX=array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0])# create modelmodel=Sequential()model.add(Dense(2,input_dim=1,activation='relu'))model.add(Dense(1))model.compile(loss='mse',optimizer='adam',metrics=[rmse])# train modelhistory=model.fit(X,X,epochs=500,batch_size=len(X),verbose=2)# plot metricspyplot.plot(history.history['rmse'])pyplot.show()

Running the example reports the custom RMSE metric at the end of each training epoch.

相關推薦

How to Use Metrics for Deep Learning with Keras in Python

Tweet Share Share Google Plus The Keras library provides a way to calculate and report on a suit

How to Clean Text for Machine Learning with Python

Tweet Share Share Google Plus You cannot go straight from raw text to fitting a machine learning

Image Augmentation for Deep Learning With Keras

Tweet Share Share Google Plus Data preparation is required when working with neural network and

Why Use Framework for Deep Learning?

You can implement your own deep learning algorithms from scratch using Python or any other programming language. When you start implementing more complex m

Ask HN: Whats the best way to learn C++ for Deep learning?

What is your reason for learning "C++ for deep learning"?This will kind of define how to go about doing it.I can think of a few different reasons you might

Help! My company doesn't know how to use Git for production ready releases

My company is still widely using CVCS (Central Version Control Systems) tools mostly SVN. We've just now been slowly integrating Git into our department.Ou

How to Prepare Data For Machine Learning

Tweet Share Share Google Plus Machine learning algorithms learn from data. It is critical that y

Introduction to Python Deep Learning with Keras

Tweet Share Share Google Plus Two of the top numerical platforms in Python that provide the basi

How to use Dagger 2 on Android with Kotlin (KAD 20)

Virtually everyone who wants to create code on Android in a decoupled and easy-to-test way, resorts to Dagger sooner or later. Although there is some

how to use Eclipse for kernel development

lte reporting ctu header adding point tab ros global http://wiki.eclipse.org/HowTo_use_the_CDT_to_navigate_Linux_kernel_source Here are s

A guide to convolution arithmetic for deep learning

一、Discrete convolutions A discrete convolution is a linear transformation that preserves this notio

How to use udev for Oracle ASM in Oracle Linux 6

但是在OEL6或者RHEL6中,這一切都有所變化。 主要的變化是: 1. scsi_id的命令語法發生了變化,scsi_id -g -u -s這樣的命令不再有效。 2. udevtest命令已經沒有了,整合到了udevadm中。 可以參考Redhat的官方文件(這個文件中本身有一些錯誤,在ud

(轉) Learning Deep Learning with Keras

trees create pda sse caffe latex .py encode you Learning Deep Learning with Keras Piotr Migda? - blog Projects Articles Publications Res

How to Visualize Your Recurrent Neural Network with Attention in Keras

Now for the interesting part: the decoder. For any given character at position t in the sequence, our decoder accepts the encoded sequence h=(h1,...,hT) as

How to build your own Neural Network from scratch in Python

How to build your own Neural Network from scratch in PythonA beginner’s guide to understanding the inner workings of Deep LearningMotivation: As part of my

how to get the return value from a thread in python?

Jake's answer is good, but if you don't want to use a threadpool (you don't know how many threads you'll need, but create them as needed) then a good w

How to use DeepLab in TensorFlow for object segmentation using Deep Learning

How to use DeepLab in TensorFlow for object segmentation using Deep LearningModifying the DeepLab code to train on your own dataset for object segmentation

How to Use the Keras Functional API for Deep Learning

Tweet Share Share Google Plus The Keras Python library makes creating deep learning models fast

How to use for ASP.NET Core with csproj

2017-10-10 23:40:29.5143||DEBUG|ASP.NET_Core_2___VS2017.Program|init main 2017-10-10 23:40:30.9739|0|INFO|Microsoft.AspNetCore.DataProtection.KeyManageme