Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/keras/src/utils/np_utils.py: 22%
40 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
1# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""Numpy-related utilities."""
17import numpy as np
19# isort: off
20from tensorflow.python.util.tf_export import keras_export
23@keras_export("keras.utils.to_categorical")
24def to_categorical(y, num_classes=None, dtype="float32"):
25 """Converts a class vector (integers) to binary class matrix.
27 E.g. for use with `categorical_crossentropy`.
29 Args:
30 y: Array-like with class values to be converted into a matrix
31 (integers from 0 to `num_classes - 1`).
32 num_classes: Total number of classes. If `None`, this would be inferred
33 as `max(y) + 1`.
34 dtype: The data type expected by the input. Default: `'float32'`.
36 Returns:
37 A binary matrix representation of the input as a NumPy array. The class
38 axis is placed last.
40 Example:
42 >>> a = tf.keras.utils.to_categorical([0, 1, 2, 3], num_classes=4)
43 >>> print(a)
44 [[1. 0. 0. 0.]
45 [0. 1. 0. 0.]
46 [0. 0. 1. 0.]
47 [0. 0. 0. 1.]]
49 >>> b = tf.constant([.9, .04, .03, .03,
50 ... .3, .45, .15, .13,
51 ... .04, .01, .94, .05,
52 ... .12, .21, .5, .17],
53 ... shape=[4, 4])
54 >>> loss = tf.keras.backend.categorical_crossentropy(a, b)
55 >>> print(np.around(loss, 5))
56 [0.10536 0.82807 0.1011 1.77196]
58 >>> loss = tf.keras.backend.categorical_crossentropy(a, a)
59 >>> print(np.around(loss, 5))
60 [0. 0. 0. 0.]
61 """
62 y = np.array(y, dtype="int")
63 input_shape = y.shape
65 # Shrink the last dimension if the shape is (..., 1).
66 if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
67 input_shape = tuple(input_shape[:-1])
69 y = y.reshape(-1)
70 if not num_classes:
71 num_classes = np.max(y) + 1
72 n = y.shape[0]
73 categorical = np.zeros((n, num_classes), dtype=dtype)
74 categorical[np.arange(n), y] = 1
75 output_shape = input_shape + (num_classes,)
76 categorical = np.reshape(categorical, output_shape)
77 return categorical
80@keras_export("keras.utils.to_ordinal")
81def to_ordinal(y, num_classes=None, dtype="float32"):
82 """Converts a class vector (integers) to an ordinal regression matrix.
84 This utility encodes class vector to ordinal regression/classification
85 matrix where each sample is indicated by a row and rank of that sample is
86 indicated by number of ones in that row.
88 Args:
89 y: Array-like with class values to be converted into a matrix
90 (integers from 0 to `num_classes - 1`).
91 num_classes: Total number of classes. If `None`, this would be inferred
92 as `max(y) + 1`.
93 dtype: The data type expected by the input. Default: `'float32'`.
95 Returns:
96 An ordinal regression matrix representation of the input as a NumPy
97 array. The class axis is placed last.
99 Example:
101 >>> a = tf.keras.utils.to_ordinal([0, 1, 2, 3], num_classes=4)
102 >>> print(a)
103 [[0. 0. 0.]
104 [1. 0. 0.]
105 [1. 1. 0.]
106 [1. 1. 1.]]
107 """
108 y = np.array(y, dtype="int")
109 input_shape = y.shape
111 # Shrink the last dimension if the shape is (..., 1).
112 if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
113 input_shape = tuple(input_shape[:-1])
115 y = y.reshape(-1)
116 if not num_classes:
117 num_classes = np.max(y) + 1
118 n = y.shape[0]
119 range_values = np.arange(num_classes - 1)
120 range_values = np.tile(np.expand_dims(range_values, 0), [n, 1])
121 ordinal = np.zeros((n, num_classes - 1), dtype=dtype)
122 ordinal[range_values < np.expand_dims(y, -1)] = 1
123 output_shape = input_shape + (num_classes - 1,)
124 ordinal = np.reshape(ordinal, output_shape)
125 return ordinal
128@keras_export("keras.utils.normalize")
129def normalize(x, axis=-1, order=2):
130 """Normalizes a Numpy array.
132 Args:
133 x: Numpy array to normalize.
134 axis: axis along which to normalize.
135 order: Normalization order (e.g. `order=2` for L2 norm).
137 Returns:
138 A normalized copy of the array.
139 """
140 l2 = np.atleast_1d(np.linalg.norm(x, order, axis))
141 l2[l2 == 0] = 1
142 return x / np.expand_dims(l2, axis)