Private
checkGet number of samples provided for training, evaluation or prediction.
Input tf.Tensor
.
Integer batch size, optional.
Total number of steps (batches of samples) before declaring loop finished. Optional.
The public API's parameter name for steps
.
Number of samples provided.
List of InputSpec class instances.
Each entry describes one required input:
n
input tensors must have an inputSpec
of length n
.Private
makeCreate a function which, when invoked with an array of tf.Tensor
s as a
batch of inputs, returns the prespecified loss and metrics of the model
under the batch of input data.
Name for this layer. Must be unique within a model.
Private
predictHelper method to loop over some data in batches.
Porting Note: Not using the functional approach in the Python equivalent due to the imperative backend. Porting Note: Does not support step mode currently.
input data
integer batch size.
verbosity model
@returns: Predictions as tf.Tensor
(if a single output) or an Array
of
tf.Tensor
(if multipe outputs).
Private
retrieveRetrieve the model's internal symbolic tensors from symbolic-tensor names.
Private
testLoop over some test data in batches.
A Function returning a list of tensors.
Array of tensors to be fed to f
.
Integer batch size or null
/ undefined
.
verbosity mode.
Total number of steps (batches of samples) before
declaring test finished. Ignored with the default value of null
/
undefined
.
Array of Scalars.
Protected
trainable_Whether the layer weights will be updated during training.
Static
classRetrieves the input tensor(s) of a layer.
Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.
Input tensor or list of input tensors.
AttributeError if the layer is connected to more than one incoming layers.
Retrieves the output tensor(s) of a layer.
Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer.
Output tensor or list of output tensors.
AttributeError if the layer is connected to more than one incoming layers.
Retrieves the output shape(s) of a layer.
Only applicable if the layer has only one inbound node, or if all inbound nodes have the same output shape.
Output shape or shapes.
AttributeError: if the layer is connected to more than one incoming nodes.
Determine whether the container is stateful.
Porting Note: this is the equivalent of the stateful
Setter used for force stopping of LayersModel.fit() (i.e., training).
Example:
const input = tf.input({shape: [10]});
const output = tf.layers.dense({units: 1}).apply(input);
const model = tf.model({inputs: [input], outputs: [output]});
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
const xs = tf.ones([8, 10]);
const ys = tf.zeros([8, 1]);
const history = await model.fit(xs, ys, {
epochs: 10,
callbacks: {
onEpochEnd: async (epoch, logs) => {
if (epoch === 2) {
model.stopTraining = true;
}
}
}
});
// There should be only 3 values in the loss array, instead of 10
values,
// due to the stopping after 3 epochs.
console.log(history.history.loss);
Protected
addAdds a weight variable to the layer.
Name of the new weight variable.
The shape of the weight.
Optional
dtype: keyof DataTypeMapThe dtype of the weight.
Optional
initializer: InitializerAn initializer instance.
Optional
regularizer: RegularizerA regularizer instance.
Optional
trainable: booleanWhether the weight should be trained via backprop or not (assuming that the layer itself is also trainable).
Optional
constraint: ConstraintAn optional trainable.
Optional
getInitializerFunc: FunctionThe created weight variable.
Builds or executes a Layer
's logic.
When called with tf.Tensor
(s), execute the Layer
's computation and
return Tensor(s). For example:
const denseLayer = tf.layers.dense({
units: 1,
kernelInitializer: 'zeros',
useBias: false
});
// Invoke the layer's apply() method with a `tf.Tensor` (with concrete
// numeric values).
const input = tf.ones([2, 2]);
const output = denseLayer.apply(input);
// The output's value is expected to be [[0], [0]], due to the fact that
// the dense layer has a kernel initialized to all-zeros and does not have
// a bias.
output.print();
When called with tf.SymbolicTensor
(s), this will prepare the layer for
future execution. This entails internal book-keeping on shapes of
expected Tensors, wiring layers together, and initializing weights.
Calling apply
with tf.SymbolicTensor
s are typically used during the
building of non-tf.Sequential
models. For example:
const flattenLayer = tf.layers.flatten();
const denseLayer = tf.layers.dense({units: 1});
// Use tf.layers.input() to obtain a SymbolicTensor as input to apply().
const input = tf.input({shape: [2, 2]});
const output1 = flattenLayer.apply(input);
// output1.shape is [null, 4]. The first dimension is the undetermined
// batch size. The second dimension comes from flattening the [2, 2]
// shape.
console.log(JSON.stringify(output1.shape));
// The output SymbolicTensor of the flatten layer can be used to call
// the apply() of the dense layer:
const output2 = denseLayer.apply(output1);
// output2.shape is [null, 1]. The first dimension is the undetermined
// batch size. The second dimension matches the number of units of the
// dense layer.
console.log(JSON.stringify(output2.shape));
// The input and output can be used to construct a model that consists
// of the flatten and dense layers.
const model = tf.model({inputs: input, outputs: output2});
a tf.Tensor
or tf.SymbolicTensor
or an Array of them.
Optional
kwargs: KwargsAdditional keyword arguments to be passed to call()
.
Output of the layer's call
method.
ValueError error in case the layer is missing shape information
for its build
call.
Protected
assertChecks compatibility between the layer and provided inputs.
This checks that the tensor(s) input
verify the input assumptions of the layer
(if any). If not, exceptions are raised.
Input tensor or list of input tensors.
ValueError in case of mismatch between the provided inputs and the expectations of the layer.
Call the model on new inputs.
In this case call
just reapplies all ops in the graph to the new inputs
(e.g. build a new computational graph from the provided inputs).
A tensor if there is a single output, or a list of tensors if there are more than one outputs.
Protected
checkCheck trainable weights count consistency.
This will raise a warning if this.trainableWeights
and
this.collectedTrainableWeights
are inconsistent (i.e., have different
numbers of parameters).
Inconsistency will typically arise when one modifies model.trainable
without calling model.compile()
again.
Configures and prepares the model for training and evaluation. Compiling
outfits the model with an optimizer, loss, and/or metrics. Calling fit
or evaluate
on an un-compiled model will throw an error.
a ModelCompileArgs
specifying the loss, optimizer, and
metrics to be used for fitting and evaluating this model.
Protected
disposeReturns the loss value & metrics values for the model in test mode.
Loss and metrics are specified during compile()
, which needs to happen
before calls to evaluate()
.
Computation is done in batches.
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
const result = model.evaluate(
tf.ones([8, 10]), tf.ones([8, 1]), {batchSize: 4});
result.print();
tf.Tensor
of test data, or an Array
of tf.Tensor
s if the
model has multiple inputs.
tf.Tensor
of target data, or an Array
of tf.Tensor
s if the
model has multiple outputs.
Optional
args: ModelEvaluateArgsA ModelEvaluateArgs
, containing optional fields.
Scalar
test loss (if the model has a single output and no
metrics) or Array
of Scalar
s (if the model has multiple outputs
and/or metrics). The attribute model.metricsNames
will give you the display labels for the scalar outputs.
Evaluate model using a dataset object.
Note: Unlike evaluate()
, this method is asynchronous (async
).
A dataset object. Its iterator()
method is expected
to generate a dataset iterator object, the next()
method of which
is expected to produce data batches for evaluation. The return value
of the next()
call ought to contain a boolean done
field and a
value
field. The value
field is expected to be an array of two
tf.Tensor
s or an array of two nested tf.Tensor
structures. The former
case is for models with exactly one input and one output (e.g.
a sequential model). The latter case is for models with multiple
inputs and/or multiple outputs. Of the two items in the array, the
first is the input feature(s) and the second is the output target(s).
Optional
args: ModelEvaluateDatasetArgsA configuration object for the dataset-based evaluation.
Loss and metric values as an Array of Scalar
objects.
Execute internal tensors of the model with input data feed.
Input data feed. Must match the inputs of the model.
Names of the output tensors to be fetched. Must match names of the SymbolicTensors that belong to the graph.
Fetched values for outputs
.
Trains the model for a fixed number of epochs (iterations on a dataset).
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
for (let i = 1; i < 5 ; ++i) {
const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
epochs: 3
});
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
}
tf.Tensor
of training data, or an array of tf.Tensor
s if the
model has multiple inputs. If all inputs in the model are named, you
can also pass a dictionary mapping input names to tf.Tensor
s.
tf.Tensor
of target (label) data, or an array of tf.Tensor
s if
the model has multiple outputs. If all outputs in the model are named,
you can also pass a dictionary mapping output names to tf.Tensor
s.
Optional
args: ModelFitArgsA ModelFitArgs
, containing optional fields.
A History
instance. Its history
attribute contains all
information collected during training.
ValueError In case of mismatch between the provided input data and what the model expects.
Trains the model using a dataset object.
A dataset object. Its iterator()
method is expected
to generate a dataset iterator object, the next()
method of which
is expected to produce data batches for training. The return value
of the next()
call ought to contain a boolean done
field and a
value
field. The value
field is expected to be an array of two
tf.Tensor
s or an array of two nested tf.Tensor
structures. The former
case is for models with exactly one input and one output (e.g.
a sequential model). The latter case is for models with multiple
inputs and/or multiple outputs.
Of the two items in the array, the first is the input feature(s) and
the second is the output target(s).
A ModelFitDatasetArgs
, containing optional fields.
A History
instance. Its history
attribute contains all
information collected during training.
Abstract fit function for f(ins)
.
A Function returning a list of tensors. For training, this function is expected to perform the updates to the variables.
List of tensors to be fed to f
.
Optional
outLabels: string[]List of strings, display names of the outputs of f
.
Optional
batchSize: numberInteger batch size or == null
if unknown. Default : 32.
Optional
epochs: numberNumber of times to iterate over the data. Default : 1.
Optional
verbose: numberVerbosity mode: 0, 1, or 2. Default: 1.
Optional
callbacks: BaseCallback[]List of callbacks to be called during training.
Optional
valF: ((data) => Scalar[])Function to call for validation.
Optional
valIns: Tensor<Rank>[]List of tensors to be fed to valF
.
Optional
shuffle: string | booleanWhether to shuffle the data at the beginning of every epoch. Default : true.
Optional
callbackMetrics: string[]List of strings, the display names of the metrics
passed to the callbacks. They should be the concatenation of the
display names of the outputs of f
and the list of display names
of the outputs of valF
.
Optional
initialEpoch: numberEpoch at which to start training (useful for resuming a previous training run). Default : 0.
Optional
stepsPerEpoch: numberTotal number of steps (batches on samples) before
declaring one epoch finished and starting the next epoch. Ignored with
the default value of undefined
or null
.
Optional
validationSteps: numberNumber of steps to run validation for (only if doing validation from data tensors). Not applicable for tfjs-layers.
A History
object.
Return the class name for this class to use in serialization contexts.
Generally speaking this will be the same thing that constructor.name would have returned. However, the class name needs to be robust against minification for serialization/deserialization to work properly.
There's also places such as initializers.VarianceScaling, where implementation details between different languages led to different class hierarchies and a non-leaf node is used for serialization purposes.
Retrieves the input tensor(s) of a layer at a given node.
Integer, index of the node from which to retrieve the
attribute. E.g. nodeIndex=0
will correspond to the first time the layer
was called.
A tensor (or list of tensors if the layer has multiple inputs).
Retrieves a layer based on either its name (unique) or index.
Indices are based on order of horizontal graph traversal (bottom-up).
If both name
and index
are specified, index
takes precedence.
Name of layer.
A Layer instance.
ValueError: In case of invalid layer name or index.
Protected
getRetrieves the output tensor(s) of a layer at a given node.
Integer, index of the node from which to retrieve the
attribute. E.g. nodeIndex=0
will correspond to the first time the layer
was called.
A tensor (or list of tensors if the layer has multiple outputs).
Get user-defined metadata.
The metadata is supplied via one of the two routes:
setUserDefinedMetadata()
.tf.loadLayersModel()
.)If no user-defined metadata is available from either of the
two routes, this function will return undefined
.
Loads all layer weights from a JSON object.
Porting Note: HDF5 weight files cannot be directly loaded in JavaScript /
TypeScript. The utility script at scripts/pykeras.py
offers means
to convert them into JSON strings compatible with this method.
Porting Note: TensorFlow.js Layers supports only loading by name currently.
A JSON mapping weight names to weight values as nested
arrays of numbers, or a NamedTensorMap
, i.e., a JSON mapping weight
names to tf.Tensor
objects.
Optional
strict: booleanRequire that the provided weights exactly match those
required by the container. Default: true
. Passing false
means that
extra weights and missing weights will be silently ignored.
Protected
makeCreates a function that performs the following actions:
Creates a function that performs the following actions:
Generates output predictions for the input samples.
Computation is done in batches.
Note: the "step" mode of predict() is currently not supported. This is because the TensorFlow.js core backend is imperative only.
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.predict(tf.ones([8, 10]), {batchSize: 4}).print();
Prediction results as a tf.Tensor
(s).
ValueError In case of mismatch between the provided input data and the model's expectations, or in case a stateful model receives a number of samples that is not a multiple of the batch size.
Returns predictions for a single batch of samples.
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.predictOnBatch(tf.ones([8, 10])).print();
Tensor(s) of predictions
Protected
runSave the configuration and/or weights of the LayersModel.
An IOHandler
is an object that has a save
method of the proper
signature defined. The save
method manages the storing or
transmission of serialized data ("artifacts") that represent the
model's topology and weights onto or via a specific medium, such as
file downloads, local storage, IndexedDB in the web browser and HTTP
requests to a server. TensorFlow.js provides IOHandler
implementations for a number of frequently used saving mediums, such as
tf.io.browserDownloads
and tf.io.browserLocalStorage
. See tf.io
for more details.
This method also allows you to refer to certain types of IOHandler
s
as URL-like string shortcuts, such as 'localstorage://' and
'indexeddb://'.
Example 1: Save model
's topology and weights to browser local
storage;
then load it back.
const model = tf.sequential(
{layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
console.log('Prediction from original model:');
model.predict(tf.ones([1, 3])).print();
const saveResults = await model.save('localstorage://my-model-1');
const loadedModel = await tf.loadLayersModel('localstorage://my-model-1');
console.log('Prediction from loaded model:');
loadedModel.predict(tf.ones([1, 3])).print();
Example 2. Saving model
's topology and weights to browser
IndexedDB;
then load it back.
const model = tf.sequential(
{layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
console.log('Prediction from original model:');
model.predict(tf.ones([1, 3])).print();
const saveResults = await model.save('indexeddb://my-model-1');
const loadedModel = await tf.loadLayersModel('indexeddb://my-model-1');
console.log('Prediction from loaded model:');
loadedModel.predict(tf.ones([1, 3])).print();
Example 3. Saving model
's topology and weights as two files
(my-model-1.json
and my-model-1.weights.bin
) downloaded from
browser.
const model = tf.sequential(
{layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
const saveResults = await model.save('downloads://my-model-1');
Example 4. Send model
's topology and weights to an HTTP server.
See the documentation of tf.io.http
for more details
including specifying request parameters and implementation of the
server.
const model = tf.sequential(
{layers: [tf.layers.dense({units: 1, inputShape: [3]})]});
const saveResults = await model.save('http://my-server/model/upload');
An instance of IOHandler
or a URL-like,
scheme-based string shortcut for IOHandler
.
Optional
config: SaveConfigOptions for saving the model.
A Promise
of SaveResult
, which summarizes the result of
the saving, such as byte sizes of the saved artifacts for the model's
topology and weight values.
Set the fast-weight-initialization flag.
In cases where the initialized weight values will be immediately
overwritten by loaded weight values during model loading, setting
the flag to true
saves unnecessary calls to potentially expensive
initializers and speeds up the loading process.
Target value of the flag.
Sets the weights of the layer, from Tensors.
a list of Tensors. The number of arrays and their shape
must match number of the dimensions of the weights of the layer (i.e.
it should match the output of getWeights
).
ValueError If the provided weights list does not match the layer's specifications.
Print a text summary of the model's layers.
The summary includes
const input1 = tf.input({shape: [10]});
const input2 = tf.input({shape: [20]});
const dense1 = tf.layers.dense({units: 4}).apply(input1);
const dense2 = tf.layers.dense({units: 8}).apply(input2);
const concat = tf.layers.concatenate().apply([dense1, dense2]);
const output =
tf.layers.dense({units: 3, activation: 'softmax'}).apply(concat);
const model = tf.model({inputs: [input1, input2], outputs: output});
model.summary();
Optional
lineLength: numberCustom line length, in number of characters.
Optional
positions: number[]Custom widths of each of the columns, as either
fractions of lineLength
(e.g., [0.5, 0.75, 1]
) or absolute number
of characters (e.g., [30, 50, 65]
). Each number corresponds to
right-most (i.e., ending) position of a column.
Optional
printFn: ((message?, ...optionalParams) => void)Custom print function. Can be used to replace the default
console.log
. For example, you can use x => {}
to mute the printed
messages in the console.
Optional
message: anyRest
...optionalParams: any[]Returns a JSON string containing the network configuration.
To load a network from a JSON save file, use models.modelFromJSON(jsonString);
Optional
unused: anyOptional
returnString: booleanWhether the return value should be stringified
(default: true
).
a JSON string if returnString
(default), or a JSON object if
!returnString
.
Runs a single gradient update on a single batch of data.
This method differs from fit()
and fitDataset()
in the following
regards:
Input data. It could be one of the following:
tf.Tensor
, or an Array of tf.Tensor
s (in case the model has
multiple inputs).tf.Tensor
(if the
model has named inputs).Target data. It could be either a tf.Tensor
or multiple
tf.Tensor
s. It should be consistent with x
.
Training loss or losses (in case the model has multiple outputs), along with metrics (if any), as numbers.
Protected
updatedProtected
warnCheck compatibility between input shape and this layer's batchInputShape.
Print warning if any incompatibility is found.
Input shape to be checked.
Static
fromOptional
customObjects: ConfigDictOptional
fastWeightInit: booleanProtected
Static
nodeConverts a layer and its index to a unique (immutable type) name.
This function is used internally with this.containerNodes
.
The layer.
The layer's position (e.g. via enumerate) in a list of nodes.
The unique name.
Generated using TypeDoc
A
tf.LayersModel
is a directed, acyclic graph oftf.Layer
s plus methods for training, evaluation, prediction and saving.tf.LayersModel
is the basic unit of training, inference and evaluation in TensorFlow.js. To create atf.LayersModel
, usetf.LayersModel
.See also:
tf.Sequential
,tf.loadLayersModel
.Doc