• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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."""
16from __future__ import absolute_import
17from __future__ import division
18from __future__ import print_function
19
20import numpy as np
21from tensorflow.python.util.tf_export import keras_export
22
23
24@keras_export('keras.utils.to_categorical')
25def to_categorical(y, num_classes=None, dtype='float32'):
26  """Converts a class vector (integers) to binary class matrix.
27
28  E.g. for use with categorical_crossentropy.
29
30  Arguments:
31      y: class vector to be converted into a matrix
32          (integers from 0 to num_classes).
33      num_classes: total number of classes.
34      dtype: The data type expected by the input. Default: `'float32'`.
35
36  Returns:
37      A binary matrix representation of the input. The classes axis is placed
38      last.
39  """
40  y = np.array(y, dtype='int')
41  input_shape = y.shape
42  if input_shape and input_shape[-1] == 1 and len(input_shape) > 1:
43    input_shape = tuple(input_shape[:-1])
44  y = y.ravel()
45  if not num_classes:
46    num_classes = np.max(y) + 1
47  n = y.shape[0]
48  categorical = np.zeros((n, num_classes), dtype=dtype)
49  categorical[np.arange(n), y] = 1
50  output_shape = input_shape + (num_classes,)
51  categorical = np.reshape(categorical, output_shape)
52  return categorical
53
54
55@keras_export('keras.utils.normalize')
56def normalize(x, axis=-1, order=2):
57  """Normalizes a Numpy array.
58
59  Arguments:
60      x: Numpy array to normalize.
61      axis: axis along which to normalize.
62      order: Normalization order (e.g. 2 for L2 norm).
63
64  Returns:
65      A normalized copy of the array.
66  """
67  l2 = np.atleast_1d(np.linalg.norm(x, order, axis))
68  l2[l2 == 0] = 1
69  return x / np.expand_dims(l2, axis)
70