CINXE.COM

Model training APIs

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Keras documentation"> <meta name="author" content="Keras Team"> <link rel="shortcut icon" href="https://keras.io/img/favicon.ico"> <link rel="canonical" href="https://keras.io/api/models/model_training_apis/" /> <!-- Social --> <meta property="og:title" content="Keras documentation: Model training APIs"> <meta property="og:image" content="https://keras.io/img/logo-k-keras-wb.png"> <meta name="twitter:title" content="Keras documentation: Model training APIs"> <meta name="twitter:image" content="https://keras.io/img/k-keras-social.png"> <meta name="twitter:card" content="summary"> <title>Model training APIs</title> <!-- Bootstrap core CSS --> <link href="/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700;800&display=swap" rel="stylesheet"> <!-- Custom styles for this template --> <link href="/css/docs.css" rel="stylesheet"> <link href="/css/monokai.css" rel="stylesheet"> <!-- Google Tag Manager --> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= 'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-5DNGF4N'); </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-175165319-128', 'auto'); ga('send', 'pageview'); </script> <!-- End Google Tag Manager --> <script async defer src="https://buttons.github.io/buttons.js"></script> </head> <body> <!-- Google Tag Manager (noscript) --> <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-5DNGF4N" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript> <!-- End Google Tag Manager (noscript) --> <div class='k-page'> <div class="k-nav" id="nav-menu"> <a href='/'><img src='/img/logo-small.png' class='logo-small' /></a> <div class="nav flex-column nav-pills" role="tablist" aria-orientation="vertical"> <a class="nav-link" href="/about/" role="tab" aria-selected="">About Keras</a> <a class="nav-link" href="/getting_started/" role="tab" aria-selected="">Getting started</a> <a class="nav-link" href="/guides/" role="tab" aria-selected="">Developer guides</a> <a class="nav-link active" href="/api/" role="tab" aria-selected="">Keras 3 API documentation</a> <a class="nav-sublink active" href="/api/models/">Models API</a> <a class="nav-sublink2" href="/api/models/model/">The Model class</a> <a class="nav-sublink2" href="/api/models/sequential/">The Sequential class</a> <a class="nav-sublink2 active" href="/api/models/model_training_apis/">Model training APIs</a> <a class="nav-sublink2" href="/api/models/model_saving_apis/">Saving & serialization</a> <a class="nav-sublink" href="/api/layers/">Layers API</a> <a class="nav-sublink" href="/api/callbacks/">Callbacks API</a> <a class="nav-sublink" href="/api/ops/">Ops API</a> <a class="nav-sublink" href="/api/optimizers/">Optimizers</a> <a class="nav-sublink" href="/api/metrics/">Metrics</a> <a class="nav-sublink" href="/api/losses/">Losses</a> <a class="nav-sublink" href="/api/data_loading/">Data loading</a> <a class="nav-sublink" href="/api/datasets/">Built-in small datasets</a> <a class="nav-sublink" href="/api/applications/">Keras Applications</a> <a class="nav-sublink" href="/api/mixed_precision/">Mixed precision</a> <a class="nav-sublink" href="/api/distribution/">Multi-device distribution</a> <a class="nav-sublink" href="/api/random/">RNG API</a> <a class="nav-sublink" href="/api/utils/">Utilities</a> <a class="nav-sublink" href="/api/keras_tuner/">KerasTuner</a> <a class="nav-sublink" href="/api/keras_cv/">KerasCV</a> <a class="nav-sublink" href="/api/keras_nlp/">KerasNLP</a> <a class="nav-sublink" href="/api/keras_hub/">KerasHub</a> <a class="nav-link" href="/2.18/api/" role="tab" aria-selected="">Keras 2 API documentation</a> <a class="nav-link" href="/examples/" role="tab" aria-selected="">Code examples</a> <a class="nav-link" href="/keras_tuner/" role="tab" aria-selected="">KerasTuner: Hyperparameter Tuning</a> <a class="nav-link" href="/keras_hub/" role="tab" aria-selected="">KerasHub: Pretrained Models</a> <a class="nav-link" href="/keras_cv/" role="tab" aria-selected="">KerasCV: Computer Vision Workflows</a> <a class="nav-link" href="/keras_nlp/" role="tab" aria-selected="">KerasNLP: Natural Language Workflows</a> </div> </div> <div class='k-main'> <div class='k-main-top'> <script> function displayDropdownMenu() { e = document.getElementById("nav-menu"); if (e.style.display == "block") { e.style.display = "none"; } else { e.style.display = "block"; document.getElementById("dropdown-nav").style.display = "block"; } } function resetMobileUI() { if (window.innerWidth <= 840) { document.getElementById("nav-menu").style.display = "none"; document.getElementById("dropdown-nav").style.display = "block"; } else { document.getElementById("nav-menu").style.display = "block"; document.getElementById("dropdown-nav").style.display = "none"; } var navmenu = document.getElementById("nav-menu"); var menuheight = navmenu.clientHeight; var kmain = document.getElementById("k-main-id"); kmain.style.minHeight = (menuheight + 100) + 'px'; } window.onresize = resetMobileUI; window.addEventListener("load", (event) => { resetMobileUI() }); </script> <div id='dropdown-nav' onclick="displayDropdownMenu();"> <svg viewBox="-20 -20 120 120" width="60" height="60"> <rect width="100" height="20"></rect> <rect y="30" width="100" height="20"></rect> <rect y="60" width="100" height="20"></rect> </svg> </div> <form class="bd-search d-flex align-items-center k-search-form" id="search-form"> <input type="search" class="k-search-input" id="search-input" placeholder="Search Keras documentation..." aria-label="Search Keras documentation..." autocomplete="off"> <button class="k-search-btn"> <svg width="13" height="13" viewBox="0 0 13 13"><title>search</title><path d="m4.8495 7.8226c0.82666 0 1.5262-0.29146 2.0985-0.87438 0.57232-0.58292 0.86378-1.2877 0.87438-2.1144 0.010599-0.82666-0.28086-1.5262-0.87438-2.0985-0.59352-0.57232-1.293-0.86378-2.0985-0.87438-0.8055-0.010599-1.5103 0.28086-2.1144 0.87438-0.60414 0.59352-0.8956 1.293-0.87438 2.0985 0.021197 0.8055 0.31266 1.5103 0.87438 2.1144 0.56172 0.60414 1.2665 0.8956 2.1144 0.87438zm4.4695 0.2115 3.681 3.6819-1.259 1.284-3.6817-3.7 0.0019784-0.69479-0.090043-0.098846c-0.87973 0.76087-1.92 1.1413-3.1207 1.1413-1.3553 0-2.5025-0.46363-3.4417-1.3909s-1.4088-2.0686-1.4088-3.4239c0-1.3553 0.4696-2.4966 1.4088-3.4239 0.9392-0.92727 2.0864-1.3969 3.4417-1.4088 1.3553-0.011889 2.4906 0.45771 3.406 1.4088 0.9154 0.95107 1.379 2.0924 1.3909 3.4239 0 1.2126-0.38043 2.2588-1.1413 3.1385l0.098834 0.090049z"></path></svg> </button> </form> <script> var form = document.getElementById('search-form'); form.onsubmit = function(e) { e.preventDefault(); var query = document.getElementById('search-input').value; window.location.href = '/search.html?query=' + query; return False } </script> </div> <div class='k-main-inner' id='k-main-id'> <div class='k-location-slug'> <span class="k-location-slug-pointer">►</span> <a href='/api/'>Keras 3 API documentation</a> / <a href='/api/models/'>Models API</a> / Model training APIs </div> <div class='k-content'> <h1 id="model-training-apis">Model training APIs</h1> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/trainers/trainer.py#L38">[source]</a></span></p> <h3 id="compile-method"><code>compile</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="n">optimizer</span><span class="o">=</span><span class="s2">&quot;rmsprop&quot;</span><span class="p">,</span> <span class="n">loss</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">loss_weights</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">metrics</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">weighted_metrics</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">run_eagerly</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">steps_per_execution</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">jit_compile</span><span class="o">=</span><span class="s2">&quot;auto&quot;</span><span class="p">,</span> <span class="n">auto_scale_loss</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="p">)</span> </code></pre></div> <p>Configures the model for training.</p> <p><strong>Example</strong></p> <div class="codehilite"><pre><span></span><code><span class="n">model</span><span class="o">.</span><span class="n">compile</span><span class="p">(</span> <span class="n">optimizer</span><span class="o">=</span><span class="n">keras</span><span class="o">.</span><span class="n">optimizers</span><span class="o">.</span><span class="n">Adam</span><span class="p">(</span><span class="n">learning_rate</span><span class="o">=</span><span class="mf">1e-3</span><span class="p">),</span> <span class="n">loss</span><span class="o">=</span><span class="n">keras</span><span class="o">.</span><span class="n">losses</span><span class="o">.</span><span class="n">BinaryCrossentropy</span><span class="p">(),</span> <span class="n">metrics</span><span class="o">=</span><span class="p">[</span> <span class="n">keras</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">BinaryAccuracy</span><span class="p">(),</span> <span class="n">keras</span><span class="o">.</span><span class="n">metrics</span><span class="o">.</span><span class="n">FalseNegatives</span><span class="p">(),</span> <span class="p">],</span> <span class="p">)</span> </code></pre></div> <p><strong>Arguments</strong></p> <ul> <li><strong>optimizer</strong>: String (name of optimizer) or optimizer instance. See <code>keras.optimizers</code>.</li> <li><strong>loss</strong>: Loss function. May be a string (name of loss function), or a <a href="/api/losses#loss-class"><code>keras.losses.Loss</code></a> instance. See <code>keras.losses</code>. A loss function is any callable with the signature <code>loss = fn(y_true, y_pred)</code>, where <code>y_true</code> are the ground truth values, and <code>y_pred</code> are the model's predictions. <code>y_true</code> should have shape <code>(batch_size, d0, .. dN)</code> (except in the case of sparse loss functions such as sparse categorical crossentropy which expects integer arrays of shape <code>(batch_size, d0, .. dN-1)</code>). <code>y_pred</code> should have shape <code>(batch_size, d0, .. dN)</code>. The loss function should return a float tensor.</li> <li><strong>loss_weights</strong>: Optional list or dictionary specifying scalar coefficients (Python floats) to weight the loss contributions of different model outputs. The loss value that will be minimized by the model will then be the <em>weighted sum</em> of all individual losses, weighted by the <code>loss_weights</code> coefficients. If a list, it is expected to have a 1:1 mapping to the model's outputs. If a dict, it is expected to map output names (strings) to scalar coefficients.</li> <li><strong>metrics</strong>: List of metrics to be evaluated by the model during training and testing. Each of this can be a string (name of a built-in function), function or a <a href="/api/metrics/base_metric#metric-class"><code>keras.metrics.Metric</code></a> instance. See <code>keras.metrics</code>. Typically you will use <code>metrics=['accuracy']</code>. A function is any callable with the signature <code>result = fn(y_true, _pred)</code>. To specify different metrics for different outputs of a multi-output model, you could also pass a dictionary, such as <code>metrics={'a':'accuracy', 'b':['accuracy', 'mse']}</code>. You can also pass a list to specify a metric or a list of metrics for each output, such as <code>metrics=[['accuracy'], ['accuracy', 'mse']]</code> or <code>metrics=['accuracy', ['accuracy', 'mse']]</code>. When you pass the strings 'accuracy' or 'acc', we convert this to one of <a href="/api/metrics/accuracy_metrics#binaryaccuracy-class"><code>keras.metrics.BinaryAccuracy</code></a>, <a href="/api/metrics/accuracy_metrics#categoricalaccuracy-class"><code>keras.metrics.CategoricalAccuracy</code></a>, <a href="/api/metrics/accuracy_metrics#sparsecategoricalaccuracy-class"><code>keras.metrics.SparseCategoricalAccuracy</code></a> based on the shapes of the targets and of the model output. A similar conversion is done for the strings <code>"crossentropy"</code> and <code>"ce"</code> as well. The metrics passed here are evaluated without sample weighting; if you would like sample weighting to apply, you can specify your metrics via the <code>weighted_metrics</code> argument instead.</li> <li><strong>weighted_metrics</strong>: List of metrics to be evaluated and weighted by <code>sample_weight</code> or <code>class_weight</code> during training and testing.</li> <li><strong>run_eagerly</strong>: Bool. If <code>True</code>, this model's forward pass will never be compiled. It is recommended to leave this as <code>False</code> when training (for best performance), and to set it to <code>True</code> when debugging.</li> <li><strong>steps_per_execution</strong>: Int. The number of batches to run during each a single compiled function call. Running multiple batches inside a single compiled function call can greatly improve performance on TPUs or small models with a large Python overhead. At most, one full epoch will be run each execution. If a number larger than the size of the epoch is passed, the execution will be truncated to the size of the epoch. Note that if <code>steps_per_execution</code> is set to <code>N</code>, <code>Callback.on_batch_begin</code> and <code>Callback.on_batch_end</code> methods will only be called every <code>N</code> batches (i.e. before/after each compiled function execution). Not supported with the PyTorch backend.</li> <li><strong>jit_compile</strong>: Bool or <code>"auto"</code>. Whether to use XLA compilation when compiling a model. For <code>jax</code> and <code>tensorflow</code> backends, <code>jit_compile="auto"</code> enables XLA compilation if the model supports it, and disabled otherwise. For <code>torch</code> backend, <code>"auto"</code> will default to eager execution and <code>jit_compile=True</code> will run with <code>torch.compile</code> with the <code>"inductor"</code> backend.</li> <li><strong>auto_scale_loss</strong>: Bool. If <code>True</code> and the model dtype policy is <code>"mixed_float16"</code>, the passed optimizer will be automatically wrapped in a <code>LossScaleOptimizer</code>, which will dynamically scale the loss to prevent underflow.</li> </ul> <hr /> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/backend/tensorflow/trainer.py#L240">[source]</a></span></p> <h3 id="fit-method"><code>fit</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span> <span class="n">x</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="s2">&quot;auto&quot;</span><span class="p">,</span> <span class="n">callbacks</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">validation_split</span><span class="o">=</span><span class="mf">0.0</span><span class="p">,</span> <span class="n">validation_data</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">shuffle</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">class_weight</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">sample_weight</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">initial_epoch</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">steps_per_epoch</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">validation_steps</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">validation_batch_size</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">validation_freq</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="p">)</span> </code></pre></div> <p>Trains the model for a fixed number of epochs (dataset iterations).</p> <p><strong>Arguments</strong></p> <ul> <li><strong>x</strong>: Input data. It could be:<ul> <li>A NumPy array (or array-like), or a list of arrays (in case the model has multiple inputs).</li> <li>A tensor, or a list of tensors (in case the model has multiple inputs).</li> <li>A dict mapping input names to the corresponding array/tensors, if the model has named inputs.</li> <li>A <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a>. Should return a tuple of either <code>(inputs, targets)</code> or <code>(inputs, targets, sample_weights)</code>.</li> <li>A <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> returning <code>(inputs, targets)</code> or <code>(inputs, targets, sample_weights)</code>.</li> </ul> </li> <li><strong>y</strong>: Target data. Like the input data <code>x</code>, it could be either NumPy array(s) or backend-native tensor(s). If <code>x</code> is a dataset, generator, or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instance, <code>y</code> should not be specified (since targets will be obtained from <code>x</code>).</li> <li><strong>batch_size</strong>: Integer or <code>None</code>. Number of samples per gradient update. If unspecified, <code>batch_size</code> will default to 32. Do not specify the <code>batch_size</code> if your data is in the form of datasets, generators, or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instances (since they generate batches).</li> <li><strong>epochs</strong>: Integer. Number of epochs to train the model. An epoch is an iteration over the entire <code>x</code> and <code>y</code> data provided (unless the <code>steps_per_epoch</code> flag is set to something other than None). Note that in conjunction with <code>initial_epoch</code>, <code>epochs</code> is to be understood as "final epoch". The model is not trained for a number of iterations given by <code>epochs</code>, but merely until the epoch of index <code>epochs</code> is reached.</li> <li><strong>verbose</strong>: <code>"auto"</code>, 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = one line per epoch. "auto" becomes 1 for most cases. Note that the progress bar is not particularly useful when logged to a file, so <code>verbose=2</code> is recommended when not running interactively (e.g., in a production environment). Defaults to <code>"auto"</code>.</li> <li><strong>callbacks</strong>: List of <a href="/api/callbacks/base_callback#callback-class"><code>keras.callbacks.Callback</code></a> instances. List of callbacks to apply during training. See <code>keras.callbacks</code>. Note <a href="/api/callbacks/progbar_logger#progbarlogger-class"><code>keras.callbacks.ProgbarLogger</code></a> and <code>keras.callbacks.History</code> callbacks are created automatically and need not be passed to <code>model.fit()</code>. <a href="/api/callbacks/progbar_logger#progbarlogger-class"><code>keras.callbacks.ProgbarLogger</code></a> is created or not based on the <code>verbose</code> argument in <code>model.fit()</code>.</li> <li><strong>validation_split</strong>: Float between 0 and 1. Fraction of the training data to be used as validation data. The model will set apart this fraction of the training data, will not train on it, and will evaluate the loss and any model metrics on this data at the end of each epoch. The validation data is selected from the last samples in the <code>x</code> and <code>y</code> data provided, before shuffling. This argument is not supported when <code>x</code> is a dataset, generator or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instance. If both <code>validation_data</code> and <code>validation_split</code> are provided, <code>validation_data</code> will override <code>validation_split</code>.</li> <li><strong>validation_data</strong>: Data on which to evaluate the loss and any model metrics at the end of each epoch. The model will not be trained on this data. Thus, note the fact that the validation loss of data provided using <code>validation_split</code> or <code>validation_data</code> is not affected by regularization layers like noise and dropout. <code>validation_data</code> will override <code>validation_split</code>. It could be:<ul> <li>A tuple <code>(x_val, y_val)</code> of NumPy arrays or tensors.</li> <li>A tuple <code>(x_val, y_val, val_sample_weights)</code> of NumPy arrays.</li> <li>A <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a>.</li> <li>A Python generator or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> returning <code>(inputs, targets)</code> or <code>(inputs, targets, sample_weights)</code>.</li> </ul> </li> <li><strong>shuffle</strong>: Boolean, whether to shuffle the training data before each epoch. This argument is ignored when <code>x</code> is a generator or a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a>.</li> <li><strong>class_weight</strong>: Optional dictionary mapping class indices (integers) to a weight (float) value, used for weighting the loss function (during training only). This can be useful to tell the model to "pay more attention" to samples from an under-represented class. When <code>class_weight</code> is specified and targets have a rank of 2 or greater, either <code>y</code> must be one-hot encoded, or an explicit final dimension of <code>1</code> must be included for sparse class labels.</li> <li><strong>sample_weight</strong>: Optional NumPy array of weights for the training samples, used for weighting the loss function (during training only). You can either pass a flat (1D) NumPy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape <code>(samples, sequence_length)</code>, to apply a different weight to every timestep of every sample. This argument is not supported when <code>x</code> is a dataset, generator, or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instance, instead provide the sample_weights as the third element of <code>x</code>. Note that sample weighting does not apply to metrics specified via the <code>metrics</code> argument in <code>compile()</code>. To apply sample weighting to your metrics, you can specify them via the <code>weighted_metrics</code> in <code>compile()</code> instead.</li> <li><strong>initial_epoch</strong>: Integer. Epoch at which to start training (useful for resuming a previous training run).</li> <li><strong>steps_per_epoch</strong>: Integer or <code>None</code>. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as backend-native tensors, the default <code>None</code> is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined. If <code>x</code> is a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a>, and <code>steps_per_epoch</code> is <code>None</code>, the epoch will run until the input dataset is exhausted. When passing an infinitely repeating dataset, you must specify the <code>steps_per_epoch</code> argument. If <code>steps_per_epoch=-1</code> the training will run indefinitely with an infinitely repeating dataset.</li> <li><strong>validation_steps</strong>: Only relevant if <code>validation_data</code> is provided. Total number of steps (batches of samples) to draw before stopping when performing validation at the end of every epoch. If <code>validation_steps</code> is <code>None</code>, validation will run until the <code>validation_data</code> dataset is exhausted. In the case of an infinitely repeated dataset, it will run into an infinite loop. If <code>validation_steps</code> is specified and only part of the dataset will be consumed, the evaluation will start from the beginning of the dataset at each epoch. This ensures that the same validation samples are used every time.</li> <li><strong>validation_batch_size</strong>: Integer or <code>None</code>. Number of samples per validation batch. If unspecified, will default to <code>batch_size</code>. Do not specify the <code>validation_batch_size</code> if your data is in the form of datasets or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instances (since they generate batches).</li> <li><strong>validation_freq</strong>: Only relevant if validation data is provided. Specifies how many training epochs to run before a new validation run is performed, e.g. <code>validation_freq=2</code> runs validation every 2 epochs.</li> </ul> <p>Unpacking behavior for iterator-like inputs: A common pattern is to pass an iterator like object such as a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a> or a <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> to <code>fit()</code>, which will in fact yield not only features (<code>x</code>) but optionally targets (<code>y</code>) and sample weights (<code>sample_weight</code>). Keras requires that the output of such iterator-likes be unambiguous. The iterator should return a tuple of length 1, 2, or 3, where the optional second and third elements will be used for <code>y</code> and <code>sample_weight</code> respectively. Any other type provided will be wrapped in a length-one tuple, effectively treating everything as <code>x</code>. When yielding dicts, they should still adhere to the top-level tuple structure, e.g. <code>({"x0": x0, "x1": x1}, y)</code>. Keras will not attempt to separate features, targets, and weights from the keys of a single dict. A notable unsupported data type is the <code>namedtuple</code>. The reason is that it behaves like both an ordered datatype (tuple) and a mapping datatype (dict). So given a namedtuple of the form: <code>namedtuple("example_tuple", ["y", "x"])</code> it is ambiguous whether to reverse the order of the elements when interpreting the value. Even worse is a tuple of the form: <code>namedtuple("other_tuple", ["x", "y", "z"])</code> where it is unclear if the tuple was intended to be unpacked into <code>x</code>, <code>y</code>, and <code>sample_weight</code> or passed through as a single element to <code>x</code>.</p> <p><strong>Returns</strong></p> <p>A <code>History</code> object. Its <code>History.history</code> attribute is a record of training loss values and metrics values at successive epochs, as well as validation loss values and validation metrics values (if applicable).</p> <hr /> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/backend/tensorflow/trainer.py#L376">[source]</a></span></p> <h3 id="evaluate-method"><code>evaluate</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">evaluate</span><span class="p">(</span> <span class="n">x</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="s2">&quot;auto&quot;</span><span class="p">,</span> <span class="n">sample_weight</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">steps</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">callbacks</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">return_dict</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span> <span class="p">)</span> </code></pre></div> <p>Returns the loss value &amp; metrics values for the model in test mode.</p> <p>Computation is done in batches (see the <code>batch_size</code> arg.)</p> <p><strong>Arguments</strong></p> <ul> <li><strong>x</strong>: Input data. It could be:<ul> <li>A NumPy array (or array-like), or a list of arrays (in case the model has multiple inputs).</li> <li>A tensor, or a list of tensors (in case the model has multiple inputs).</li> <li>A dict mapping input names to the corresponding array/tensors, if the model has named inputs.</li> <li>A <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a>. Should return a tuple of either <code>(inputs, targets)</code> or <code>(inputs, targets, sample_weights)</code>.</li> <li>A generator or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> returning <code>(inputs, targets)</code> or <code>(inputs, targets, sample_weights)</code>.</li> </ul> </li> <li><strong>y</strong>: Target data. Like the input data <code>x</code>, it could be either NumPy array(s) or backend-native tensor(s). If <code>x</code> is a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a> or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instance, <code>y</code> should not be specified (since targets will be obtained from the iterator/dataset).</li> <li><strong>batch_size</strong>: Integer or <code>None</code>. Number of samples per batch of computation. If unspecified, <code>batch_size</code> will default to 32. Do not specify the <code>batch_size</code> if your data is in the form of a dataset, generators, or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instances (since they generate batches).</li> <li><strong>verbose</strong>: <code>"auto"</code>, 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = single line. <code>"auto"</code> becomes 1 for most cases. Note that the progress bar is not particularly useful when logged to a file, so <code>verbose=2</code> is recommended when not running interactively (e.g. in a production environment). Defaults to <code>"auto"</code>.</li> <li><strong>sample_weight</strong>: Optional NumPy array of weights for the test samples, used for weighting the loss function. You can either pass a flat (1D) NumPy array with the same length as the input samples (1:1 mapping between weights and samples), or in the case of temporal data, you can pass a 2D array with shape <code>(samples, sequence_length)</code>, to apply a different weight to every timestep of every sample. This argument is not supported when <code>x</code> is a dataset, instead pass sample weights as the third element of <code>x</code>.</li> <li><strong>steps</strong>: Integer or <code>None</code>. Total number of steps (batches of samples) before declaring the evaluation round finished. Ignored with the default value of <code>None</code>. If <code>x</code> is a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a> and <code>steps</code> is <code>None</code>, evaluation will run until the dataset is exhausted.</li> <li><strong>callbacks</strong>: List of <a href="/api/callbacks/base_callback#callback-class"><code>keras.callbacks.Callback</code></a> instances. List of callbacks to apply during evaluation.</li> <li><strong>return_dict</strong>: If <code>True</code>, loss and metric results are returned as a dict, with each key being the name of the metric. If <code>False</code>, they are returned as a list.</li> </ul> <p><strong>Returns</strong></p> <p>Scalar test loss (if the model has a single output and no metrics) or list of scalars (if the model has multiple outputs and/or metrics). The attribute <code>model.metrics_names</code> will give you the display labels for the scalar outputs.</p> <hr /> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/backend/tensorflow/trainer.py#L443">[source]</a></span></p> <h3 id="predict-method"><code>predict</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">predict</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="s2">&quot;auto&quot;</span><span class="p">,</span> <span class="n">steps</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">callbacks</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span> </code></pre></div> <p>Generates output predictions for the input samples.</p> <p>Computation is done in batches. This method is designed for batch processing of large numbers of inputs. It is not intended for use inside of loops that iterate over your data and process small numbers of inputs at a time.</p> <p>For small numbers of inputs that fit in one batch, directly use <code>__call__()</code> for faster execution, e.g., <code>model(x)</code>, or <code>model(x, training=False)</code> if you have layers such as <code>BatchNormalization</code> that behave differently during inference.</p> <p>Note: See <a href="https://keras.io/getting_started/faq/#whats-the-difference-between-model-methods-predict-and-call">this FAQ entry</a> for more details about the difference between <code>Model</code> methods <code>predict()</code> and <code>__call__()</code>.</p> <p><strong>Arguments</strong></p> <ul> <li><strong>x</strong>: Input samples. It could be:<ul> <li>A NumPy array (or array-like), or a list of arrays (in case the model has multiple inputs).</li> <li>A tensor, or a list of tensors (in case the model has multiple inputs).</li> <li>A <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a>.</li> <li>A <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instance.</li> </ul> </li> <li><strong>batch_size</strong>: Integer or <code>None</code>. Number of samples per batch. If unspecified, <code>batch_size</code> will default to 32. Do not specify the <code>batch_size</code> if your data is in the form of dataset, generators, or <a href="/api/utils/python_utils#pydataset-class"><code>keras.utils.PyDataset</code></a> instances (since they generate batches).</li> <li><strong>verbose</strong>: <code>"auto"</code>, 0, 1, or 2. Verbosity mode. 0 = silent, 1 = progress bar, 2 = single line. <code>"auto"</code> becomes 1 for most cases. Note that the progress bar is not particularly useful when logged to a file, so <code>verbose=2</code> is recommended when not running interactively (e.g. in a production environment). Defaults to <code>"auto"</code>.</li> <li><strong>steps</strong>: Total number of steps (batches of samples) before declaring the prediction round finished. Ignored with the default value of <code>None</code>. If <code>x</code> is a <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset"><code>tf.data.Dataset</code></a> and <code>steps</code> is <code>None</code>, <code>predict()</code> will run until the input dataset is exhausted.</li> <li><strong>callbacks</strong>: List of <a href="/api/callbacks/base_callback#callback-class"><code>keras.callbacks.Callback</code></a> instances. List of callbacks to apply during prediction.</li> </ul> <p><strong>Returns</strong></p> <p>NumPy array(s) of predictions.</p> <hr /> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/backend/tensorflow/trainer.py#L521">[source]</a></span></p> <h3 id="trainonbatch-method"><code>train_on_batch</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">train_on_batch</span><span class="p">(</span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">sample_weight</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">class_weight</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">return_dict</span><span class="o">=</span><span class="kc">False</span> <span class="p">)</span> </code></pre></div> <p>Runs a single gradient update on a single batch of data.</p> <p><strong>Arguments</strong></p> <ul> <li><strong>x</strong>: Input data. Must be array-like.</li> <li><strong>y</strong>: Target data. Must be array-like.</li> <li><strong>sample_weight</strong>: Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape <code>(samples, sequence_length)</code>, to apply a different weight to every timestep of every sample.</li> <li><strong>class_weight</strong>: Optional dictionary mapping class indices (integers) to a weight (float) to apply to the model's loss for the samples from this class during training. This can be useful to tell the model to "pay more attention" to samples from an under-represented class. When <code>class_weight</code> is specified and targets have a rank of 2 or greater, either <code>y</code> must be one-hot encoded, or an explicit final dimension of 1 must be included for sparse class labels.</li> <li><strong>return_dict</strong>: If <code>True</code>, loss and metric results are returned as a dict, with each key being the name of the metric. If <code>False</code>, they are returned as a list.</li> </ul> <p><strong>Returns</strong></p> <p>A scalar loss value (when no metrics and <code>return_dict=False</code>), a list of loss and metric values (if there are metrics and <code>return_dict=False</code>), or a dict of metric and loss values (if <code>return_dict=True</code>).</p> <hr /> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/backend/tensorflow/trainer.py#L555">[source]</a></span></p> <h3 id="testonbatch-method"><code>test_on_batch</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">test_on_batch</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">sample_weight</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">return_dict</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> </code></pre></div> <p>Test the model on a single batch of samples.</p> <p><strong>Arguments</strong></p> <ul> <li><strong>x</strong>: Input data. Must be array-like.</li> <li><strong>y</strong>: Target data. Must be array-like.</li> <li><strong>sample_weight</strong>: Optional array of the same length as x, containing weights to apply to the model's loss for each sample. In the case of temporal data, you can pass a 2D array with shape <code>(samples, sequence_length)</code>, to apply a different weight to every timestep of every sample.</li> <li><strong>return_dict</strong>: If <code>True</code>, loss and metric results are returned as a dict, with each key being the name of the metric. If <code>False</code>, they are returned as a list.</li> </ul> <p><strong>Returns</strong></p> <p>A scalar loss value (when no metrics and <code>return_dict=False</code>), a list of loss and metric values (if there are metrics and <code>return_dict=False</code>), or a dict of metric and loss values (if <code>return_dict=True</code>).</p> <hr /> <p><span style="float:right;"><a href="https://github.com/keras-team/keras/tree/v3.6.0/keras/src/backend/tensorflow/trainer.py#L577">[source]</a></span></p> <h3 id="predictonbatch-method"><code>predict_on_batch</code> method</h3> <div class="codehilite"><pre><span></span><code><span class="n">Model</span><span class="o">.</span><span class="n">predict_on_batch</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> </code></pre></div> <p>Returns predictions for a single batch of samples.</p> <p><strong>Arguments</strong></p> <ul> <li><strong>x</strong>: Input data. It must be array-like.</li> </ul> <p><strong>Returns</strong></p> <p>NumPy array(s) of predictions.</p> <hr /> </div> <div class='k-outline'> <div class='k-outline-depth-1'> <a href='#model-training-apis'>Model training APIs</a> </div> <div class='k-outline-depth-3'> <a href='#compile-method'><code>compile</code> method</a> </div> <div class='k-outline-depth-3'> <a href='#fit-method'><code>fit</code> method</a> </div> <div class='k-outline-depth-3'> <a href='#evaluate-method'><code>evaluate</code> method</a> </div> <div class='k-outline-depth-3'> <a href='#predict-method'><code>predict</code> method</a> </div> <div class='k-outline-depth-3'> <a href='#trainonbatch-method'><code>train_on_batch</code> method</a> </div> <div class='k-outline-depth-3'> <a href='#testonbatch-method'><code>test_on_batch</code> method</a> </div> <div class='k-outline-depth-3'> <a href='#predictonbatch-method'><code>predict_on_batch</code> method</a> </div> </div> </div> </div> </div> </body> <footer style="float: left; width: 100%; padding: 1em; border-top: solid 1px #bbb;"> <a href="https://policies.google.com/terms">Terms</a> | <a href="https://policies.google.com/privacy">Privacy</a> </footer> </html>

Pages: 1 2 3 4 5 6 7 8 9 10