doc_content
stringlengths 1
386k
| doc_id
stringlengths 5
188
|
---|---|
tf.io.gfile.rmtree View source on GitHub Deletes everything under path recursively. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.rmtree
tf.io.gfile.rmtree(
path
)
Args
path string, a path
Raises
errors.OpError If the operation fails. | tensorflow.io.gfile.rmtree |
tf.io.gfile.stat View source on GitHub Returns file statistics for a given path. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.stat
tf.io.gfile.stat(
path
)
Args
path string, path to a file
Returns FileStatistics struct that contains information about the path
Raises
errors.OpError If the operation fails. | tensorflow.io.gfile.stat |
tf.io.gfile.walk View source on GitHub Recursive directory tree generator for directories. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.gfile.walk
tf.io.gfile.walk(
top, topdown=True, onerror=None
)
Args
top string, a Directory name
topdown bool, Traverse pre order if True, post order if False.
onerror optional handler for errors. Should be a function, it will be called with the error as argument. Rethrowing the error aborts the walk. Errors that happen while listing directories are ignored.
Yields Each yield is a 3-tuple: the pathname of a directory, followed by lists of all its subdirectories and leaf files. That is, each yield looks like: (dirname, [subdirname, subdirname, ...], [filename, filename, ...]). Each item is a string. | tensorflow.io.gfile.walk |
tf.io.is_jpeg View source on GitHub Convenience function to check if the 'contents' encodes a JPEG image. View aliases Main aliases
tf.image.is_jpeg Compat aliases for migration See Migration guide for more details. tf.compat.v1.image.is_jpeg, tf.compat.v1.io.is_jpeg
tf.io.is_jpeg(
contents, name=None
)
Args
contents 0-D string. The encoded image bytes.
name A name for the operation (optional)
Returns A scalar boolean tensor indicating if 'contents' may be a JPEG image. is_jpeg is susceptible to false positives. | tensorflow.io.is_jpeg |
tf.io.matching_files Returns the set of files matching one or more glob patterns. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.matching_files, tf.compat.v1.matching_files
tf.io.matching_files(
pattern, name=None
)
Note that this routine only supports wildcard characters in the basename portion of the pattern, not in the directory portion. Note also that the order of filenames returned is deterministic.
Args
pattern A Tensor of type string. Shell wildcard pattern(s). Scalar or vector of type string.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.matching_files |
tf.io.match_filenames_once View source on GitHub Save the list of files matching pattern, so it is only computed once. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.match_filenames_once, tf.compat.v1.train.match_filenames_once
tf.io.match_filenames_once(
pattern, name=None
)
Note: The order of the files returned is deterministic.
Args
pattern A file pattern (glob), or 1D tensor of file patterns.
name A name for the operations (optional).
Returns A variable that is initialized to the list of files matching the pattern(s). | tensorflow.io.match_filenames_once |
tf.io.parse_example View source on GitHub Parses Example protos into a dict of tensors.
tf.io.parse_example(
serialized, features, example_names=None, name=None
)
Parses a number of serialized Example protos given in serialized. We refer to serialized as a batch with batch_size many entries of individual Example protos. example_names may contain descriptive names for the corresponding serialized protos. These may be useful for debugging purposes, but they have no effect on the output. If not None, example_names must be the same length as serialized. This op parses serialized examples into a dictionary mapping keys to Tensor SparseTensor, and RaggedTensor objects. features is a dict from keys to VarLenFeature, SparseFeature, RaggedFeature, and FixedLenFeature objects. Each VarLenFeature and SparseFeature is mapped to a SparseTensor; each FixedLenFeature is mapped to a Tensor; and each RaggedFeature is mapped to a RaggedTensor. Each VarLenFeature maps to a SparseTensor of the specified type representing a ragged matrix. Its indices are [batch, index] where batch identifies the example in serialized, and index is the value's index in the list of values associated with that feature and example. Each SparseFeature maps to a SparseTensor of the specified type representing a Tensor of dense_shape [batch_size] + SparseFeature.size. Its values come from the feature in the examples with key value_key. A values[i] comes from a position k in the feature of an example at batch entry batch. This positional information is recorded in indices[i] as [batch, index_0, index_1, ...] where index_j is the k-th value of the feature in the example at with key SparseFeature.index_key[j]. In other words, we split the indices (except the first index indicating the batch entry) of a SparseTensor by dimension into different features of the Example. Due to its complexity a VarLenFeature should be preferred over a SparseFeature whenever possible. Each FixedLenFeature df maps to a Tensor of the specified type (or tf.float32 if not specified) and shape (serialized.size(),) + df.shape. FixedLenFeature entries with a default_value are optional. With no default value, we will fail if that Feature is missing from any example in serialized. Each FixedLenSequenceFeature df maps to a Tensor of the specified type (or tf.float32 if not specified) and shape (serialized.size(), None) + df.shape. All examples in serialized will be padded with default_value along the second dimension. Each RaggedFeature maps to a RaggedTensor of the specified type. It is formed by stacking the RaggedTensor for each example, where the RaggedTensor for each individual example is constructed using the tensors specified by RaggedTensor.values_key and RaggedTensor.partition. See the tf.io.RaggedFeature documentation for details and examples. Examples: For example, if one expects a tf.float32 VarLenFeature ft and three serialized Examples are provided: serialized = [
features
{ feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } },
features
{ feature []},
features
{ feature { key: "ft" value { float_list { value: [3.0] } } }
]
then the output will look like: {"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]],
values=[1.0, 2.0, 3.0],
dense_shape=(3, 2)) }
If instead a FixedLenSequenceFeature with default_value = -1.0 and shape=[] is used then the output will look like: {"ft": [[1.0, 2.0], [3.0, -1.0]]}
Given two Example input protos in serialized: [
features {
feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } }
feature { key: "gps" value { float_list { value: [] } } }
},
features {
feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } }
feature { key: "dank" value { int64_list { value: [ 42 ] } } }
feature { key: "gps" value { } }
}
]
And arguments example_names: ["input0", "input1"],
features: {
"kw": VarLenFeature(tf.string),
"dank": VarLenFeature(tf.int64),
"gps": VarLenFeature(tf.float32),
}
Then the output is a dictionary: {
"kw": SparseTensor(
indices=[[0, 0], [0, 1], [1, 0]],
values=["knit", "big", "emmy"]
dense_shape=[2, 2]),
"dank": SparseTensor(
indices=[[1, 0]],
values=[42],
dense_shape=[2, 1]),
"gps": SparseTensor(
indices=[],
values=[],
dense_shape=[2, 0]),
}
For dense results in two serialized Examples: [
features {
feature { key: "age" value { int64_list { value: [ 0 ] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
},
features {
feature { key: "age" value { int64_list { value: [] } } }
feature { key: "gender" value { bytes_list { value: [ "f" ] } } }
}
]
We can use arguments: example_names: ["input0", "input1"],
features: {
"age": FixedLenFeature([], dtype=tf.int64, default_value=-1),
"gender": FixedLenFeature([], dtype=tf.string),
}
And the expected output is: {
"age": [[0], [-1]],
"gender": [["f"], ["f"]],
}
An alternative to VarLenFeature to obtain a SparseTensor is SparseFeature. For example, given two Example input protos in serialized: [
features {
feature { key: "val" value { float_list { value: [ 0.5, -1.0 ] } } }
feature { key: "ix" value { int64_list { value: [ 3, 20 ] } } }
},
features {
feature { key: "val" value { float_list { value: [ 0.0 ] } } }
feature { key: "ix" value { int64_list { value: [ 42 ] } } }
}
]
And arguments example_names: ["input0", "input1"],
features: {
"sparse": SparseFeature(
index_key="ix", value_key="val", dtype=tf.float32, size=100),
}
Then the output is a dictionary: {
"sparse": SparseTensor(
indices=[[0, 3], [0, 20], [1, 42]],
values=[0.5, -1.0, 0.0]
dense_shape=[2, 100]),
}
See the tf.io.RaggedFeature documentation for examples showing how RaggedFeature can be used to obtain RaggedTensors.
Args
serialized A vector (1-D Tensor) of strings, a batch of binary serialized Example protos.
features A dict mapping feature keys to FixedLenFeature, VarLenFeature, SparseFeature, and RaggedFeature values.
example_names A vector (1-D Tensor) of strings (optional), the names of the serialized protos in the batch.
name A name for this operation (optional).
Returns A dict mapping feature keys to Tensor, SparseTensor, and RaggedTensor values.
Raises
ValueError if any feature is invalid. | tensorflow.io.parse_example |
tf.io.parse_sequence_example View source on GitHub Parses a batch of SequenceExample protos. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.parse_sequence_example
tf.io.parse_sequence_example(
serialized, context_features=None, sequence_features=None, example_names=None,
name=None
)
Parses a vector of serialized SequenceExample protos given in serialized. This op parses serialized sequence examples into a tuple of dictionaries, each mapping keys to Tensor and SparseTensor objects. The first dictionary contains mappings for keys appearing in context_features, and the second dictionary contains mappings for keys appearing in sequence_features. At least one of context_features and sequence_features must be provided and non-empty. The context_features keys are associated with a SequenceExample as a whole, independent of time / frame. In contrast, the sequence_features keys provide a way to access variable-length data within the FeatureList section of the SequenceExample proto. While the shapes of context_features values are fixed with respect to frame, the frame dimension (the first dimension) of sequence_features values may vary between SequenceExample protos, and even between feature_list keys within the same SequenceExample. context_features contains VarLenFeature, RaggedFeature, and FixedLenFeature objects. Each VarLenFeature is mapped to a SparseTensor; each RaggedFeature is mapped to a RaggedTensor; and each FixedLenFeature is mapped to a Tensor, of the specified type, shape, and default value. sequence_features contains VarLenFeature, RaggedFeature, and FixedLenSequenceFeature objects. Each VarLenFeature is mapped to a SparseTensor; each RaggedFeature is mapped to a RaggedTensor; and eachFixedLenSequenceFeatureis mapped to aTensor, each of the specified type. The shape will be(B,T,) + df.dense_shapeforFixedLenSequenceFeaturedf, whereBis the batch size, andTis the length of the associatedFeatureListin theSequenceExample. For instance,FixedLenSequenceFeature([])yields a scalar 2-DTensorof static shape[None, None]and dynamic shape[B, T], whileFixedLenSequenceFeature([k])(forint k >= 1) yields a 3-D matrixTensorof static shape[None, None, k]and dynamic shape[B, T, k]`. Like the input, the resulting output tensors have a batch dimension. This means that the original per-example shapes of VarLenFeatures and FixedLenSequenceFeatures can be lost. To handle that situation, this op also provides dicts of shape tensors as part of the output. There is one dict for the context features, and one for the feature_list features. Context features of type FixedLenFeatures will not be present, since their shapes are already known by the caller. In situations where the input 'FixedLenFeature`s are of different lengths across examples, the shorter examples will be padded with default datatype values: 0 for numeric types, and the empty string for string types. Each SparseTensor corresponding to sequence_features represents a ragged vector. Its indices are [time, index], where time is the FeatureList entry and index is the value's index in the list of values associated with that time. FixedLenFeature entries with a default_value and FixedLenSequenceFeature entries with allow_missing=True are optional; otherwise, we will fail if that Feature or FeatureList is missing from any example in serialized. example_name may contain a descriptive name for the corresponding serialized proto. This may be useful for debugging purposes, but it has no effect on the output. If not None, example_name must be a scalar.
Args
serialized A vector (1-D Tensor) of type string containing binary serialized SequenceExample protos.
context_features A dict mapping feature keys to FixedLenFeature or VarLenFeature or RaggedFeature values. These features are associated with a SequenceExample as a whole.
sequence_features A dict mapping feature keys to FixedLenSequenceFeature or VarLenFeature or RaggedFeature values. These features are associated with data within the FeatureList section of the SequenceExample proto.
example_names A vector (1-D Tensor) of strings (optional), the name of the serialized protos.
name A name for this operation (optional).
Returns A tuple of three dicts, each mapping keys to Tensors, SparseTensors, and RaggedTensor. The first dict contains the context key/values, the second dict contains the feature_list key/values, and the final dict contains the lengths of any dense feature_list features.
Raises
ValueError if any feature is invalid. | tensorflow.io.parse_sequence_example |
tf.io.parse_single_example View source on GitHub Parses a single Example proto.
tf.io.parse_single_example(
serialized, features, example_names=None, name=None
)
Similar to parse_example, except: For dense tensors, the returned Tensor is identical to the output of parse_example, except there is no batch dimension, the output shape is the same as the shape given in dense_shape. For SparseTensors, the first (batch) column of the indices matrix is removed (the indices matrix is a column vector), the values vector is unchanged, and the first (batch_size) entry of the shape vector is removed (it is now a single element vector). One might see performance advantages by batching Example protos with parse_example instead of using this function directly.
Args
serialized A scalar string Tensor, a single serialized Example.
features A dict mapping feature keys to FixedLenFeature or VarLenFeature values.
example_names (Optional) A scalar string Tensor, the associated name.
name A name for this operation (optional).
Returns A dict mapping feature keys to Tensor and SparseTensor values.
Raises
ValueError if any feature is invalid. | tensorflow.io.parse_single_example |
tf.io.parse_single_sequence_example View source on GitHub Parses a single SequenceExample proto. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.parse_single_sequence_example, tf.compat.v1.parse_single_sequence_example
tf.io.parse_single_sequence_example(
serialized, context_features=None, sequence_features=None, example_name=None,
name=None
)
Parses a single serialized SequenceExample proto given in serialized. This op parses a serialized sequence example into a tuple of dictionaries, each mapping keys to Tensor and SparseTensor objects. The first dictionary contains mappings for keys appearing in context_features, and the second dictionary contains mappings for keys appearing in sequence_features. At least one of context_features and sequence_features must be provided and non-empty. The context_features keys are associated with a SequenceExample as a whole, independent of time / frame. In contrast, the sequence_features keys provide a way to access variable-length data within the FeatureList section of the SequenceExample proto. While the shapes of context_features values are fixed with respect to frame, the frame dimension (the first dimension) of sequence_features values may vary between SequenceExample protos, and even between feature_list keys within the same SequenceExample. context_features contains VarLenFeature, RaggedFeature, and FixedLenFeature objects. Each VarLenFeature is mapped to a SparseTensor; each RaggedFeature is mapped to a RaggedTensor; and each FixedLenFeature is mapped to a Tensor, of the specified type, shape, and default value. sequence_features contains VarLenFeature, RaggedFeature, and FixedLenSequenceFeature objects. Each VarLenFeature is mapped to a SparseTensor; each RaggedFeature is mapped to a RaggedTensor; and each FixedLenSequenceFeature is mapped to a Tensor, each of the specified type. The shape will be (T,) + df.dense_shape for FixedLenSequenceFeature df, where T is the length of the associated FeatureList in the SequenceExample. For instance, FixedLenSequenceFeature([]) yields a scalar 1-D Tensor of static shape [None] and dynamic shape [T], while FixedLenSequenceFeature([k]) (for int k >= 1) yields a 2-D matrix Tensor of static shape [None, k] and dynamic shape [T, k]. Each SparseTensor corresponding to sequence_features represents a ragged vector. Its indices are [time, index], where time is the FeatureList entry and index is the value's index in the list of values associated with that time. FixedLenFeature entries with a default_value and FixedLenSequenceFeature entries with allow_missing=True are optional; otherwise, we will fail if that Feature or FeatureList is missing from any example in serialized. example_name may contain a descriptive name for the corresponding serialized proto. This may be useful for debugging purposes, but it has no effect on the output. If not None, example_name must be a scalar. Note that the batch version of this function, tf.parse_sequence_example, is written for better memory efficiency and will be faster on large SequenceExamples.
Args
serialized A scalar (0-D Tensor) of type string, a single binary serialized SequenceExample proto.
context_features A dict mapping feature keys to FixedLenFeature or VarLenFeature or RaggedFeature values. These features are associated with a SequenceExample as a whole.
sequence_features A dict mapping feature keys to FixedLenSequenceFeature or VarLenFeature or RaggedFeature values. These features are associated with data within the FeatureList section of the SequenceExample proto.
example_name A scalar (0-D Tensor) of strings (optional), the name of the serialized proto.
name A name for this operation (optional).
Returns A tuple of two dicts, each mapping keys to Tensors and SparseTensors and RaggedTensors. The first dict contains the context key/values. The second dict contains the feature_list key/values.
Raises
ValueError if any feature is invalid. | tensorflow.io.parse_single_sequence_example |
tf.io.parse_tensor Transforms a serialized tensorflow.TensorProto proto into a Tensor. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.parse_tensor, tf.compat.v1.parse_tensor
tf.io.parse_tensor(
serialized, out_type, name=None
)
Args
serialized A Tensor of type string. A scalar string containing a serialized TensorProto proto.
out_type A tf.DType. The type of the serialized tensor. The provided type must match the type of the serialized tensor and no implicit conversion will take place.
name A name for the operation (optional).
Returns A Tensor of type out_type. | tensorflow.io.parse_tensor |
tf.io.RaggedFeature Configuration for passing a RaggedTensor input feature. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature
tf.io.RaggedFeature(
dtype, value_key=None, partitions=(), row_splits_dtype=tf.dtypes.int32,
validate=False
)
value_key specifies the feature key for a variable-length list of values; and partitions specifies zero or more feature keys for partitioning those values into higher dimensions. Each element of partitions must be one of the following: tf.io.RaggedFeature.RowSplits(key: string) tf.io.RaggedFeature.RowLengths(key: string) tf.io.RaggedFeature.RowStarts(key: string) tf.io.RaggedFeature.RowLimits(key: string) tf.io.RaggedFeature.ValueRowIds(key: string)
tf.io.RaggedFeature.UniformRowLength(length: int). Where key is a feature key whose values are used to partition the values. Partitions are listed from outermost to innermost.
If len(partitions) == 0 (the default), then: A feature from a single tf.Example is parsed into a 1D tf.Tensor. A feature from a batch of tf.Examples is parsed into a 2D tf.RaggedTensor, where the outer dimension is the batch dimension, and the inner (ragged) dimension is the feature length in each example.
If len(partitions) == 1, then: A feature from a single tf.Example is parsed into a 2D tf.RaggedTensor, where the values taken from the value_key are separated into rows using the partition key. A feature from a batch of tf.Examples is parsed into a 3D tf.RaggedTensor, where the outer dimension is the batch dimension, the two inner dimensions are formed by separating the value_key values from each example into rows using that example's partition key.
If len(partitions) > 1, then: A feature from a single tf.Example is parsed into a tf.RaggedTensor whose rank is len(partitions)+1, and whose ragged_rank is len(partitions). A feature from a batch of tf.Examples is parsed into a tf.RaggedTensor whose rank is len(partitions)+2 and whose ragged_rank is len(partitions)+1, where the outer dimension is the batch dimension.
There is one exception: if the final (i.e., innermost) element(s) of partitions are UniformRowLengths, then the values are simply reshaped (as a higher-dimensional tf.Tensor), rather than being wrapped in a tf.RaggedTensor. Examples
import google.protobuf.text_format as pbtext
example_batch = [
pbtext.Merge(r'''
features {
feature {key: "v" value {int64_list {value: [3, 1, 4, 1, 5, 9]} } }
feature {key: "s1" value {int64_list {value: [0, 2, 3, 3, 6]} } }
feature {key: "s2" value {int64_list {value: [0, 2, 3, 4]} } }
}''', tf.train.Example()).SerializeToString(),
pbtext.Merge(r'''
features {
feature {key: "v" value {int64_list {value: [2, 7, 1, 8, 2, 8, 1]} } }
feature {key: "s1" value {int64_list {value: [0, 3, 4, 5, 7]} } }
feature {key: "s2" value {int64_list {value: [0, 1, 1, 4]} } }
}''', tf.train.Example()).SerializeToString()]
features = {
# Zero partitions: returns 1D tf.Tensor for each Example.
'f1': tf.io.RaggedFeature(value_key="v", dtype=tf.int64),
# One partition: returns 2D tf.RaggedTensor for each Example.
'f2': tf.io.RaggedFeature(value_key="v", dtype=tf.int64, partitions=[
tf.io.RaggedFeature.RowSplits("s1")]),
# Two partitions: returns 3D tf.RaggedTensor for each Example.
'f3': tf.io.RaggedFeature(value_key="v", dtype=tf.int64, partitions=[
tf.io.RaggedFeature.RowSplits("s2"),
tf.io.RaggedFeature.RowSplits("s1")])
}
feature_dict = tf.io.parse_single_example(example_batch[0], features)
for (name, val) in sorted(feature_dict.items()):
print('%s: %s' % (name, val))
f1: tf.Tensor([3 1 4 1 5 9], shape=(6,), dtype=int64)
f2: <tf.RaggedTensor [[3, 1], [4], [], [1, 5, 9]]>
f3: <tf.RaggedTensor [[[3, 1], [4]], [[]], [[1, 5, 9]]]>
feature_dict = tf.io.parse_example(example_batch, features)
for (name, val) in sorted(feature_dict.items()):
print('%s: %s' % (name, val))
f1: <tf.RaggedTensor [[3, 1, 4, 1, 5, 9],
[2, 7, 1, 8, 2, 8, 1]]>
f2: <tf.RaggedTensor [[[3, 1], [4], [], [1, 5, 9]],
[[2, 7, 1], [8], [2], [8, 1]]]>
f3: <tf.RaggedTensor [[[[3, 1], [4]], [[]], [[1, 5, 9]]],
[[[2, 7, 1]], [], [[8], [2], [8, 1]]]]>
Fields:
dtype: Data type of the RaggedTensor. Must be one of: tf.dtypes.int64, tf.dtypes.float32, tf.dtypes.string.
value_key: (Optional.) Key for a Feature in the input Example, whose parsed Tensor will be the resulting RaggedTensor.flat_values. If not specified, then it defaults to the key for this RaggedFeature.
partitions: (Optional.) A list of objects specifying the row-partitioning tensors (from outermost to innermost). Each entry in this list must be one of: tf.io.RaggedFeature.RowSplits(key: string) tf.io.RaggedFeature.RowLengths(key: string) tf.io.RaggedFeature.RowStarts(key: string) tf.io.RaggedFeature.RowLimits(key: string) tf.io.RaggedFeature.ValueRowIds(key: string)
tf.io.RaggedFeature.UniformRowLength(length: int). Where key is a key for a Feature in the input Example, whose parsed Tensor will be the resulting row-partitioning tensor.
row_splits_dtype: (Optional.) Data type for the row-partitioning tensor(s). One of int32 or int64. Defaults to int32.
validate: (Optional.) Boolean indicating whether or not to validate that the input values form a valid RaggedTensor. Defaults to False.
Attributes
dtype
value_key
partitions
row_splits_dtype
validate
Child Classes class RowLengths class RowLimits class RowSplits class RowStarts class UniformRowLength class ValueRowIds | tensorflow.io.raggedfeature |
tf.io.RaggedFeature.RowLengths RowLengths(key,) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature.RowLengths
tf.io.RaggedFeature.RowLengths(
key
)
Attributes
key | tensorflow.io.raggedfeature.rowlengths |
tf.io.RaggedFeature.RowLimits RowLimits(key,) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature.RowLimits
tf.io.RaggedFeature.RowLimits(
key
)
Attributes
key | tensorflow.io.raggedfeature.rowlimits |
tf.io.RaggedFeature.RowSplits RowSplits(key,) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature.RowSplits
tf.io.RaggedFeature.RowSplits(
key
)
Attributes
key | tensorflow.io.raggedfeature.rowsplits |
tf.io.RaggedFeature.RowStarts RowStarts(key,) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature.RowStarts
tf.io.RaggedFeature.RowStarts(
key
)
Attributes
key | tensorflow.io.raggedfeature.rowstarts |
tf.io.RaggedFeature.UniformRowLength UniformRowLength(length,) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature.UniformRowLength
tf.io.RaggedFeature.UniformRowLength(
length
)
Attributes
length | tensorflow.io.raggedfeature.uniformrowlength |
tf.io.RaggedFeature.ValueRowIds ValueRowIds(key,) View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.RaggedFeature.ValueRowIds
tf.io.RaggedFeature.ValueRowIds(
key
)
Attributes
key | tensorflow.io.raggedfeature.valuerowids |
tf.io.read_file Reads and outputs the entire contents of the input filename. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.read_file, tf.compat.v1.read_file
tf.io.read_file(
filename, name=None
)
Args
filename A Tensor of type string.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.read_file |
tf.io.serialize_many_sparse View source on GitHub Serialize N-minibatch SparseTensor into an [N, 3] Tensor.
tf.io.serialize_many_sparse(
sp_input, out_type=tf.dtypes.string, name=None
)
The SparseTensor must have rank R greater than 1, and the first dimension is treated as the minibatch dimension. Elements of the SparseTensor must be sorted in increasing order of this first dimension. The serialized SparseTensor objects going into each row of the output Tensor will have rank R-1. The minibatch size N is extracted from sparse_shape[0].
Args
sp_input The input rank R SparseTensor.
out_type The dtype to use for serialization.
name A name prefix for the returned tensors (optional).
Returns A matrix (2-D Tensor) with N rows and 3 columns. Each column represents serialized SparseTensor's indices, values, and shape (respectively).
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.io.serialize_many_sparse |
tf.io.serialize_sparse View source on GitHub Serialize a SparseTensor into a 3-vector (1-D Tensor) object.
tf.io.serialize_sparse(
sp_input, out_type=tf.dtypes.string, name=None
)
Args
sp_input The input SparseTensor.
out_type The dtype to use for serialization.
name A name prefix for the returned tensors (optional).
Returns A 3-vector (1-D Tensor), with each column representing the serialized SparseTensor's indices, values, and shape (respectively).
Raises
TypeError If sp_input is not a SparseTensor. | tensorflow.io.serialize_sparse |
tf.io.serialize_tensor Transforms a Tensor into a serialized TensorProto proto. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.serialize_tensor, tf.compat.v1.serialize_tensor
tf.io.serialize_tensor(
tensor, name=None
)
Args
tensor A Tensor. A Tensor of type T.
name A name for the operation (optional).
Returns A Tensor of type string. | tensorflow.io.serialize_tensor |
tf.io.SparseFeature View source on GitHub Configuration for parsing a sparse input feature from an Example. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.SparseFeature, tf.compat.v1.io.SparseFeature
tf.io.SparseFeature(
index_key, value_key, dtype, size, already_sorted=False
)
Note, preferably use VarLenFeature (possibly in combination with a SequenceExample) in order to parse out SparseTensors instead of SparseFeature due to its simplicity. Closely mimicking the SparseTensor that will be obtained by parsing an Example with a SparseFeature config, a SparseFeature contains a value_key: The name of key for a Feature in the Example whose parsed Tensor will be the resulting SparseTensor.values. index_key: A list of names - one for each dimension in the resulting SparseTensor whose indices[i][dim] indicating the position of the i-th value in the dim dimension will be equal to the i-th value in the Feature with key named index_key[dim] in the Example. size: A list of ints for the resulting SparseTensor.dense_shape. For example, we can represent the following 2D SparseTensor SparseTensor(indices=[[3, 1], [20, 0]],
values=[0.5, -1.0]
dense_shape=[100, 3])
with an Example input proto features {
feature { key: "val" value { float_list { value: [ 0.5, -1.0 ] } } }
feature { key: "ix0" value { int64_list { value: [ 3, 20 ] } } }
feature { key: "ix1" value { int64_list { value: [ 1, 0 ] } } }
}
and SparseFeature config with 2 index_keys SparseFeature(index_key=["ix0", "ix1"],
value_key="val",
dtype=tf.float32,
size=[100, 3])
Fields:
index_key: A single string name or a list of string names of index features. For each key the underlying feature's type must be int64 and its length must always match that of the value_key feature. To represent SparseTensors with a dense_shape of rank higher than 1 a list of length rank should be used.
value_key: Name of value feature. The underlying feature's type must be dtype and its length must always match that of all the index_keys' features.
dtype: Data type of the value_key feature.
size: A Python int or list thereof specifying the dense shape. Should be a list if and only if index_key is a list. In that case the list must be equal to the length of index_key. Each for each entry i all values in the index_key[i] feature must be in [0, size[i]).
already_sorted: A Python boolean to specify whether the values in value_key are already sorted by their index position. If so skip sorting. False by default (optional).
Attributes
index_key
value_key
dtype
size
already_sorted | tensorflow.io.sparsefeature |
tf.io.TFRecordOptions View source on GitHub Options used for manipulating TFRecord files. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.TFRecordOptions, tf.compat.v1.python_io.TFRecordOptions
tf.io.TFRecordOptions(
compression_type=None, flush_mode=None, input_buffer_size=None,
output_buffer_size=None, window_bits=None, compression_level=None,
compression_method=None, mem_level=None, compression_strategy=None
)
Args
compression_type "GZIP", "ZLIB", or "" (no compression).
flush_mode flush mode or None, Default: Z_NO_FLUSH.
input_buffer_size int or None.
output_buffer_size int or None.
window_bits int or None.
compression_level 0 to 9, or None.
compression_method compression method or None.
mem_level 1 to 9, or None.
compression_strategy strategy or None. Default: Z_DEFAULT_STRATEGY.
Raises
ValueError If compression_type is invalid. Methods get_compression_type_string View source
@classmethod
get_compression_type_string(
options
)
Convert various option types to a unified string.
Args
options TFRecordOption, TFRecordCompressionType, or string.
Returns Compression type as string (e.g. 'ZLIB', 'GZIP', or '').
Raises
ValueError If compression_type is invalid.
Class Variables
compression_type_map | tensorflow.io.tfrecordoptions |
tf.io.TFRecordWriter View source on GitHub A class to write records to a TFRecords file. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.TFRecordWriter, tf.compat.v1.python_io.TFRecordWriter
tf.io.TFRecordWriter(
path, options=None
)
TFRecords tutorial TFRecords is a binary format which is optimized for high throughput data retrieval, generally in conjunction with tf.data. TFRecordWriter is used to write serialized examples to a file for later consumption. The key steps are: Ahead of time: Convert data into a serialized format
Write the serialized data to one or more files During training or evaluation:
Read serialized examples into memory Parse (deserialize) examples A minimal example is given below:
import tempfile
example_path = os.path.join(tempfile.gettempdir(), "example.tfrecords")
np.random.seed(0)
# Write the records to a file.
with tf.io.TFRecordWriter(example_path) as file_writer:
for _ in range(4):
x, y = np.random.random(), np.random.random()
record_bytes = tf.train.Example(features=tf.train.Features(feature={
"x": tf.train.Feature(float_list=tf.train.FloatList(value=[x])),
"y": tf.train.Feature(float_list=tf.train.FloatList(value=[y])),
})).SerializeToString()
file_writer.write(record_bytes)
# Read the data back out.
def decode_fn(record_bytes):
return tf.io.parse_single_example(
# Data
record_bytes,
# Schema
{"x": tf.io.FixedLenFeature([], dtype=tf.float32),
"y": tf.io.FixedLenFeature([], dtype=tf.float32)}
)
for batch in tf.data.TFRecordDataset([example_path]).map(decode_fn):
print("x = {x:.4f}, y = {y:.4f}".format(**batch))
x = 0.5488, y = 0.7152
x = 0.6028, y = 0.5449
x = 0.4237, y = 0.6459
x = 0.4376, y = 0.8918
This class implements __enter__ and __exit__, and can be used in with blocks like a normal file. (See the usage example above.)
Args
path The path to the TFRecords file.
options (optional) String specifying compression type, TFRecordCompressionType, or TFRecordOptions object.
Raises
IOError If path cannot be opened for writing.
ValueError If valid compression_type can't be determined from options. Methods close View source
close()
Close the file. flush View source
flush()
Flush the file. write View source
write(
record
)
Write a string record to the file.
Args
record str __enter__
__enter__()
enter(self: object) -> object __exit__
__exit__()
exit(self: tensorflow.python._pywrap_record_io.RecordWriter, *args) -> None | tensorflow.io.tfrecordwriter |
tf.io.VarLenFeature View source on GitHub Configuration for parsing a variable-length input feature. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.VarLenFeature, tf.compat.v1.io.VarLenFeature
tf.io.VarLenFeature(
dtype
)
Fields:
dtype: Data type of input.
Attributes
dtype | tensorflow.io.varlenfeature |
tf.io.write_file Writes contents to the file at input filename. Creates file and recursively View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.write_file, tf.compat.v1.write_file
tf.io.write_file(
filename, contents, name=None
)
creates directory if not existing.
Args
filename A Tensor of type string. scalar. The name of the file to which we write the contents.
contents A Tensor of type string. scalar. The content to be written to the output file.
name A name for the operation (optional).
Returns The created Operation. | tensorflow.io.write_file |
tf.io.write_graph View source on GitHub Writes a graph proto to a file. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.io.write_graph, tf.compat.v1.train.write_graph
tf.io.write_graph(
graph_or_graph_def, logdir, name, as_text=True
)
The graph is written as a text proto unless as_text is False. v = tf.Variable(0, name='my_variable')
sess = tf.compat.v1.Session()
tf.io.write_graph(sess.graph_def, '/tmp/my-model', 'train.pbtxt')
or v = tf.Variable(0, name='my_variable')
sess = tf.compat.v1.Session()
tf.io.write_graph(sess.graph, '/tmp/my-model', 'train.pbtxt')
Args
graph_or_graph_def A Graph or a GraphDef protocol buffer.
logdir Directory where to write the graph. This can refer to remote filesystems, such as Google Cloud Storage (GCS).
name Filename for the graph.
as_text If True, writes the graph as an ASCII proto.
Returns The path of the output proto file. | tensorflow.io.write_graph |
tf.is_tensor View source on GitHub Checks whether x is a TF-native type that can be passed to many TF ops. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.is_tensor
tf.is_tensor(
x
)
Use is_tensor to differentiate types that can ingested by TensorFlow ops without any conversion (e.g., tf.Tensor, tf.SparseTensor, and tf.RaggedTensor) from types that need to be converted into tensors before they are ingested (e.g., numpy ndarray and Python scalars). For example, in the following code block: if not tf.is_tensor(t):
t = tf.convert_to_tensor(t)
return t.dtype
we check to make sure that t is a tensor (and convert it if not) before accessing its shape and dtype.
Args
x A python object to check.
Returns True if x is a tensor or "tensor-like", False if not. | tensorflow.is_tensor |
Module: tf.keras Implementation of the Keras API meant to be a high-level API for TensorFlow. Detailed documentation and user guides are available at tensorflow.org. Modules activations module: Built-in activation functions. applications module: Keras Applications are canned architectures with pre-trained weights. backend module: Keras backend API. callbacks module: Callbacks: utilities called at certain points during model training. constraints module: Constraints: functions that impose constraints on weight values. datasets module: Public API for tf.keras.datasets namespace. estimator module: Keras estimator API. experimental module: Public API for tf.keras.experimental namespace. initializers module: Keras initializer serialization / deserialization. layers module: Keras layers API. losses module: Built-in loss functions. metrics module: Built-in metrics. mixed_precision module: Keras mixed precision API. models module: Code for model cloning, plus model-related API entries. optimizers module: Built-in optimizer classes. preprocessing module: Keras data preprocessing utils. regularizers module: Built-in regularizers. utils module: Public API for tf.keras.utils namespace. wrappers module: Public API for tf.keras.wrappers namespace. Classes class Model: Model groups layers into an object with training and inference features. class Sequential: Sequential groups a linear stack of layers into a tf.keras.Model. Functions Input(...): Input() is used to instantiate a Keras tensor.
Other Members
version '2.4.0' | tensorflow.keras |
Module: tf.keras.activations Built-in activation functions. Functions deserialize(...): Returns activation function given a string identifier. elu(...): Exponential Linear Unit. exponential(...): Exponential activation function. gelu(...): Applies the Gaussian error linear unit (GELU) activation function. get(...): Returns function. hard_sigmoid(...): Hard sigmoid activation function. linear(...): Linear activation function (pass-through). relu(...): Applies the rectified linear unit activation function. selu(...): Scaled Exponential Linear Unit (SELU). serialize(...): Returns the string identifier of an activation function. sigmoid(...): Sigmoid activation function, sigmoid(x) = 1 / (1 + exp(-x)). softmax(...): Softmax converts a real vector to a vector of categorical probabilities. softplus(...): Softplus activation function, softplus(x) = log(exp(x) + 1). softsign(...): Softsign activation function, softsign(x) = x / (abs(x) + 1). swish(...): Swish activation function, swish(x) = x * sigmoid(x). tanh(...): Hyperbolic tangent activation function. | tensorflow.keras.activations |
tf.keras.activations.deserialize View source on GitHub Returns activation function given a string identifier. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.deserialize
tf.keras.activations.deserialize(
name, custom_objects=None
)
Args
name The name of the activation function.
custom_objects Optional {function_name: function_obj} dictionary listing user-provided activation functions.
Returns Corresponding activation function.
For example:
tf.keras.activations.deserialize('linear')
<function linear at 0x1239596a8>
tf.keras.activations.deserialize('sigmoid')
<function sigmoid at 0x123959510>
tf.keras.activations.deserialize('abcd')
Traceback (most recent call last):
ValueError: Unknown activation function:abcd
Raises
ValueError Unknown activation function if the input string does not denote any defined Tensorflow activation function. | tensorflow.keras.activations.deserialize |
tf.keras.activations.elu View source on GitHub Exponential Linear Unit. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.elu
tf.keras.activations.elu(
x, alpha=1.0
)
The exponential linear unit (ELU) with alpha > 0 is: x if x > 0 and alpha * (exp(x) - 1) if x < 0 The ELU hyperparameter alpha controls the value to which an ELU saturates for negative net inputs. ELUs diminish the vanishing gradient effect. ELUs have negative values which pushes the mean of the activations closer to zero. Mean activations that are closer to zero enable faster learning as they bring the gradient closer to the natural gradient. ELUs saturate to a negative value when the argument gets smaller. Saturation means a small derivative which decreases the variation and the information that is propagated to the next layer. Example Usage:
import tensorflow as tf
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3, 3), activation='elu',
input_shape=(28, 28, 1)))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='elu'))
model.add(tf.keras.layers.MaxPooling2D((2, 2)))
model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='elu'))
Arguments
x Input tensor.
alpha A scalar, slope of negative section. alpha controls the value to which an ELU saturates for negative net inputs.
Returns The exponential linear unit (ELU) activation function: x if x > 0 and alpha * (exp(x) - 1) if x < 0.
Reference: Fast and Accurate Deep Network Learning by Exponential Linear Units (ELUs) (Clevert et al, 2016) | tensorflow.keras.activations.elu |
tf.keras.activations.exponential View source on GitHub Exponential activation function. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.exponential
tf.keras.activations.exponential(
x
)
For example:
a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)
b = tf.keras.activations.exponential(a)
b.numpy()
array([0.04978707, 0.36787945, 1., 2.7182817 , 20.085537], dtype=float32)
Arguments
x Input tensor.
Returns Tensor with exponential activation: exp(x). | tensorflow.keras.activations.exponential |
tf.keras.activations.gelu Applies the Gaussian error linear unit (GELU) activation function.
tf.keras.activations.gelu(
x, approximate=False
)
Gaussian error linear unit (GELU) computes x * P(X <= x), where P(X) ~ N(0, 1). The (GELU) nonlinearity weights inputs by their value, rather than gates inputs by their sign as in ReLU. For example:
x = tf.constant([-3.0, -1.0, 0.0, 1.0, 3.0], dtype=tf.float32)
y = tf.keras.activations.gelu(x)
y.numpy()
array([-0.00404951, -0.15865529, 0. , 0.8413447 , 2.9959507 ],
dtype=float32)
y = tf.keras.activations.gelu(x, approximate=True)
y.numpy()
array([-0.00363752, -0.15880796, 0. , 0.841192 , 2.9963627 ],
dtype=float32)
Arguments
x Input tensor.
approximate A bool, whether to enable approximation.
Returns The gaussian error linear activation: 0.5 * x * (1 + tanh(sqrt(2 / pi) * (x + 0.044715 * x^3))) if approximate is True or x * P(X <= x) = 0.5 * x * (1 + erf(x / sqrt(2))), where P(X) ~ N(0, 1), if approximate is False.
Reference: Gaussian Error Linear Units (GELUs) | tensorflow.keras.activations.gelu |
tf.keras.activations.get View source on GitHub Returns function. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.get
tf.keras.activations.get(
identifier
)
Arguments
identifier Function or string
Returns Function corresponding to the input string or input function.
For example:
tf.keras.activations.get('softmax')
<function softmax at 0x1222a3d90>
tf.keras.activations.get(tf.keras.activations.softmax)
<function softmax at 0x1222a3d90>
tf.keras.activations.get(None)
<function linear at 0x1239596a8>
tf.keras.activations.get(abs)
<built-in function abs>
tf.keras.activations.get('abcd')
Traceback (most recent call last):
ValueError: Unknown activation function:abcd
Raises
ValueError Input is an unknown function or string, i.e., the input does not denote any defined function. | tensorflow.keras.activations.get |
tf.keras.activations.hard_sigmoid View source on GitHub Hard sigmoid activation function. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.hard_sigmoid
tf.keras.activations.hard_sigmoid(
x
)
A faster approximation of the sigmoid activation. For example:
a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)
b = tf.keras.activations.hard_sigmoid(a)
b.numpy()
array([0. , 0.3, 0.5, 0.7, 1. ], dtype=float32)
Arguments
x Input tensor.
Returns The hard sigmoid activation, defined as: if x < -2.5: return 0 if x > 2.5: return 1
if -2.5 <= x <= 2.5: return 0.2 * x + 0.5 | tensorflow.keras.activations.hard_sigmoid |
tf.keras.activations.linear View source on GitHub Linear activation function (pass-through). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.linear
tf.keras.activations.linear(
x
)
For example:
a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)
b = tf.keras.activations.linear(a)
b.numpy()
array([-3., -1., 0., 1., 3.], dtype=float32)
Arguments
x Input tensor.
Returns The input, unmodified. | tensorflow.keras.activations.linear |
tf.keras.activations.relu View source on GitHub Applies the rectified linear unit activation function. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.relu
tf.keras.activations.relu(
x, alpha=0.0, max_value=None, threshold=0
)
With default values, this returns the standard ReLU activation: max(x, 0), the element-wise maximum of 0 and the input tensor. Modifying default parameters allows you to use non-zero thresholds, change the max value of the activation, and to use a non-zero multiple of the input for values below the threshold. For example:
foo = tf.constant([-10, -5, 0.0, 5, 10], dtype = tf.float32)
tf.keras.activations.relu(foo).numpy()
array([ 0., 0., 0., 5., 10.], dtype=float32)
tf.keras.activations.relu(foo, alpha=0.5).numpy()
array([-5. , -2.5, 0. , 5. , 10. ], dtype=float32)
tf.keras.activations.relu(foo, max_value=5).numpy()
array([0., 0., 0., 5., 5.], dtype=float32)
tf.keras.activations.relu(foo, threshold=5).numpy()
array([-0., -0., 0., 0., 10.], dtype=float32)
Arguments
x Input tensor or variable.
alpha A float that governs the slope for values lower than the threshold.
max_value A float that sets the saturation threshold (the largest value the function will return).
threshold A float giving the threshold value of the activation function below which values will be damped or set to zero.
Returns A Tensor representing the input tensor, transformed by the relu activation function. Tensor will be of the same shape and dtype of input x. | tensorflow.keras.activations.relu |
tf.keras.activations.selu View source on GitHub Scaled Exponential Linear Unit (SELU). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.selu
tf.keras.activations.selu(
x
)
The Scaled Exponential Linear Unit (SELU) activation function is defined as: if x > 0: return scale * x if x < 0: return scale * alpha * (exp(x) - 1) where alpha and scale are pre-defined constants (alpha=1.67326324 and scale=1.05070098). Basically, the SELU activation function multiplies scale (> 1) with the output of the tf.keras.activations.elu function to ensure a slope larger than one for positive inputs. The values of alpha and scale are chosen so that the mean and variance of the inputs are preserved between two consecutive layers as long as the weights are initialized correctly (see tf.keras.initializers.LecunNormal initializer) and the number of input units is "large enough" (see reference paper for more information). Example Usage:
num_classes = 10 # 10-class problem
model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(64, kernel_initializer='lecun_normal',
activation='selu'))
model.add(tf.keras.layers.Dense(32, kernel_initializer='lecun_normal',
activation='selu'))
model.add(tf.keras.layers.Dense(16, kernel_initializer='lecun_normal',
activation='selu'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))
Arguments
x A tensor or variable to compute the activation function for.
Returns The scaled exponential unit activation: scale * elu(x, alpha).
Notes: To be used together with the tf.keras.initializers.LecunNormal initializer. To be used together with the dropout variant tf.keras.layers.AlphaDropout (not regular dropout). References: Klambauer et al., 2017 | tensorflow.keras.activations.selu |
tf.keras.activations.serialize View source on GitHub Returns the string identifier of an activation function. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.serialize
tf.keras.activations.serialize(
activation
)
Arguments
activation Function object.
Returns String denoting the name attribute of the input function
For example:
tf.keras.activations.serialize(tf.keras.activations.tanh)
'tanh'
tf.keras.activations.serialize(tf.keras.activations.sigmoid)
'sigmoid'
tf.keras.activations.serialize('abcd')
Traceback (most recent call last):
ValueError: ('Cannot serialize', 'abcd')
Raises
ValueError The input function is not a valid one. | tensorflow.keras.activations.serialize |
tf.keras.activations.sigmoid View source on GitHub Sigmoid activation function, sigmoid(x) = 1 / (1 + exp(-x)). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.sigmoid
tf.keras.activations.sigmoid(
x
)
Applies the sigmoid activation function. For small values (<-5), sigmoid returns a value close to zero, and for large values (>5) the result of the function gets close to 1. Sigmoid is equivalent to a 2-element Softmax, where the second element is assumed to be zero. The sigmoid function always returns a value between 0 and 1. For example:
a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32)
b = tf.keras.activations.sigmoid(a)
b.numpy()
array([2.0611537e-09, 2.6894143e-01, 5.0000000e-01, 7.3105860e-01,
1.0000000e+00], dtype=float32)
Arguments
x Input tensor.
Returns Tensor with the sigmoid activation: 1 / (1 + exp(-x)). | tensorflow.keras.activations.sigmoid |
tf.keras.activations.softmax View source on GitHub Softmax converts a real vector to a vector of categorical probabilities. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.softmax
tf.keras.activations.softmax(
x, axis=-1
)
The elements of the output vector are in range (0, 1) and sum to 1. Each vector is handled independently. The axis argument sets which axis of the input the function is applied along. Softmax is often used as the activation for the last layer of a classification network because the result could be interpreted as a probability distribution. The softmax of each vector x is computed as exp(x) / tf.reduce_sum(exp(x)). The input values in are the log-odds of the resulting probability.
Arguments
x Input tensor.
axis Integer, axis along which the softmax normalization is applied.
Returns Tensor, output of softmax transformation (all values are non-negative and sum to 1).
Raises
ValueError In case dim(x) == 1. | tensorflow.keras.activations.softmax |
tf.keras.activations.softplus View source on GitHub Softplus activation function, softplus(x) = log(exp(x) + 1). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.softplus
tf.keras.activations.softplus(
x
)
Example Usage:
a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32)
b = tf.keras.activations.softplus(a)
b.numpy()
array([2.0611537e-09, 3.1326166e-01, 6.9314718e-01, 1.3132616e+00,
2.0000000e+01], dtype=float32)
Arguments
x Input tensor.
Returns The softplus activation: log(exp(x) + 1). | tensorflow.keras.activations.softplus |
tf.keras.activations.softsign View source on GitHub Softsign activation function, softsign(x) = x / (abs(x) + 1). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.softsign
tf.keras.activations.softsign(
x
)
Example Usage:
a = tf.constant([-1.0, 0.0, 1.0], dtype = tf.float32)
b = tf.keras.activations.softsign(a)
b.numpy()
array([-0.5, 0. , 0.5], dtype=float32)
Arguments
x Input tensor.
Returns The softsign activation: x / (abs(x) + 1). | tensorflow.keras.activations.softsign |
tf.keras.activations.swish Swish activation function, swish(x) = x * sigmoid(x). View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.swish
tf.keras.activations.swish(
x
)
Swish activation function which returns x*sigmoid(x). It is a smooth, non-monotonic function that consistently matches or outperforms ReLU on deep networks, it is unbounded above and bounded below. Example Usage:
a = tf.constant([-20, -1.0, 0.0, 1.0, 20], dtype = tf.float32)
b = tf.keras.activations.swish(a)
b.numpy()
array([-4.1223075e-08, -2.6894143e-01, 0.0000000e+00, 7.3105860e-01,
2.0000000e+01], dtype=float32)
Arguments
x Input tensor.
Returns The swish activation applied to x (see reference paper for details).
Reference: Ramachandran et al., 2017 | tensorflow.keras.activations.swish |
tf.keras.activations.tanh View source on GitHub Hyperbolic tangent activation function. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.activations.tanh
tf.keras.activations.tanh(
x
)
For example:
a = tf.constant([-3.0,-1.0, 0.0,1.0,3.0], dtype = tf.float32)
b = tf.keras.activations.tanh(a)
b.numpy()
array([-0.9950547, -0.7615942, 0., 0.7615942, 0.9950547], dtype=float32)
Arguments
x Input tensor.
Returns Tensor of same shape and dtype of input x, with tanh activation: tanh(x) = sinh(x)/cosh(x) = ((exp(x) - exp(-x))/(exp(x) + exp(-x))). | tensorflow.keras.activations.tanh |
Module: tf.keras.applications Keras Applications are canned architectures with pre-trained weights. Modules densenet module: DenseNet models for Keras. efficientnet module: EfficientNet models for Keras. imagenet_utils module: Utilities for ImageNet data preprocessing & prediction decoding. inception_resnet_v2 module: Inception-ResNet V2 model for Keras. inception_v3 module: Inception V3 model for Keras. mobilenet module: MobileNet v1 models for Keras. mobilenet_v2 module: MobileNet v2 models for Keras. mobilenet_v3 module: MobileNet v3 models for Keras. nasnet module: NASNet-A models for Keras. resnet module: ResNet models for Keras. resnet50 module: Public API for tf.keras.applications.resnet50 namespace. resnet_v2 module: ResNet v2 models for Keras. vgg16 module: VGG16 model for Keras. vgg19 module: VGG19 model for Keras. xception module: Xception V1 model for Keras. Functions DenseNet121(...): Instantiates the Densenet121 architecture. DenseNet169(...): Instantiates the Densenet169 architecture. DenseNet201(...): Instantiates the Densenet201 architecture. EfficientNetB0(...): Instantiates the EfficientNetB0 architecture. EfficientNetB1(...): Instantiates the EfficientNetB1 architecture. EfficientNetB2(...): Instantiates the EfficientNetB2 architecture. EfficientNetB3(...): Instantiates the EfficientNetB3 architecture. EfficientNetB4(...): Instantiates the EfficientNetB4 architecture. EfficientNetB5(...): Instantiates the EfficientNetB5 architecture. EfficientNetB6(...): Instantiates the EfficientNetB6 architecture. EfficientNetB7(...): Instantiates the EfficientNetB7 architecture. InceptionResNetV2(...): Instantiates the Inception-ResNet v2 architecture. InceptionV3(...): Instantiates the Inception v3 architecture. MobileNet(...): Instantiates the MobileNet architecture. MobileNetV2(...): Instantiates the MobileNetV2 architecture. MobileNetV3Large(...): Instantiates the MobileNetV3Large architecture. MobileNetV3Small(...): Instantiates the MobileNetV3Small architecture. NASNetLarge(...): Instantiates a NASNet model in ImageNet mode. NASNetMobile(...): Instantiates a Mobile NASNet model in ImageNet mode. ResNet101(...): Instantiates the ResNet101 architecture. ResNet101V2(...): Instantiates the ResNet101V2 architecture. ResNet152(...): Instantiates the ResNet152 architecture. ResNet152V2(...): Instantiates the ResNet152V2 architecture. ResNet50(...): Instantiates the ResNet50 architecture. ResNet50V2(...): Instantiates the ResNet50V2 architecture. VGG16(...): Instantiates the VGG16 model. VGG19(...): Instantiates the VGG19 architecture. Xception(...): Instantiates the Xception architecture. | tensorflow.keras.applications |
Module: tf.keras.applications.densenet DenseNet models for Keras. Reference:
Densely Connected Convolutional Networks (CVPR 2017) Functions DenseNet121(...): Instantiates the Densenet121 architecture. DenseNet169(...): Instantiates the Densenet169 architecture. DenseNet201(...): Instantiates the Densenet201 architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.densenet |
tf.keras.applications.densenet.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.densenet.decode_predictions
tf.keras.applications.densenet.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.densenet.decode_predictions |
tf.keras.applications.densenet.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.densenet.preprocess_input
tf.keras.applications.densenet.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The input pixels values are scaled between 0 and 1 and each channel is normalized with respect to the ImageNet dataset.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.densenet.preprocess_input |
tf.keras.applications.DenseNet121 View source on GitHub Instantiates the Densenet121 architecture. View aliases Main aliases
tf.keras.applications.densenet.DenseNet121 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.DenseNet121, tf.compat.v1.keras.applications.densenet.DenseNet121
tf.keras.applications.DenseNet121(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000
)
Reference:
Densely Connected Convolutional Networks (CVPR 2017) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For DenseNet, call tf.keras.applications.densenet.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance. | tensorflow.keras.applications.densenet121 |
tf.keras.applications.DenseNet169 View source on GitHub Instantiates the Densenet169 architecture. View aliases Main aliases
tf.keras.applications.densenet.DenseNet169 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.DenseNet169, tf.compat.v1.keras.applications.densenet.DenseNet169
tf.keras.applications.DenseNet169(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000
)
Reference:
Densely Connected Convolutional Networks (CVPR 2017) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For DenseNet, call tf.keras.applications.densenet.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance. | tensorflow.keras.applications.densenet169 |
tf.keras.applications.DenseNet201 View source on GitHub Instantiates the Densenet201 architecture. View aliases Main aliases
tf.keras.applications.densenet.DenseNet201 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.DenseNet201, tf.compat.v1.keras.applications.densenet.DenseNet201
tf.keras.applications.DenseNet201(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000
)
Reference:
Densely Connected Convolutional Networks (CVPR 2017) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For DenseNet, call tf.keras.applications.densenet.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance. | tensorflow.keras.applications.densenet201 |
Module: tf.keras.applications.efficientnet EfficientNet models for Keras. Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Functions EfficientNetB0(...): Instantiates the EfficientNetB0 architecture. EfficientNetB1(...): Instantiates the EfficientNetB1 architecture. EfficientNetB2(...): Instantiates the EfficientNetB2 architecture. EfficientNetB3(...): Instantiates the EfficientNetB3 architecture. EfficientNetB4(...): Instantiates the EfficientNetB4 architecture. EfficientNetB5(...): Instantiates the EfficientNetB5 architecture. EfficientNetB6(...): Instantiates the EfficientNetB6 architecture. EfficientNetB7(...): Instantiates the EfficientNetB7 architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...) | tensorflow.keras.applications.efficientnet |
tf.keras.applications.efficientnet.decode_predictions Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.efficientnet.decode_predictions
tf.keras.applications.efficientnet.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.efficientnet.decode_predictions |
tf.keras.applications.efficientnet.preprocess_input View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.efficientnet.preprocess_input
tf.keras.applications.efficientnet.preprocess_input(
x, data_format=None
) | tensorflow.keras.applications.efficientnet.preprocess_input |
tf.keras.applications.EfficientNetB0 Instantiates the EfficientNetB0 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB0 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB0, tf.compat.v1.keras.applications.efficientnet.EfficientNetB0
tf.keras.applications.EfficientNetB0(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb0 |
tf.keras.applications.EfficientNetB1 Instantiates the EfficientNetB1 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB1 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB1, tf.compat.v1.keras.applications.efficientnet.EfficientNetB1
tf.keras.applications.EfficientNetB1(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb1 |
tf.keras.applications.EfficientNetB2 Instantiates the EfficientNetB2 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB2 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB2, tf.compat.v1.keras.applications.efficientnet.EfficientNetB2
tf.keras.applications.EfficientNetB2(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb2 |
tf.keras.applications.EfficientNetB3 Instantiates the EfficientNetB3 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB3 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB3, tf.compat.v1.keras.applications.efficientnet.EfficientNetB3
tf.keras.applications.EfficientNetB3(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb3 |
tf.keras.applications.EfficientNetB4 Instantiates the EfficientNetB4 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB4 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB4, tf.compat.v1.keras.applications.efficientnet.EfficientNetB4
tf.keras.applications.EfficientNetB4(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb4 |
tf.keras.applications.EfficientNetB5 Instantiates the EfficientNetB5 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB5 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB5, tf.compat.v1.keras.applications.efficientnet.EfficientNetB5
tf.keras.applications.EfficientNetB5(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb5 |
tf.keras.applications.EfficientNetB6 Instantiates the EfficientNetB6 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB6 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB6, tf.compat.v1.keras.applications.efficientnet.EfficientNetB6
tf.keras.applications.EfficientNetB6(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb6 |
tf.keras.applications.EfficientNetB7 Instantiates the EfficientNetB7 architecture. View aliases Main aliases
tf.keras.applications.efficientnet.EfficientNetB7 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.EfficientNetB7, tf.compat.v1.keras.applications.efficientnet.EfficientNetB7
tf.keras.applications.EfficientNetB7(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks (ICML 2019) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json. If you have never configured it, it defaults to "channels_last".
Arguments
include_top Whether to include the fully-connected layer at the top of the network. Defaults to True.
weights One of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded. Defaults to 'imagenet'.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape Optional shape tuple, only to be specified if include_top is False. It should have exactly 3 inputs channels.
pooling Optional pooling mode for feature extraction when include_top is False. Defaults to None.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Defaults to 1000 (number of ImageNet classes).
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer. Defaults to 'softmax'.
Returns A keras.Model instance. | tensorflow.keras.applications.efficientnetb7 |
Module: tf.keras.applications.imagenet_utils Utilities for ImageNet data preprocessing & prediction decoding. Functions decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.imagenet_utils |
tf.keras.applications.imagenet_utils.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.imagenet_utils.decode_predictions
tf.keras.applications.imagenet_utils.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.imagenet_utils.decode_predictions |
tf.keras.applications.imagenet_utils.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.imagenet_utils.preprocess_input
tf.keras.applications.imagenet_utils.preprocess_input(
x, data_format=None, mode='caffe'
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
mode One of "caffe", "tf" or "torch". Defaults to "caffe". caffe: will convert the images from RGB to BGR, then will zero-center each color channel with respect to the ImageNet dataset, without scaling. tf: will scale pixels between -1 and 1, sample-wise. torch: will scale pixels between 0 and 1 and then will normalize each channel with respect to the ImageNet dataset.
Returns Preprocessed numpy.array or a tf.Tensor with type float32.
Raises
ValueError In case of unknown mode or data_format argument. | tensorflow.keras.applications.imagenet_utils.preprocess_input |
tf.keras.applications.InceptionResNetV2 View source on GitHub Instantiates the Inception-ResNet v2 architecture. View aliases Main aliases
tf.keras.applications.inception_resnet_v2.InceptionResNetV2 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.InceptionResNetV2, tf.compat.v1.keras.applications.inception_resnet_v2.InceptionResNetV2
tf.keras.applications.InceptionResNetV2(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning (AAAI 2017) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For InceptionResNetV2, call tf.keras.applications.inception_resnet_v2.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (299, 299, 3) (with 'channels_last' data format) or (3, 299, 299) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 75. E.g. (150, 150, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
'avg' means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
'max' means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
**kwargs For backwards compatibility only.
Returns A keras.Model instance.
Raises
ValueError in case of invalid argument for weights, or invalid input shape.
ValueError if classifier_activation is not softmax or None when using a pretrained top layer. | tensorflow.keras.applications.inceptionresnetv2 |
tf.keras.applications.InceptionV3 View source on GitHub Instantiates the Inception v3 architecture. View aliases Main aliases
tf.keras.applications.inception_v3.InceptionV3 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.InceptionV3, tf.compat.v1.keras.applications.inception_v3.InceptionV3
tf.keras.applications.InceptionV3(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax'
)
Reference:
Rethinking the Inception Architecture for Computer Vision (CVPR 2016) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in the tf.keras.backend.image_data_format().
Note: each Keras Application expects a specific kind of input preprocessing. For InceptionV3, call tf.keras.applications.inception_v3.preprocess_input on your inputs before passing them to the model.
Arguments
include_top Boolean, whether to include the fully-connected layer at the top, as the last layer of the network. Default to True.
weights One of None (random initialization), imagenet (pre-training on ImageNet), or the path to the weights file to be loaded. Default to imagenet.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model. input_tensor is useful for sharing inputs between multiple different networks. Default to None.
input_shape Optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (299, 299, 3) (with channels_last data format) or (3, 299, 299) (with channels_first data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 75. E.g. (150, 150, 3) would be one valid value. input_shape will be ignored if the input_tensor is provided.
pooling Optional pooling mode for feature extraction when include_top is False.
None (default) means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified. Default to 1000.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
Returns A keras.Model instance.
Raises
ValueError in case of invalid argument for weights, or invalid input shape.
ValueError if classifier_activation is not softmax or None when using a pretrained top layer. | tensorflow.keras.applications.inceptionv3 |
Module: tf.keras.applications.inception_resnet_v2 Inception-ResNet V2 model for Keras. Reference:
Inception-v4, Inception-ResNet and the Impact of Residual Connections on Learning (AAAI 2017) Functions InceptionResNetV2(...): Instantiates the Inception-ResNet v2 architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.inception_resnet_v2 |
tf.keras.applications.inception_resnet_v2.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.inception_resnet_v2.decode_predictions
tf.keras.applications.inception_resnet_v2.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.inception_resnet_v2.decode_predictions |
tf.keras.applications.inception_resnet_v2.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.inception_resnet_v2.preprocess_input
tf.keras.applications.inception_resnet_v2.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.inception_resnet_v2.preprocess_input |
Module: tf.keras.applications.inception_v3 Inception V3 model for Keras. Reference:
Rethinking the Inception Architecture for Computer Vision (CVPR 2016) Functions InceptionV3(...): Instantiates the Inception v3 architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.inception_v3 |
tf.keras.applications.inception_v3.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.inception_v3.decode_predictions
tf.keras.applications.inception_v3.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.inception_v3.decode_predictions |
tf.keras.applications.inception_v3.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.inception_v3.preprocess_input
tf.keras.applications.inception_v3.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.inception_v3.preprocess_input |
Module: tf.keras.applications.mobilenet MobileNet v1 models for Keras. MobileNet is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices. MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance. The number of parameters and number of multiply-adds can be modified by using the alpha parameter, which increases/decreases the number of filters in each layer. By altering the image size and alpha parameter, all 16 models from the paper can be built, with ImageNet weights provided. The paper demonstrates the performance of MobileNets using alpha values of 1.0 (also called 100 % MobileNet), 0.75, 0.5 and 0.25. For each of these alpha values, weights for 4 different input image sizes are provided (224, 192, 160, 128). The following table describes the size and accuracy of the 100% MobileNet on size 224 x 224: Width Multiplier (alpha) | ImageNet Acc | Multiply-Adds (M) | Params (M) | 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 0.75 MobileNet-224 | 68.4 % | 325 | 2.6 | | 0.50 MobileNet-224 | 63.7 % | 149 | 1.3 | | 0.25 MobileNet-224 | 50.6 % | 41 | 0.5 | The following table describes the performance of the 100 % MobileNet on various input sizes: Resolution | ImageNet Acc | Multiply-Adds (M) | Params (M)
| 1.0 MobileNet-224 | 70.6 % | 529 | 4.2 | | 1.0 MobileNet-192 | 69.1 % | 529 | 4.2 | | 1.0 MobileNet-160 | 67.2 % | 529 | 4.2 | | 1.0 MobileNet-128 | 64.4 % | 529 | 4.2 | Reference: MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications Functions MobileNet(...): Instantiates the MobileNet architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.mobilenet |
tf.keras.applications.mobilenet.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.mobilenet.decode_predictions
tf.keras.applications.mobilenet.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.mobilenet.decode_predictions |
tf.keras.applications.mobilenet.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.mobilenet.preprocess_input
tf.keras.applications.mobilenet.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.mobilenet.preprocess_input |
tf.keras.applications.MobileNetV2 View source on GitHub Instantiates the MobileNetV2 architecture. View aliases Main aliases
tf.keras.applications.mobilenet_v2.MobileNetV2 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.MobileNetV2, tf.compat.v1.keras.applications.mobilenet_v2.MobileNetV2
tf.keras.applications.MobileNetV2(
input_shape=None, alpha=1.0, include_top=True, weights='imagenet',
input_tensor=None, pooling=None, classes=1000,
classifier_activation='softmax', **kwargs
)
Reference:
MobileNetV2: Inverted Residuals and Linear Bottlenecks (CVPR 2018) Optionally loads weights pre-trained on ImageNet.
Note: each Keras Application expects a specific kind of input preprocessing. For MobileNetV2, call tf.keras.applications.mobilenet_v2.preprocess_input on your inputs before passing them to the model.
Arguments
input_shape Optional shape tuple, to be specified if you would like to use a model with an input image resolution that is not (224, 224, 3). It should have exactly 3 inputs channels (224, 224, 3). You can also omit this option if you would like to infer input_shape from an input_tensor. If you choose to include both input_tensor and input_shape then input_shape will be used if they match, if the shapes do not match then we will throw an error. E.g. (160, 160, 3) would be one valid value.
alpha Float between 0 and 1. controls the width of the network. This is known as the width multiplier in the MobileNetV2 paper, but the name is kept for consistency with applications.MobileNetV1 model in Keras. If alpha < 1.0, proportionally decreases the number of filters in each layer. If alpha > 1.0, proportionally increases the number of filters in each layer. If alpha = 1, default number of filters from the paper are used at each layer.
include_top Boolean, whether to include the fully-connected layer at the top of the network. Defaults to True.
weights String, one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
pooling String, optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Integer, optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
**kwargs For backwards compatibility only.
Returns A keras.Model instance.
Raises
ValueError in case of invalid argument for weights, or invalid input shape or invalid alpha, rows when weights='imagenet'
ValueError if classifier_activation is not softmax or None when using a pretrained top layer. | tensorflow.keras.applications.mobilenetv2 |
tf.keras.applications.MobileNetV3Large Instantiates the MobileNetV3Large architecture. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.MobileNetV3Large
tf.keras.applications.MobileNetV3Large(
input_shape=None, alpha=1.0, minimalistic=False, include_top=True,
weights='imagenet', input_tensor=None, classes=1000, pooling=None,
dropout_rate=0.2, classifier_activation='softmax'
)
Reference:
Searching for MobileNetV3 (ICCV 2019) The following table describes the performance of MobileNets: MACs stands for Multiply Adds Classification Checkpoint MACs(M) Parameters(M) Top1 Accuracy Pixel1 CPU(ms) mobilenet_v3_large_1.0_224 217 5.4 75.6 51.2 mobilenet_v3_large_0.75_224 155 4.0 73.3 39.8 mobilenet_v3_large_minimalistic_1.0_224 209 3.9 72.3 44.1 mobilenet_v3_small_1.0_224 66 2.9 68.1 15.8 mobilenet_v3_small_0.75_224 44 2.4 65.4 12.8 mobilenet_v3_small_minimalistic_1.0_224 65 2.0 61.9 12.2 The weights for all 6 models are obtained and translated from the Tensorflow checkpoints from TensorFlow checkpoints found here. Optionally loads weights pre-trained on ImageNet.
Note: each Keras Application expects a specific kind of input preprocessing. For MobileNetV3, call tf.keras.applications.mobilenet_v3.preprocess_input on your inputs before passing them to the model.
Arguments
input_shape Optional shape tuple, to be specified if you would like to use a model with an input image resolution that is not (224, 224, 3). It should have exactly 3 inputs channels (224, 224, 3). You can also omit this option if you would like to infer input_shape from an input_tensor. If you choose to include both input_tensor and input_shape then input_shape will be used if they match, if the shapes do not match then we will throw an error. E.g. (160, 160, 3) would be one valid value.
alpha controls the width of the network. This is known as the depth multiplier in the MobileNetV3 paper, but the name is kept for consistency with MobileNetV1 in Keras. If alpha < 1.0, proportionally decreases the number of filters in each layer. If alpha > 1.0, proportionally increases the number of filters in each layer. If alpha = 1, default number of filters from the paper are used at each layer.
minimalistic In addition to large and small models this module also contains so-called minimalistic models, these models have the same per-layer dimensions characteristic as MobilenetV3 however, they don't utilize any of the advanced blocks (squeeze-and-excite units, hard-swish, and 5x5 convolutions). While these models are less efficient on CPU, they are much more performant on GPU/DSP.
include_top Boolean, whether to include the fully-connected layer at the top of the network. Defaults to True.
weights String, one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
pooling String, optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Integer, optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
dropout_rate fraction of the input units to drop on the last layer.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
Returns A keras.Model instance.
Raises
ValueError in case of invalid argument for weights, or invalid input shape or invalid alpha, rows when weights='imagenet'
ValueError if classifier_activation is not softmax or None when using a pretrained top layer. | tensorflow.keras.applications.mobilenetv3large |
tf.keras.applications.MobileNetV3Small Instantiates the MobileNetV3Small architecture. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.MobileNetV3Small
tf.keras.applications.MobileNetV3Small(
input_shape=None, alpha=1.0, minimalistic=False, include_top=True,
weights='imagenet', input_tensor=None, classes=1000, pooling=None,
dropout_rate=0.2, classifier_activation='softmax'
)
Reference:
Searching for MobileNetV3 (ICCV 2019) The following table describes the performance of MobileNets: MACs stands for Multiply Adds Classification Checkpoint MACs(M) Parameters(M) Top1 Accuracy Pixel1 CPU(ms) mobilenet_v3_large_1.0_224 217 5.4 75.6 51.2 mobilenet_v3_large_0.75_224 155 4.0 73.3 39.8 mobilenet_v3_large_minimalistic_1.0_224 209 3.9 72.3 44.1 mobilenet_v3_small_1.0_224 66 2.9 68.1 15.8 mobilenet_v3_small_0.75_224 44 2.4 65.4 12.8 mobilenet_v3_small_minimalistic_1.0_224 65 2.0 61.9 12.2 The weights for all 6 models are obtained and translated from the Tensorflow checkpoints from TensorFlow checkpoints found here. Optionally loads weights pre-trained on ImageNet.
Note: each Keras Application expects a specific kind of input preprocessing. For MobileNetV3, call tf.keras.applications.mobilenet_v3.preprocess_input on your inputs before passing them to the model.
Arguments
input_shape Optional shape tuple, to be specified if you would like to use a model with an input image resolution that is not (224, 224, 3). It should have exactly 3 inputs channels (224, 224, 3). You can also omit this option if you would like to infer input_shape from an input_tensor. If you choose to include both input_tensor and input_shape then input_shape will be used if they match, if the shapes do not match then we will throw an error. E.g. (160, 160, 3) would be one valid value.
alpha controls the width of the network. This is known as the depth multiplier in the MobileNetV3 paper, but the name is kept for consistency with MobileNetV1 in Keras. If alpha < 1.0, proportionally decreases the number of filters in each layer. If alpha > 1.0, proportionally increases the number of filters in each layer. If alpha = 1, default number of filters from the paper are used at each layer.
minimalistic In addition to large and small models this module also contains so-called minimalistic models, these models have the same per-layer dimensions characteristic as MobilenetV3 however, they don't utilize any of the advanced blocks (squeeze-and-excite units, hard-swish, and 5x5 convolutions). While these models are less efficient on CPU, they are much more performant on GPU/DSP.
include_top Boolean, whether to include the fully-connected layer at the top of the network. Defaults to True.
weights String, one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
pooling String, optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Integer, optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
dropout_rate fraction of the input units to drop on the last layer.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
Returns A keras.Model instance.
Raises
ValueError in case of invalid argument for weights, or invalid input shape or invalid alpha, rows when weights='imagenet'
ValueError if classifier_activation is not softmax or None when using a pretrained top layer. | tensorflow.keras.applications.mobilenetv3small |
Module: tf.keras.applications.mobilenet_v2 MobileNet v2 models for Keras. MobileNetV2 is a general architecture and can be used for multiple use cases. Depending on the use case, it can use different input layer size and different width factors. This allows different width models to reduce the number of multiply-adds and thereby reduce inference cost on mobile devices. MobileNetV2 is very similar to the original MobileNet, except that it uses inverted residual blocks with bottlenecking features. It has a drastically lower parameter count than the original MobileNet. MobileNets support any input size greater than 32 x 32, with larger image sizes offering better performance. The number of parameters and number of multiply-adds can be modified by using the alpha parameter, which increases/decreases the number of filters in each layer. By altering the image size and alpha parameter, all 22 models from the paper can be built, with ImageNet weights provided. The paper demonstrates the performance of MobileNets using alpha values of 1.0 (also called 100 % MobileNet), 0.35, 0.5, 0.75, 1.0, 1.3, and 1.4 For each of these alpha values, weights for 5 different input image sizes are provided (224, 192, 160, 128, and 96). The following table describes the performance of MobileNet on various input sizes: MACs stands for Multiply Adds Classification Checkpoint|MACs (M)|Parameters (M)|Top 1 Accuracy|Top 5 Accuracy --------------------------|------------|---------------|---------|----|--------- | [mobilenet_v2_1.4_224] | 582 | 6.06 | 75.0 | 92.5 | | [mobilenet_v2_1.3_224] | 509 | 5.34 | 74.4 | 92.1 | | [mobilenet_v2_1.0_224] | 300 | 3.47 | 71.8 | 91.0 | | [mobilenet_v2_1.0_192] | 221 | 3.47 | 70.7 | 90.1 | | [mobilenet_v2_1.0_160] | 154 | 3.47 | 68.8 | 89.0 | | [mobilenet_v2_1.0_128] | 99 | 3.47 | 65.3 | 86.9 | | [mobilenet_v2_1.0_96] | 56 | 3.47 | 60.3 | 83.2 | | [mobilenet_v2_0.75_224] | 209 | 2.61 | 69.8 | 89.6 | | [mobilenet_v2_0.75_192] | 153 | 2.61 | 68.7 | 88.9 | | [mobilenet_v2_0.75_160] | 107 | 2.61 | 66.4 | 87.3 | | [mobilenet_v2_0.75_128] | 69 | 2.61 | 63.2 | 85.3 | | [mobilenet_v2_0.75_96] | 39 | 2.61 | 58.8 | 81.6 | | [mobilenet_v2_0.5_224] | 97 | 1.95 | 65.4 | 86.4 | | [mobilenet_v2_0.5_192] | 71 | 1.95 | 63.9 | 85.4 | | [mobilenet_v2_0.5_160] | 50 | 1.95 | 61.0 | 83.2 | | [mobilenet_v2_0.5_128] | 32 | 1.95 | 57.7 | 80.8 | | [mobilenet_v2_0.5_96] | 18 | 1.95 | 51.2 | 75.8 | | [mobilenet_v2_0.35_224] | 59 | 1.66 | 60.3 | 82.9 | | [mobilenet_v2_0.35_192] | 43 | 1.66 | 58.2 | 81.2 | | [mobilenet_v2_0.35_160] | 30 | 1.66 | 55.7 | 79.1 | | [mobilenet_v2_0.35_128] | 20 | 1.66 | 50.8 | 75.0 | | [mobilenet_v2_0.35_96] | 11 | 1.66 | 45.5 | 70.4 | Reference:
MobileNetV2: Inverted Residuals and Linear Bottlenecks (CVPR 2018) Functions MobileNetV2(...): Instantiates the MobileNetV2 architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.mobilenet_v2 |
tf.keras.applications.mobilenet_v2.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.mobilenet_v2.decode_predictions
tf.keras.applications.mobilenet_v2.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.mobilenet_v2.decode_predictions |
tf.keras.applications.mobilenet_v2.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.mobilenet_v2.preprocess_input
tf.keras.applications.mobilenet_v2.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.mobilenet_v2.preprocess_input |
Module: tf.keras.applications.mobilenet_v3 MobileNet v3 models for Keras. Functions decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.mobilenet_v3 |
tf.keras.applications.mobilenet_v3.decode_predictions Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.mobilenet_v3.decode_predictions
tf.keras.applications.mobilenet_v3.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.mobilenet_v3.decode_predictions |
tf.keras.applications.mobilenet_v3.preprocess_input Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.mobilenet_v3.preprocess_input
tf.keras.applications.mobilenet_v3.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.mobilenet_v3.preprocess_input |
Module: tf.keras.applications.nasnet NASNet-A models for Keras. NASNet refers to Neural Architecture Search Network, a family of models that were designed automatically by learning the model architectures directly on the dataset of interest. Here we consider NASNet-A, the highest performance model that was found for the CIFAR-10 dataset, and then extended to ImageNet 2012 dataset, obtaining state of the art performance on CIFAR-10 and ImageNet 2012. Only the NASNet-A models, and their respective weights, which are suited for ImageNet 2012 are provided. The below table describes the performance on ImageNet 2012: Architecture | Top-1 Acc | Top-5 Acc | Multiply-Adds | Params (M)
| NASNet-A (4 @ 1056) | 74.0 % | 91.6 % | 564 M | 5.3 | | NASNet-A (6 @ 4032) | 82.7 % | 96.2 % | 23.8 B | 88.9 | Reference:
Learning Transferable Architectures for Scalable Image Recognition (CVPR 2018) Functions NASNetLarge(...): Instantiates a NASNet model in ImageNet mode. NASNetMobile(...): Instantiates a Mobile NASNet model in ImageNet mode. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.nasnet |
tf.keras.applications.nasnet.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.nasnet.decode_predictions
tf.keras.applications.nasnet.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.nasnet.decode_predictions |
tf.keras.applications.nasnet.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Compat aliases for migration
See Migration guide for more details. tf.compat.v1.keras.applications.nasnet.preprocess_input
tf.keras.applications.nasnet.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The inputs pixel values are scaled between -1 and 1, sample-wise.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.nasnet.preprocess_input |
tf.keras.applications.NASNetLarge View source on GitHub Instantiates a NASNet model in ImageNet mode. View aliases Main aliases
tf.keras.applications.nasnet.NASNetLarge Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.NASNetLarge, tf.compat.v1.keras.applications.nasnet.NASNetLarge
tf.keras.applications.NASNetLarge(
input_shape=None, include_top=True, weights='imagenet',
input_tensor=None, pooling=None, classes=1000
)
Reference:
Learning Transferable Architectures for Scalable Image Recognition (CVPR 2018) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For NASNet, call tf.keras.applications.nasnet.preprocess_input on your inputs before passing them to the model.
Arguments
input_shape Optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (331, 331, 3) for NASNetLarge. It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (224, 224, 3) would be one valid value.
include_top Whether to include the fully-connected layer at the top of the network.
weights None (random initialization) or imagenet (ImageNet weights) For loading imagenet weights, input_shape should be (331, 331, 3)
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance.
Raises
ValueError in case of invalid argument for weights, or invalid input shape.
RuntimeError If attempting to run this model with a backend that does not support separable convolutions. | tensorflow.keras.applications.nasnetlarge |
tf.keras.applications.NASNetMobile View source on GitHub Instantiates a Mobile NASNet model in ImageNet mode. View aliases Main aliases
tf.keras.applications.nasnet.NASNetMobile Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.NASNetMobile, tf.compat.v1.keras.applications.nasnet.NASNetMobile
tf.keras.applications.NASNetMobile(
input_shape=None, include_top=True, weights='imagenet',
input_tensor=None, pooling=None, classes=1000
)
Reference:
Learning Transferable Architectures for Scalable Image Recognition (CVPR 2018) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For NASNet, call tf.keras.applications.nasnet.preprocess_input on your inputs before passing them to the model.
Arguments
input_shape Optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) for NASNetMobile It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (224, 224, 3) would be one valid value.
include_top Whether to include the fully-connected layer at the top of the network.
weights None (random initialization) or imagenet (ImageNet weights) For loading imagenet weights, input_shape should be (224, 224, 3)
input_tensor Optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional layer.
avg means that global average pooling will be applied to the output of the last convolutional layer, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes Optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance.
Raises
ValueError In case of invalid argument for weights, or invalid input shape.
RuntimeError If attempting to run this model with a backend that does not support separable convolutions. | tensorflow.keras.applications.nasnetmobile |
Module: tf.keras.applications.resnet ResNet models for Keras. Reference:
Deep Residual Learning for Image Recognition (CVPR 2015) Functions ResNet101(...): Instantiates the ResNet101 architecture. ResNet152(...): Instantiates the ResNet152 architecture. ResNet50(...): Instantiates the ResNet50 architecture. decode_predictions(...): Decodes the prediction of an ImageNet model. preprocess_input(...): Preprocesses a tensor or Numpy array encoding a batch of images. | tensorflow.keras.applications.resnet |
tf.keras.applications.resnet.decode_predictions View source on GitHub Decodes the prediction of an ImageNet model. View aliases Main aliases
tf.keras.applications.resnet50.decode_predictions Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.resnet.decode_predictions, tf.compat.v1.keras.applications.resnet50.decode_predictions
tf.keras.applications.resnet.decode_predictions(
preds, top=5
)
Arguments
preds Numpy array encoding a batch of predictions.
top Integer, how many top-guesses to return. Defaults to 5.
Returns A list of lists of top class prediction tuples (class_name, class_description, score). One list of tuples per sample in batch input.
Raises
ValueError In case of invalid shape of the pred array (must be 2D). | tensorflow.keras.applications.resnet.decode_predictions |
tf.keras.applications.resnet.preprocess_input View source on GitHub Preprocesses a tensor or Numpy array encoding a batch of images. View aliases Main aliases
tf.keras.applications.resnet50.preprocess_input Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.resnet.preprocess_input, tf.compat.v1.keras.applications.resnet50.preprocess_input
tf.keras.applications.resnet.preprocess_input(
x, data_format=None
)
Usage example with applications.MobileNet: i = tf.keras.layers.Input([None, None, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNet()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
image = tf.image.decode_png(tf.io.read_file('file.png'))
result = model(image)
Arguments
x A floating point numpy.array or a tf.Tensor, 3D or 4D with 3 color channels, with values in the range [0, 255]. The preprocessed data are written over the input data if the data types are compatible. To avoid this behaviour, numpy.copy(x) can be used.
data_format Optional data format of the image tensor/array. Defaults to None, in which case the global setting tf.keras.backend.image_data_format() is used (unless you changed it, it defaults to "channels_last").
Returns Preprocessed numpy.array or a tf.Tensor with type float32. The images are converted from RGB to BGR, then each color channel is zero-centered with respect to the ImageNet dataset, without scaling.
Raises
ValueError In case of unknown data_format argument. | tensorflow.keras.applications.resnet.preprocess_input |
tf.keras.applications.ResNet101 View source on GitHub Instantiates the ResNet101 architecture. View aliases Main aliases
tf.keras.applications.resnet.ResNet101 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.ResNet101, tf.compat.v1.keras.applications.resnet.ResNet101
tf.keras.applications.ResNet101(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000, **kwargs
)
Reference:
Deep Residual Learning for Image Recognition (CVPR 2015) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For ResNet, call tf.keras.applications.resnet.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance. | tensorflow.keras.applications.resnet101 |
tf.keras.applications.ResNet101V2 View source on GitHub Instantiates the ResNet101V2 architecture. View aliases Main aliases
tf.keras.applications.resnet_v2.ResNet101V2 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.ResNet101V2, tf.compat.v1.keras.applications.resnet_v2.ResNet101V2
tf.keras.applications.ResNet101V2(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax'
)
Reference:
Identity Mappings in Deep Residual Networks (CVPR 2016) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For ResNetV2, call tf.keras.applications.resnet_v2.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
Returns A keras.Model instance. | tensorflow.keras.applications.resnet101v2 |
tf.keras.applications.ResNet152 View source on GitHub Instantiates the ResNet152 architecture. View aliases Main aliases
tf.keras.applications.resnet.ResNet152 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.ResNet152, tf.compat.v1.keras.applications.resnet.ResNet152
tf.keras.applications.ResNet152(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000, **kwargs
)
Reference:
Deep Residual Learning for Image Recognition (CVPR 2015) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For ResNet, call tf.keras.applications.resnet.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
Returns A Keras model instance. | tensorflow.keras.applications.resnet152 |
tf.keras.applications.ResNet152V2 View source on GitHub Instantiates the ResNet152V2 architecture. View aliases Main aliases
tf.keras.applications.resnet_v2.ResNet152V2 Compat aliases for migration See Migration guide for more details. tf.compat.v1.keras.applications.ResNet152V2, tf.compat.v1.keras.applications.resnet_v2.ResNet152V2
tf.keras.applications.ResNet152V2(
include_top=True, weights='imagenet', input_tensor=None,
input_shape=None, pooling=None, classes=1000,
classifier_activation='softmax'
)
Reference:
Identity Mappings in Deep Residual Networks (CVPR 2016) Optionally loads weights pre-trained on ImageNet. Note that the data format convention used by the model is the one specified in your Keras config at ~/.keras/keras.json.
Note: each Keras Application expects a specific kind of input preprocessing. For ResNetV2, call tf.keras.applications.resnet_v2.preprocess_input on your inputs before passing them to the model.
Arguments
include_top whether to include the fully-connected layer at the top of the network.
weights one of None (random initialization), 'imagenet' (pre-training on ImageNet), or the path to the weights file to be loaded.
input_tensor optional Keras tensor (i.e. output of layers.Input()) to use as image input for the model.
input_shape optional shape tuple, only to be specified if include_top is False (otherwise the input shape has to be (224, 224, 3) (with 'channels_last' data format) or (3, 224, 224) (with 'channels_first' data format). It should have exactly 3 inputs channels, and width and height should be no smaller than 32. E.g. (200, 200, 3) would be one valid value.
pooling Optional pooling mode for feature extraction when include_top is False.
None means that the output of the model will be the 4D tensor output of the last convolutional block.
avg means that global average pooling will be applied to the output of the last convolutional block, and thus the output of the model will be a 2D tensor.
max means that global max pooling will be applied.
classes optional number of classes to classify images into, only to be specified if include_top is True, and if no weights argument is specified.
classifier_activation A str or callable. The activation function to use on the "top" layer. Ignored unless include_top=True. Set classifier_activation=None to return the logits of the "top" layer.
Returns A keras.Model instance. | tensorflow.keras.applications.resnet152v2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.