1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
|
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="http://keras.io/utils/">
<link rel="shortcut icon" href="../img/favicon.ico">
<title>Utils - Keras Documentation</title>
<link href='https://fonts.googleapis.com/css?family=Lato:400,700|Source+Sans+Pro:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="../css/theme.css" type="text/css" />
<link rel="stylesheet" href="../css/theme_extra.css" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">
<script>
// Current page data
var mkdocs_page_name = "Utils";
var mkdocs_page_input_path = "utils.md";
var mkdocs_page_url = "/utils/";
</script>
<script src="../js/jquery-2.1.1.min.js" defer></script>
<script src="../js/modernizr-2.8.3.min.js" defer></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-61785484-1', 'keras.io');
ga('send', 'pageview');
</script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side stickynav">
<div class="wy-side-scroll">
<a href="">
<div class="keras-logo">
<img src="/img/keras-logo-small.jpg" class="keras-logo-img">
Keras Documentation
</div>
</a>
<div class="wy-side-nav-search">
<div role="search">
<form id ="rtd-search-form" class="wy-form" action="../search.html" method="get">
<input type="text" name="q" placeholder="Search docs" title="Type search term here" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul>
<li class="toctree-l1"><a class="reference internal" href="..">Home</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../why-use-keras/">Why use Keras</a>
</li>
</ul>
<p class="caption"><span class="caption-text">Getting started</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../getting-started/sequential-model-guide/">Guide to the Sequential model</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../getting-started/functional-api-guide/">Guide to the Functional API</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../getting-started/faq/">FAQ</a>
</li>
</ul>
<p class="caption"><span class="caption-text">Models</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../models/about-keras-models/">About Keras models</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../models/sequential/">Sequential</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../models/model/">Model (functional API)</a>
</li>
</ul>
<p class="caption"><span class="caption-text">Layers</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../layers/about-keras-layers/">About Keras layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/core/">Core Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/convolutional/">Convolutional Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/pooling/">Pooling Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/local/">Locally-connected Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/recurrent/">Recurrent Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/embeddings/">Embedding Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/merge/">Merge Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/advanced-activations/">Advanced Activations Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/normalization/">Normalization Layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/noise/">Noise layers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/wrappers/">Layer wrappers</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../layers/writing-your-own-keras-layers/">Writing your own Keras layers</a>
</li>
</ul>
<p class="caption"><span class="caption-text">Preprocessing</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../preprocessing/sequence/">Sequence Preprocessing</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../preprocessing/text/">Text Preprocessing</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../preprocessing/image/">Image Preprocessing</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../losses/">Losses</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../metrics/">Metrics</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../optimizers/">Optimizers</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../activations/">Activations</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../callbacks/">Callbacks</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../datasets/">Datasets</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../applications/">Applications</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../backend/">Backend</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../initializers/">Initializers</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../regularizers/">Regularizers</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../constraints/">Constraints</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../visualization/">Visualization</a>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../scikit-learn-api/">Scikit-learn API</a>
</li>
</ul>
<ul class="current">
<li class="toctree-l1 current"><a class="reference internal current" href="./">Utils</a>
<ul class="current">
</ul>
</li>
</ul>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../contributing/">Contributing</a>
</li>
</ul>
<p class="caption"><span class="caption-text">Examples</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="../examples/addition_rnn/">Addition RNN</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/antirectifier/">Custom layer - antirectifier</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/babi_rnn/">Baby RNN</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/babi_memnn/">Baby MemNN</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/cifar10_cnn/">CIFAR-10 CNN</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/cifar10_resnet/">CIFAR-10 ResNet</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/conv_filter_visualization/">Convolution filter visualization</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/conv_lstm/">Convolutional LSTM</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/deep_dream/">Deep Dream</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/image_ocr/">Image OCR</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/imdb_bidirectional_lstm/">Bidirectional LSTM</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/imdb_cnn/">1D CNN for text classification</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/imdb_cnn_lstm/">Sentiment classification CNN-LSTM</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/imdb_fasttext/">Fasttext for text classification</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/imdb_lstm/">Sentiment classification LSTM</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/lstm_seq2seq/">Sequence to sequence - training</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/lstm_seq2seq_restore/">Sequence to sequence - prediction</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/lstm_stateful/">Stateful LSTM</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/lstm_text_generation/">LSTM for text generation</a>
</li>
<li class="toctree-l1"><a class="reference internal" href="../examples/mnist_acgan/">Auxiliary Classifier GAN</a>
</li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="..">Keras Documentation</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="..">Docs</a> »</li>
<li>Utils</li>
<li class="wy-breadcrumbs-aside">
<a href="https://github.com/keras-team/keras/tree/master/docs"
class="icon icon-github"> Edit on GitHub</a>
</li>
</ul>
<hr/>
</div>
<div role="main">
<div class="section">
<p><span style="float:right;"><a href="https://github.com/keras-team/keras/blob/master/keras/utils/generic_utils.py#L21">[source]</a></span></p>
<h3 id="customobjectscope">CustomObjectScope</h3>
<pre><code class="python">keras.utils.CustomObjectScope()
</code></pre>
<p>Provides a scope that changes to <code>_GLOBAL_CUSTOM_OBJECTS</code> cannot escape.</p>
<p>Code within a <code>with</code> statement will be able to access custom objects
by name. Changes to global custom objects persist
within the enclosing <code>with</code> statement. At end of the <code>with</code> statement,
global custom objects are reverted to state
at beginning of the <code>with</code> statement.</p>
<p><strong>Example</strong></p>
<p>Consider a custom object <code>MyObject</code> (e.g. a class):</p>
<pre><code class="python">with CustomObjectScope({'MyObject':MyObject}):
layer = Dense(..., kernel_regularizer='MyObject')
# save, load, etc. will recognize custom object by name
</code></pre>
<hr />
<p><span style="float:right;"><a href="https://github.com/keras-team/keras/blob/master/keras/utils/io_utils.py#L26">[source]</a></span></p>
<h3 id="hdf5matrix">HDF5Matrix</h3>
<pre><code class="python">keras.utils.HDF5Matrix(datapath, dataset, start=0, end=None, normalizer=None)
</code></pre>
<p>Representation of HDF5 dataset to be used instead of a Numpy array.</p>
<p><strong>Example</strong></p>
<pre><code class="python">x_data = HDF5Matrix('input/file.hdf5', 'data')
model.predict(x_data)
</code></pre>
<p>Providing <code>start</code> and <code>end</code> allows use of a slice of the dataset.</p>
<p>Optionally, a normalizer function (or lambda) can be given. This will
be called on every slice of data retrieved.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>datapath</strong>: string, path to a HDF5 file</li>
<li><strong>dataset</strong>: string, name of the HDF5 dataset in the file specified
in datapath</li>
<li><strong>start</strong>: int, start of desired slice of the specified dataset</li>
<li><strong>end</strong>: int, end of desired slice of the specified dataset</li>
<li><strong>normalizer</strong>: function to be called on data when retrieved</li>
</ul>
<p><strong>Returns</strong></p>
<p>An array-like HDF5 dataset.</p>
<hr />
<p><span style="float:right;"><a href="https://github.com/keras-team/keras/blob/master/keras/utils/data_utils.py#L305">[source]</a></span></p>
<h3 id="sequence">Sequence</h3>
<pre><code class="python">keras.utils.Sequence()
</code></pre>
<p>Base object for fitting to a sequence of data, such as a dataset.</p>
<p>Every <code>Sequence</code> must implement the <code>__getitem__</code> and the <code>__len__</code> methods.
If you want to modify your dataset between epochs you may implement
<code>on_epoch_end</code>. The method <code>__getitem__</code> should return a complete batch.</p>
<p><strong>Notes</strong></p>
<p><code>Sequence</code> are a safer way to do multiprocessing. This structure guarantees
that the network will only train once on each sample per epoch which is not
the case with generators.</p>
<p><strong>Examples</strong></p>
<pre><code class="python">from skimage.io import imread
from skimage.transform import resize
import numpy as np
# Here, `x_set` is list of path to the images
# and `y_set` are the associated classes.
class CIFAR10Sequence(Sequence):
def __init__(self, x_set, y_set, batch_size):
self.x, self.y = x_set, y_set
self.batch_size = batch_size
def __len__(self):
return int(np.ceil(len(self.x) / float(self.batch_size)))
def __getitem__(self, idx):
batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
return np.array([
resize(imread(file_name), (200, 200))
for file_name in batch_x]), np.array(batch_y)
</code></pre>
<hr />
<h3 id="to_categorical">to_categorical</h3>
<pre><code class="python">keras.utils.to_categorical(y, num_classes=None, dtype='float32')
</code></pre>
<p>Converts a class vector (integers) to binary class matrix.</p>
<p>E.g. for use with categorical_crossentropy.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>y</strong>: class vector to be converted into a matrix
(integers from 0 to num_classes).</li>
<li><strong>num_classes</strong>: total number of classes.</li>
<li><strong>dtype</strong>: The data type expected by the input, as a string
(<code>float32</code>, <code>float64</code>, <code>int32</code>...)</li>
</ul>
<p><strong>Returns</strong></p>
<p>A binary matrix representation of the input. The classes axis
is placed last.</p>
<p><strong>Example</strong></p>
<pre><code class="python"># Consider an array of 5 labels out of a set of 3 classes {0, 1, 2}:
> labels
array([0, 2, 1, 2, 0])
# `to_categorical` converts this into a matrix with as many
# columns as there are classes. The number of rows
# stays the same.
> to_categorical(labels)
array([[ 1., 0., 0.],
[ 0., 0., 1.],
[ 0., 1., 0.],
[ 0., 0., 1.],
[ 1., 0., 0.]], dtype=float32)
</code></pre>
<hr />
<h3 id="normalize">normalize</h3>
<pre><code class="python">keras.utils.normalize(x, axis=-1, order=2)
</code></pre>
<p>Normalizes a Numpy array.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>x</strong>: Numpy array to normalize.</li>
<li><strong>axis</strong>: axis along which to normalize.</li>
<li><strong>order</strong>: Normalization order (e.g. 2 for L2 norm).</li>
</ul>
<p><strong>Returns</strong></p>
<p>A normalized copy of the array.</p>
<hr />
<h3 id="get_file">get_file</h3>
<pre><code class="python">keras.utils.get_file(fname, origin, untar=False, md5_hash=None, file_hash=None, cache_subdir='datasets', hash_algorithm='auto', extract=False, archive_format='auto', cache_dir=None)
</code></pre>
<p>Downloads a file from a URL if it not already in the cache.</p>
<p>By default the file at the url <code>origin</code> is downloaded to the
cache_dir <code>~/.keras</code>, placed in the cache_subdir <code>datasets</code>,
and given the filename <code>fname</code>. The final location of a file
<code>example.txt</code> would therefore be <code>~/.keras/datasets/example.txt</code>.</p>
<p>Files in tar, tar.gz, tar.bz, and zip formats can also be extracted.
Passing a hash will verify the file after download. The command line
programs <code>shasum</code> and <code>sha256sum</code> can compute the hash.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>fname</strong>: Name of the file. If an absolute path <code>/path/to/file.txt</code> is
specified the file will be saved at that location.</li>
<li><strong>origin</strong>: Original URL of the file.</li>
<li><strong>untar</strong>: Deprecated in favor of 'extract'.
boolean, whether the file should be decompressed</li>
<li><strong>md5_hash</strong>: Deprecated in favor of 'file_hash'.
md5 hash of the file for verification</li>
<li><strong>file_hash</strong>: The expected hash string of the file after download.
The sha256 and md5 hash algorithms are both supported.</li>
<li><strong>cache_subdir</strong>: Subdirectory under the Keras cache dir where the file is
saved. If an absolute path <code>/path/to/folder</code> is
specified the file will be saved at that location.</li>
<li><strong>hash_algorithm</strong>: Select the hash algorithm to verify the file.
options are 'md5', 'sha256', and 'auto'.
The default 'auto' detects the hash algorithm in use.</li>
<li><strong>extract</strong>: True tries extracting the file as an Archive, like tar or zip.</li>
<li><strong>archive_format</strong>: Archive format to try for extracting the file.
Options are 'auto', 'tar', 'zip', and None.
'tar' includes tar, tar.gz, and tar.bz files.
The default 'auto' is ['tar', 'zip'].
None or an empty list will return no matches found.</li>
<li><strong>cache_dir</strong>: Location to store cached files, when None it
defaults to the <a href="/faq/#where-is-the-keras-configuration-filed-stored">Keras Directory</a>.</li>
</ul>
<p><strong>Returns</strong></p>
<p>Path to the downloaded file</p>
<hr />
<h3 id="print_summary">print_summary</h3>
<pre><code class="python">keras.utils.print_summary(model, line_length=None, positions=None, print_fn=None)
</code></pre>
<p>Prints a summary of a model.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>model</strong>: Keras model instance.</li>
<li><strong>line_length</strong>: Total length of printed lines
(e.g. set this to adapt the display to different
terminal window sizes).</li>
<li><strong>positions</strong>: Relative or absolute positions of log elements in each line.
If not provided, defaults to <code>[.33, .55, .67, 1.]</code>.</li>
<li><strong>print_fn</strong>: Print function to use.
It will be called on each line of the summary.
You can set it to a custom function
in order to capture the string summary.
It defaults to <code>print</code> (prints to stdout).</li>
</ul>
<hr />
<h3 id="plot_model">plot_model</h3>
<pre><code class="python">keras.utils.plot_model(model, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB', expand_nested=False, dpi=96)
</code></pre>
<p>Converts a Keras model to dot format and save to a file.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>model</strong>: A Keras model instance</li>
<li><strong>to_file</strong>: File name of the plot image.</li>
<li><strong>show_shapes</strong>: whether to display shape information.</li>
<li><strong>show_layer_names</strong>: whether to display layer names.</li>
<li><strong>rankdir</strong>: <code>rankdir</code> argument passed to PyDot,
a string specifying the format of the plot:
'TB' creates a vertical plot;
'LR' creates a horizontal plot.</li>
<li><strong>expand_nested</strong>: whether to expand nested models into clusters.</li>
<li><strong>dpi</strong>: dot DPI.</li>
</ul>
<p><strong>Returns</strong></p>
<p>A Jupyter notebook Image object if Jupyter is installed.
This enables in-line display of the model plots in notebooks.</p>
<hr />
<h3 id="multi_gpu_model">multi_gpu_model</h3>
<pre><code class="python">keras.utils.multi_gpu_model(model, gpus=None, cpu_merge=True, cpu_relocation=False)
</code></pre>
<p>Replicates a model on different GPUs.</p>
<p>Specifically, this function implements single-machine
multi-GPU data parallelism. It works in the following way:</p>
<ul>
<li>Divide the model's input(s) into multiple sub-batches.</li>
<li>Apply a model copy on each sub-batch. Every model copy
is executed on a dedicated GPU.</li>
<li>Concatenate the results (on CPU) into one big batch.</li>
</ul>
<p>E.g. if your <code>batch_size</code> is 64 and you use <code>gpus=2</code>,
then we will divide the input into 2 sub-batches of 32 samples,
process each sub-batch on one GPU, then return the full
batch of 64 processed samples.</p>
<p>This induces quasi-linear speedup on up to 8 GPUs.</p>
<p>This function is only available with the TensorFlow backend
for the time being.</p>
<p><strong>Arguments</strong></p>
<ul>
<li><strong>model</strong>: A Keras model instance. To avoid OOM errors,
this model could have been built on CPU, for instance
(see usage example below).</li>
<li><strong>gpus</strong>: Integer >= 2 or list of integers, number of GPUs or
list of GPU IDs on which to create model replicas.</li>
<li><strong>cpu_merge</strong>: A boolean value to identify whether to force
merging model weights under the scope of the CPU or not.</li>
<li><strong>cpu_relocation</strong>: A boolean value to identify whether to
create the model's weights under the scope of the CPU.
If the model is not defined under any preceding device
scope, you can still rescue it by activating this option.</li>
</ul>
<p><strong>Returns</strong></p>
<p>A Keras <code>Model</code> instance which can be used just like the initial
<code>model</code> argument, but which distributes its workload on multiple GPUs.</p>
<p><strong>Examples</strong></p>
<p>Example 1 - Training models with weights merge on CPU</p>
<pre><code class="python">import tensorflow as tf
from keras.applications import Xception
from keras.utils import multi_gpu_model
import numpy as np
num_samples = 1000
height = 224
width = 224
num_classes = 1000
# Instantiate the base model (or "template" model).
# We recommend doing this with under a CPU device scope,
# so that the model's weights are hosted on CPU memory.
# Otherwise they may end up hosted on a GPU, which would
# complicate weight sharing.
with tf.device('/cpu:0'):
model = Xception(weights=None,
input_shape=(height, width, 3),
classes=num_classes)
# Replicates the model on 8 GPUs.
# This assumes that your machine has 8 available GPUs.
parallel_model = multi_gpu_model(model, gpus=8)
parallel_model.compile(loss='categorical_crossentropy',
optimizer='rmsprop')
# Generate dummy data.
x = np.random.random((num_samples, height, width, 3))
y = np.random.random((num_samples, num_classes))
# This `fit` call will be distributed on 8 GPUs.
# Since the batch size is 256, each GPU will process 32 samples.
parallel_model.fit(x, y, epochs=20, batch_size=256)
# Save model via the template model (which shares the same weights):
model.save('my_model.h5')
</code></pre>
<p>Example 2 - Training models with weights merge on CPU using cpu_relocation</p>
<pre><code class="python">..
# Not needed to change the device scope for model definition:
model = Xception(weights=None, ..)
try:
parallel_model = multi_gpu_model(model, cpu_relocation=True)
print("Training using multiple GPUs..")
except ValueError:
parallel_model = model
print("Training using single GPU or CPU..")
parallel_model.compile(..)
..
</code></pre>
<p>Example 3 - Training models with weights merge on GPU (recommended for NV-link)</p>
<pre><code class="python">..
# Not needed to change the device scope for model definition:
model = Xception(weights=None, ..)
try:
parallel_model = multi_gpu_model(model, cpu_merge=False)
print("Training using multiple GPUs..")
except:
parallel_model = model
print("Training using single GPU or CPU..")
parallel_model.compile(..)
..
</code></pre>
<p><strong>On model saving</strong></p>
<p>To save the multi-gpu model, use <code>.save(fname)</code> or <code>.save_weights(fname)</code>
with the template model (the argument you passed to <code>multi_gpu_model</code>),
rather than the model returned by <code>multi_gpu_model</code>.</p>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
<a href="../contributing/" class="btn btn-neutral float-right" title="Contributing">Next <span class="icon icon-circle-arrow-right"></span></a>
<a href="../scikit-learn-api/" class="btn btn-neutral" title="Scikit-learn API"><span class="icon icon-circle-arrow-left"></span> Previous</a>
</div>
<hr/>
<div role="contentinfo">
<!-- Copyright etc -->
</div>
Built with <a href="https://www.mkdocs.org/">MkDocs</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
</footer>
</div>
</div>
</section>
</div>
<div class="rst-versions" role="note" aria-label="versions">
<span class="rst-current-version" data-toggle="rst-current-version">
<a href="http://github.com/keras-team/keras/" class="fa fa-github" style="float: left; color: #fcfcfc"> GitHub</a>
<span><a href="../scikit-learn-api/" style="color: #fcfcfc;">« Previous</a></span>
<span style="margin-left: 15px"><a href="../contributing/" style="color: #fcfcfc">Next »</a></span>
</span>
</div>
<script>var base_url = '..';</script>
<script src="../js/theme.js" defer></script>
<script src="../search/main.js" defer></script>
<script type="text/javascript" defer>
window.onload = function () {
SphinxRtdTheme.Navigation.enable(true);
};
</script>
</body>
</html>
|