text:
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Core Keras layers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import sys
import textwrap
import types as python_types
import warnings

import numpy as np

from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.keras import activations
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import constraints
from tensorflow.python.keras import initializers
from tensorflow.python.keras import regularizers
from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.keras.engine.input_spec import InputSpec
from tensorflow.python.keras.utils import conv_utils
from tensorflow.python.keras.utils import generic_utils
from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import sparse_ops
from tensorflow.python.ops import standard_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging
from tensorflow.python.training.tracking import base as trackable
from tensorflow.python.util import nest
from tensorflow.python.util import tf_inspect
from tensorflow.python.util.tf_export import keras_export

@keras_export('keras.layers.Masking')
class Masking(Layer):
  """Masks a sequence by using a mask value to skip timesteps.

  For each timestep in the input tensor (dimension #1 in the tensor),
  if all values in the input tensor at that timestep
  are equal to `mask_value`, then the timestep will be masked (skipped)
  in all downstream layers (as long as they support masking).

  If any downstream layer does not support masking yet receives such
  an input mask, an exception will be raised.

  Example:

  Consider a Numpy data array `x` of shape `(samples, timesteps, features)`,
  to be fed to an LSTM layer. You want to mask timestep #3 and #5 because you
  lack data for these timesteps. You can:

  - Set `x[:, 3, :] = 0.` and `x[:, 5, :] = 0.`
  - Insert a `Masking` layer with `mask_value=0.` before the LSTM layer:

  ```python
  samples, timesteps, features = 32, 10, 8
  inputs = np.random.random([samples, timesteps, features]).astype(np.float32)
  inputs[:, 3, :] = 0.
  inputs[:, 5, :] = 0.

  model = tf.keras.models.Sequential()
  model.add(tf.keras.layers.Masking(mask_value=0.,
                                    input_shape=(timesteps, features)))
  model.add(tf.keras.layers.LSTM(32))

  output = model(inputs)
  # The time step 3 and 5 will be skipped from LSTM calculation.
  ```

  See [the masking and padding
  guide](https://www.tensorflow.org/guide/keras/masking_and_padding)
  for more details.
  """

  def __init__(self, mask_value=0., **kwargs):
    super(Masking, self).__init__(**kwargs)
    self.supports_masking = True
    self.mask_value = mask_value
    self._compute_output_and_mask_jointly = True

  def compute_mask(self, inputs, mask=None):
    return K.any(math_ops.not_equal(inputs, self.mask_value), axis=-1)

  def call(self, inputs):
    boolean_mask = K.any(
        math_ops.not_equal(inputs, self.mask_value), axis=-1, keepdims=True)
    outputs = inputs * math_ops.cast(boolean_mask, inputs.dtype)
    # Compute the mask and outputs simultaneously.
    outputs._keras_mask = array_ops.squeeze(boolean_mask, axis=-1)  # pylint: disable=protected-access
    return outputs

  def compute_output_shape(self, input_shape):
    return input_shape

  def get_config(self):
    config = {'mask_value': self.mask_value}
    base_config = super(Masking, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.Dropout')
class Dropout(Layer):
  """Applies Dropout to the input.

  The Dropout layer randomly sets input units to 0 with a frequency of `rate`
  at each step during training time, which helps prevent overfitting.
  Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over
  all inputs is unchanged.

  Note that the Dropout layer only applies when `training` is set to True
  such that no values are dropped during inference. When using `model.fit`,
  `training` will be appropriately set to True automatically, and in other
  contexts, you can set the kwarg explicitly to True when calling the layer.

  (This is in contrast to setting `trainable=False` for a Dropout layer.
  `trainable` does not affect the layer's behavior, as Dropout does
  not have any variables/weights that can be frozen during training.)

  >>> tf.random.set_seed(0)
  >>> layer = tf.keras.layers.Dropout(.2, input_shape=(2,))
  >>> data = np.arange(10).reshape(5, 2).astype(np.float32)
  >>> print(data)
  [[0. 1.]
   [2. 3.]
   [4. 5.]
   [6. 7.]
   [8. 9.]]
  >>> outputs = layer(data, training=True)
  >>> print(outputs)
  tf.Tensor(
  [[ 0.    1.25]
   [ 2.5   3.75]
   [ 5.    6.25]
   [ 7.5   8.75]
   [10.    0.  ]], shape=(5, 2), dtype=float32)

  Arguments:
    rate: Float between 0 and 1. Fraction of the input units to drop.
    noise_shape: 1D integer tensor representing the shape of the
      binary dropout mask that will be multiplied with the input.
      For instance, if your inputs have shape
      `(batch_size, timesteps, features)` and
      you want the dropout mask to be the same for all timesteps,
      you can use `noise_shape=(batch_size, 1, features)`.
    seed: A Python integer to use as random seed.

  Call arguments:
    inputs: Input tensor (of any rank).
    training: Python boolean indicating whether the layer should behave in
      training mode (adding dropout) or in inference mode (doing nothing).
  """

  def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
    super(Dropout, self).__init__(**kwargs)
    self.rate = rate
    self.noise_shape = noise_shape
    self.seed = seed
    self.supports_masking = True

  def _get_noise_shape(self, inputs):
    # Subclasses of `Dropout` may implement `_get_noise_shape(self, inputs)`,
    # which will override `self.noise_shape`, and allows for custom noise
    # shapes with dynamically sized inputs.
    if self.noise_shape is None:
      return None

    concrete_inputs_shape = array_ops.shape(inputs)
    noise_shape = []
    for i, value in enumerate(self.noise_shape):
      noise_shape.append(concrete_inputs_shape[i] if value is None else value)
    return ops.convert_to_tensor_v2(noise_shape)

  def call(self, inputs, training=None):
    if training is None:
      training = K.learning_phase()

    def dropped_inputs():
      return nn.dropout(
          inputs,
          noise_shape=self._get_noise_shape(inputs),
          seed=self.seed,
          rate=self.rate)

    output = tf_utils.smart_cond(training,
                                 dropped_inputs,
                                 lambda: array_ops.identity(inputs))
    return output

  def compute_output_shape(self, input_shape):
    return input_shape

  def get_config(self):
    config = {
        'rate': self.rate,
        'noise_shape': self.noise_shape,
        'seed': self.seed
    }
    base_config = super(Dropout, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.SpatialDropout1D')
class SpatialDropout1D(Dropout):
  """Spatial 1D version of Dropout.

  This version performs the same function as Dropout, however it drops
  entire 1D feature maps instead of individual elements. If adjacent frames
  within feature maps are strongly correlated (as is normally the case in
  early convolution layers) then regular dropout will not regularize the
  activations and will otherwise just result in an effective learning rate
  decrease. In this case, SpatialDropout1D will help promote independence
  between feature maps and should be used instead.

  Arguments:
    rate: Float between 0 and 1. Fraction of the input units to drop.

  Call arguments:
    inputs: A 3D tensor.
    training: Python boolean indicating whether the layer should behave in
      training mode (adding dropout) or in inference mode (doing nothing).

  Input shape:
    3D tensor with shape:
    `(samples, timesteps, channels)`

  Output shape:
    Same as input.

  References:
    - [Efficient Object Localization Using Convolutional
      Networks](https://arxiv.org/abs/1411.4280)
  """

  def __init__(self, rate, **kwargs):
    super(SpatialDropout1D, self).__init__(rate, **kwargs)
    self.input_spec = InputSpec(ndim=3)

  def _get_noise_shape(self, inputs):
    input_shape = array_ops.shape(inputs)
    noise_shape = (input_shape[0], 1, input_shape[2])
    return noise_shape

@keras_export('keras.layers.SpatialDropout2D')
class SpatialDropout2D(Dropout):
  """Spatial 2D version of Dropout.

  This version performs the same function as Dropout, however it drops
  entire 2D feature maps instead of individual elements. If adjacent pixels
  within feature maps are strongly correlated (as is normally the case in
  early convolution layers) then regular dropout will not regularize the
  activations and will otherwise just result in an effective learning rate
  decrease. In this case, SpatialDropout2D will help promote independence
  between feature maps and should be used instead.

  Arguments:
    rate: Float between 0 and 1. Fraction of the input units to drop.
    data_format: 'channels_first' or 'channels_last'.
      In 'channels_first' mode, the channels dimension
      (the depth) is at index 1,
      in 'channels_last' mode is it at index 3.
      It defaults to the `image_data_format` value found in your
      Keras config file at `~/.keras/keras.json`.
      If you never set it, then it will be "channels_last".

  Call arguments:
    inputs: A 4D tensor.
    training: Python boolean indicating whether the layer should behave in
      training mode (adding dropout) or in inference mode (doing nothing).

  Input shape:
    4D tensor with shape:
    `(samples, channels, rows, cols)` if data_format='channels_first'
    or 4D tensor with shape:
    `(samples, rows, cols, channels)` if data_format='channels_last'.

  Output shape:
    Same as input.

  References:
    - [Efficient Object Localization Using Convolutional
      Networks](https://arxiv.org/abs/1411.4280)
  """

  def __init__(self, rate, data_format=None, **kwargs):
    super(SpatialDropout2D, self).__init__(rate, **kwargs)
    if data_format is None:
      data_format = K.image_data_format()
    if data_format not in {'channels_last', 'channels_first'}:
      raise ValueError('data_format must be in '
                       '{"channels_last", "channels_first"}')
    self.data_format = data_format
    self.input_spec = InputSpec(ndim=4)

  def _get_noise_shape(self, inputs):
    input_shape = array_ops.shape(inputs)
    if self.data_format == 'channels_first':
      return (input_shape[0], input_shape[1], 1, 1)
    elif self.data_format == 'channels_last':
      return (input_shape[0], 1, 1, input_shape[3])

@keras_export('keras.layers.SpatialDropout3D')
class SpatialDropout3D(Dropout):
  """Spatial 3D version of Dropout.

  This version performs the same function as Dropout, however it drops
  entire 3D feature maps instead of individual elements. If adjacent voxels
  within feature maps are strongly correlated (as is normally the case in
  early convolution layers) then regular dropout will not regularize the
  activations and will otherwise just result in an effective learning rate
  decrease. In this case, SpatialDropout3D will help promote independence
  between feature maps and should be used instead.

  Arguments:
    rate: Float between 0 and 1. Fraction of the input units to drop.
    data_format: 'channels_first' or 'channels_last'.
        In 'channels_first' mode, the channels dimension (the depth)
        is at index 1, in 'channels_last' mode is it at index 4.
        It defaults to the `image_data_format` value found in your
        Keras config file at `~/.keras/keras.json`.
        If you never set it, then it will be "channels_last".

  Call arguments:
    inputs: A 5D tensor.
    training: Python boolean indicating whether the layer should behave in
      training mode (adding dropout) or in inference mode (doing nothing).

  Input shape:
    5D tensor with shape:
    `(samples, channels, dim1, dim2, dim3)` if data_format='channels_first'
    or 5D tensor with shape:
    `(samples, dim1, dim2, dim3, channels)` if data_format='channels_last'.

  Output shape:
    Same as input.

  References:
    - [Efficient Object Localization Using Convolutional
      Networks](https://arxiv.org/abs/1411.4280)
  """

  def __init__(self, rate, data_format=None, **kwargs):
    super(SpatialDropout3D, self).__init__(rate, **kwargs)
    if data_format is None:
      data_format = K.image_data_format()
    if data_format not in {'channels_last', 'channels_first'}:
      raise ValueError('data_format must be in '
                       '{"channels_last", "channels_first"}')
    self.data_format = data_format
    self.input_spec = InputSpec(ndim=5)

  def _get_noise_shape(self, inputs):
    input_shape = array_ops.shape(inputs)
    if self.data_format == 'channels_first':
      return (input_shape[0], input_shape[1], 1, 1, 1)
    elif self.data_format == 'channels_last':
      return (input_shape[0], 1, 1, 1, input_shape[4])

@keras_export('keras.layers.Activation')
class Activation(Layer):
  """Applies an activation function to an output.

  Arguments:
    activation: Activation function, such as `tf.nn.relu`, or string name of
      built-in activation function, such as "relu".

  Usage:

  >>> layer = tf.keras.layers.Activation('relu')
  >>> output = layer([-3.0, -1.0, 0.0, 2.0])
  >>> list(output.numpy())
  [0.0, 0.0, 0.0, 2.0]
  >>> layer = tf.keras.layers.Activation(tf.nn.relu)
  >>> output = layer([-3.0, -1.0, 0.0, 2.0])
  >>> list(output.numpy())
  [0.0, 0.0, 0.0, 2.0]

  Input shape:
    Arbitrary. Use the keyword argument `input_shape`
    (tuple of integers, does not include the batch axis)
    when using this layer as the first layer in a model.

  Output shape:
    Same shape as input.
  """

  def __init__(self, activation, **kwargs):
    super(Activation, self).__init__(**kwargs)
    self.supports_masking = True
    self.activation = activations.get(activation)

  def call(self, inputs):
    return self.activation(inputs)

  def compute_output_shape(self, input_shape):
    return input_shape

  def get_config(self):
    config = {'activation': activations.serialize(self.activation)}
    base_config = super(Activation, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.Reshape')
class Reshape(Layer):
  """Layer that reshapes inputs into the given shape.

  Input shape:
    Arbitrary, although all dimensions in the input shape must be known/fixed.
    Use the keyword argument `input_shape` (tuple of integers, does not include
    the samples/batch size axis) when using this layer as the first layer
    in a model.

  Output shape:
    `(batch_size,) + target_shape`

  Example:

  >>> # as first layer in a Sequential model
  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.layers.Reshape((3, 4), input_shape=(12,)))
  >>> # model.output_shape == (None, 3, 4), `None` is the batch size.
  >>> model.output_shape
  (None, 3, 4)

  >>> # as intermediate layer in a Sequential model
  >>> model.add(tf.keras.layers.Reshape((6, 2)))
  >>> model.output_shape
  (None, 6, 2)

  >>> # also supports shape inference using `-1` as dimension
  >>> model.add(tf.keras.layers.Reshape((-1, 2, 2)))
  >>> model.output_shape
  (None, None, 2, 2)
  """

  def __init__(self, target_shape, **kwargs):
    """Creates a `tf.keras.layers.Reshape`  layer instance.

    Args:
      target_shape: Target shape. Tuple of integers, does not include the
        samples dimension (batch size).
      **kwargs: Any additional layer keyword arguments.
    """
    super(Reshape, self).__init__(**kwargs)
    self.target_shape = tuple(target_shape)

  def _fix_unknown_dimension(self, input_shape, output_shape):
    """Find and replace a missing dimension in an output shape.

    This is a near direct port of the internal Numpy function
    `_fix_unknown_dimension` in `numpy/core/src/multiarray/shape.c`

    Arguments:
      input_shape: Shape of array being reshaped
      output_shape: Desired shape of the array with at most
        a single -1 which indicates a dimension that should be
        derived from the input shape.

    Returns:
      The new output shape with a -1 replaced with its computed value.

    Raises:
      ValueError: If the total array size of the output_shape is
      different than the input_shape, or more than one unknown dimension
      is specified.
    """
    output_shape = list(output_shape)
    msg = 'total size of new array must be unchanged'

    known, unknown = 1, None
    for index, dim in enumerate(output_shape):
      if dim < 0:
        if unknown is None:
          unknown = index
        else:
          raise ValueError('Can only specify one unknown dimension.')
      else:
        known *= dim

    original = np.prod(input_shape, dtype=int)
    if unknown is not None:
      if known == 0 or original % known != 0:
        raise ValueError(msg)
      output_shape[unknown] = original // known
    elif original != known:
      raise ValueError(msg)
    return output_shape

  def compute_output_shape(self, input_shape):
    input_shape = tensor_shape.TensorShape(input_shape).as_list()
    if None in input_shape[1:]:
      output_shape = [input_shape[0]]
      # input shape (partially) unknown? replace -1's with None's
      output_shape += tuple(s if s != -1 else None for s in self.target_shape)
    else:
      output_shape = [input_shape[0]]
      output_shape += self._fix_unknown_dimension(input_shape[1:],
                                                  self.target_shape)
    return tensor_shape.TensorShape(output_shape)

  def call(self, inputs):
    return array_ops.reshape(inputs,
                             (array_ops.shape(inputs)[0],) + self.target_shape)

  def get_config(self):
    config = {'target_shape': self.target_shape}
    base_config = super(Reshape, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.Permute')
class Permute(Layer):
  """Permutes the dimensions of the input according to a given pattern.

  Useful for e.g. connecting RNNs and convnets together.

  Example:

  ```python
  model = Sequential()
  model.add(Permute((2, 1), input_shape=(10, 64)))
  # now: model.output_shape == (None, 64, 10)
  # note: `None` is the batch dimension
  ```

  Arguments:
    dims: Tuple of integers. Permutation pattern, does not include the
      samples dimension. Indexing starts at 1.
      For instance, `(2, 1)` permutes the first and second dimensions
      of the input.

  Input shape:
    Arbitrary. Use the keyword argument `input_shape`
    (tuple of integers, does not include the samples axis)
    when using this layer as the first layer in a model.

  Output shape:
    Same as the input shape, but with the dimensions re-ordered according
    to the specified pattern.
  """

  def __init__(self, dims, **kwargs):
    super(Permute, self).__init__(**kwargs)
    self.dims = tuple(dims)
    if sorted(dims) != list(range(1, len(dims) + 1)):
      raise ValueError(
          'Invalid permutation `dims` for Permute Layer: %s. '
          'The set of indices in `dims` must be consecutive and start from 1.' %
          (dims,))
    self.input_spec = InputSpec(ndim=len(self.dims) + 1)

  def compute_output_shape(self, input_shape):
    input_shape = tensor_shape.TensorShape(input_shape).as_list()
    output_shape = copy.copy(input_shape)
    for i, dim in enumerate(self.dims):
      target_dim = input_shape[dim]
      output_shape[i + 1] = target_dim
    return tensor_shape.TensorShape(output_shape)

  def call(self, inputs):
    return array_ops.transpose(inputs, perm=(0,) + self.dims)

  def get_config(self):
    config = {'dims': self.dims}
    base_config = super(Permute, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.Flatten')
class Flatten(Layer):
  """Flattens the input. Does not affect the batch size.

  Note: If inputs are shaped `(batch,)` without a feature axis, then
  flattening adds an extra channel dimension and output shape is `(batch, 1)`.

  Arguments:
    data_format: A string,
      one of `channels_last` (default) or `channels_first`.
      The ordering of the dimensions in the inputs.
      `channels_last` corresponds to inputs with shape
      `(batch, ..., channels)` while `channels_first` corresponds to
      inputs with shape `(batch, channels, ...)`.
      It defaults to the `image_data_format` value found in your
      Keras config file at `~/.keras/keras.json`.
      If you never set it, then it will be "channels_last".

  Example:

  >>> model = tf.keras.Sequential()
  >>> model.add(tf.keras.layers.Conv2D(64, 3, 3, input_shape=(3, 32, 32)))
  >>> model.output_shape
  (None, 1, 10, 64)

  >>> model.add(Flatten())
  >>> model.output_shape
  (None, 640)

  """

  def __init__(self, data_format=None, **kwargs):
    super(Flatten, self).__init__(**kwargs)
    self.data_format = conv_utils.normalize_data_format(data_format)
    self.input_spec = InputSpec(min_ndim=1)

  def call(self, inputs):
    if (self.data_format == 'channels_first'
        and K.ndim(inputs) is not None and K.ndim(inputs) > 1):
      permutation = [0]
      permutation.extend(range(2, K.ndim(inputs)))
      permutation.append(1)
      inputs = array_ops.transpose(inputs, perm=permutation)

    input_shape = inputs.shape
    if input_shape[1:].is_fully_defined():
      flattened_dim = tensor_shape.dimension_value(
          np.prod(input_shape[1:], dtype=int))
      # Temporary fix for integer overflow issue.
      if flattened_dim > np.iinfo(np.int32).max:
        shape_dtype = dtypes.int64
      else:
        shape_dtype = dtypes.int32
      outputs = array_ops.reshape(
          inputs, constant_op.constant((-1, flattened_dim), dtype=shape_dtype))
    else:
      batch_size = tensor_shape.dimension_value(inputs.shape[0])
      if batch_size:
        # Temporary fix for integer overflow issue.
        if batch_size > np.iinfo(np.int32).max:
          shape_dtype = dtypes.int64
        else:
          shape_dtype = dtypes.int32
        outputs = array_ops.reshape(
            inputs, constant_op.constant((batch_size, -1), dtype=shape_dtype))
      else:
        outputs = array_ops.reshape(inputs, (array_ops.shape(inputs)[0], -1))
    if not context.executing_eagerly():
      outputs.set_shape(self.compute_output_shape(inputs.shape))
    return outputs

  def compute_output_shape(self, input_shape):
    input_shape = tensor_shape.as_shape(input_shape).as_list()
    if not input_shape:
      output_shape = tensor_shape.TensorShape([1])
    else:
      output_shape = [input_shape[0]]
    if np.all(input_shape[1:]):
      output_shape += [np.prod(input_shape[1:], dtype=int)]
    else:
      output_shape += [None]
    return tensor_shape.TensorShape(output_shape)

  def get_config(self):
    config = {'data_format': self.data_format}
    base_config = super(Flatten, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.RepeatVector')
class RepeatVector(Layer):
  """Repeats the input n times.

  Example:

  ```python
  model = Sequential()
  model.add(Dense(32, input_dim=32))
  # now: model.output_shape == (None, 32)
  # note: `None` is the batch dimension

  model.add(RepeatVector(3))
  # now: model.output_shape == (None, 3, 32)
  ```

  Arguments:
    n: Integer, repetition factor.

  Input shape:
    2D tensor of shape `(num_samples, features)`.

  Output shape:
    3D tensor of shape `(num_samples, n, features)`.
  """

  def __init__(self, n, **kwargs):
    super(RepeatVector, self).__init__(**kwargs)
    self.n = n
    self.input_spec = InputSpec(ndim=2)

  def compute_output_shape(self, input_shape):
    input_shape = tensor_shape.TensorShape(input_shape).as_list()
    return tensor_shape.TensorShape([input_shape[0], self.n, input_shape[1]])

  def call(self, inputs):
    return K.repeat(inputs, self.n)

  def get_config(self):
    config = {'n': self.n}
    base_config = super(RepeatVector, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.Lambda')
class Lambda(Layer):
  """Wraps arbitrary expressions as a `Layer` object.

  The `Lambda` layer exists so that arbitrary TensorFlow functions
  can be used when constructing `Sequential` and Functional API
  models. `Lambda` layers are best suited for simple operations or
  quick experimentation. For more advanced usecases, follow
  [this guide](https://www.tensorflow.org/guide/keras/custom_layers_and_models)
  for subclassing `tf.keras.layers.Layer`.

  The main reason to subclass `tf.keras.layers.Layer` instead of using a
  `Lambda` layer is saving and inspecting a Model. `Lambda` layers
  are saved by serializing the Python bytecode, whereas subclassed
  Layers can be saved via overriding their `get_config` method. Overriding
  `get_config` improves the portability of Models. Models that rely on
  subclassed Layers are also often easier to visualize and reason about.

  Examples:

  ```python
  # add a x -> x^2 layer
  model.add(Lambda(lambda x: x ** 2))
  ```
  ```python
  # add a layer that returns the concatenation
  # of the positive part of the input and
  # the opposite of the negative part

  def antirectifier(x):
      x -= K.mean(x, axis=1, keepdims=True)
      x = K.l2_normalize(x, axis=1)
      pos = K.relu(x)
      neg = K.relu(-x)
      return K.concatenate([pos, neg], axis=1)

  model.add(Lambda(antirectifier))
  ```

  Variables:
    While it is possible to use Variables with Lambda layers, this practice is
    discouraged as it can easily lead to bugs. For instance, consider the
    following layer:

    ```python
      scale = tf.Variable(1.)
      scale_layer = tf.keras.layers.Lambda(lambda x: x * scale)
    ```

    Because scale_layer does not directly track the `scale` variable, it will
    not appear in `scale_layer.trainable_weights` and will therefore not be
    trained if `scale_layer` is used in a Model.

    A better pattern is to write a subclassed Layer:

    ```python
      class ScaleLayer(tf.keras.layers.Layer):
        def __init__(self):
          super(ScaleLayer, self).__init__()
          self.scale = tf.Variable(1.)

        def call(self, inputs):
          return inputs * self.scale
    ```

    In general, Lambda layers can be convenient for simple stateless
    computation, but anything more complex should use a subclass Layer instead.

  Arguments:
    function: The function to be evaluated. Takes input tensor as first
      argument.
    output_shape: Expected output shape from function. This argument can be
      inferred if not explicitly provided. Can be a tuple or function. If a
      tuple, it only specifies the first dimension onward;
      sample dimension is assumed either the same as the input: `output_shape =
        (input_shape[0], ) + output_shape` or, the input is `None` and
      the sample dimension is also `None`: `output_shape = (None, ) +
        output_shape` If a function, it specifies the entire shape as a function
        of the
      input shape: `output_shape = f(input_shape)`
    mask: Either None (indicating no masking) or a callable with the same
      signature as the `compute_mask` layer method, or a tensor that will be
      returned as output mask regardless what the input is.
    arguments: Optional dictionary of keyword arguments to be passed to the
      function.
  Input shape: Arbitrary. Use the keyword argument input_shape (tuple of
    integers, does not include the samples axis) when using this layer as the
    first layer in a model.
  Output shape: Specified by `output_shape` argument
  """

  @trackable.no_automatic_dependency_tracking
  def __init__(self, function, output_shape=None, mask=None, arguments=None,
               **kwargs):
    super(Lambda, self).__init__(**kwargs)

    self.arguments = arguments or {}
    self.function = function

    if mask is not None:
      self.supports_masking = True
    self.mask = mask
    self._supports_ragged_inputs = True
    self._output_shape = output_shape

    # Warning on every invocation will be quite irksome in Eager mode.
    self._already_warned = False

    function_args = tf_inspect.getfullargspec(function).args
    self._fn_expects_training_arg = 'training' in function_args
    self._fn_expects_mask_arg = 'mask' in function_args

  @tf_utils.shape_type_conversion
  def compute_output_shape(self, input_shape):
    if self._output_shape is None:
      # Make use of existing autocomputation but provide Lambda-specific
      # error message. This is always safe to run even when the outer context
      # is Graph mode because Lambda layers don't have side effects such as
      # `add_loss`.
      with context.eager_mode():
        try:
          return super(Lambda, self).compute_output_shape(input_shape)
        except NotImplementedError:
          raise NotImplementedError(
              'We could not automatically infer the shape of the Lambda\'s '
              'output. Please specify `output_shape` for this Lambda.')

    if callable(self._output_shape):
      output_shapes = self._output_shape(input_shape)
      return tf_utils.convert_shapes(output_shapes, to_tuples=False)

    # Output shapes are passed directly and don't include batch dimension.
    input_tensor_shape = tf_utils.convert_shapes(input_shape, to_tuples=False)
    batch_size = nest.flatten(input_tensor_shape)[0][0] if input_shape else None

    def _add_batch(shape):
      return tensor_shape.TensorShape([batch_size] + shape.as_list())

    output_shapes = tf_utils.convert_shapes(self._output_shape, to_tuples=False)
    return nest.map_structure(_add_batch, output_shapes)

  def call(self, inputs, mask=None, training=None):
    # We must copy for thread safety, but it only needs to be a shallow copy.
    kwargs = {k: v for k, v in self.arguments.items()}
    if self._fn_expects_mask_arg:
      kwargs['mask'] = mask
    if self._fn_expects_training_arg:
      kwargs['training'] = training

    created_variables = []
    def _variable_creator(next_creator, **kwargs):
      var = next_creator(**kwargs)
      created_variables.append(var)
      return var

    with backprop.GradientTape(watch_accessed_variables=True) as tape,\
        variable_scope.variable_creator_scope(_variable_creator):
      result = self.function(inputs, **kwargs)
    self._check_variables(created_variables, tape.watched_variables())
    return result

  def _check_variables(self, created_variables, accessed_variables):
    if not created_variables and not accessed_variables:
      # In the common case that a Lambda layer does not touch a Variable, we
      # don't want to incur the runtime cost of assembling any state used for
      # checking only to immediately discard it.
      return

    tracked_weights = set(v.ref() for v in self.weights)
    untracked_new_vars = [
        v for v in created_variables if v.ref() not in tracked_weights
    ]
    if untracked_new_vars:
      variable_str = '\n'.join('  {}'.format(i) for i in untracked_new_vars)
      error_str = textwrap.dedent(
          '''
          The following Variables were created within a Lambda layer ({name})
          but are not tracked by said layer:
          {variable_str}
          The layer cannot safely ensure proper Variable reuse across multiple
          calls, and consquently this behavior is disallowed for safety. Lambda
          layers are not well suited to stateful computation; instead, writing a
          subclassed Layer is the recommend way to define layers with
          Variables.'''
      ).format(name=self.name, variable_str=variable_str)
      raise ValueError(error_str)

    untracked_used_vars = [
        v for v in accessed_variables if v.ref() not in tracked_weights
    ]
    if untracked_used_vars and not self._already_warned:
      variable_str = '\n'.join('  {}'.format(i) for i in untracked_used_vars)
      self._warn(textwrap.dedent(
          '''
          The following Variables were used a Lambda layer's call ({name}), but
          are not present in its tracked objects:
          {variable_str}
          It is possible that this is intended behavior, but it is more likely
          an omission. This is a strong indication that this layer should be
          formulated as a subclassed Layer rather than a Lambda layer.'''
      ).format(name=self.name, variable_str=variable_str))
      self._already_warned = True

  def _warn(self, msg):
    # This method will be overridden in a unit test to raise an error, because
    # self.assertWarns is not universally implemented.
    return tf_logging.warn(msg)

  def compute_mask(self, inputs, mask=None):
    if callable(self.mask):
      return self.mask(inputs, mask)
    return self.mask

  def get_config(self):
    function_config = self._serialize_function_to_config(self.function)
    output_shape_config = self._serialize_function_to_config(self._output_shape,
                                                             allow_raw=True)
    config = {
        'function': function_config[0],
        'function_type': function_config[1],
        'module': function_config[2],
        'output_shape': output_shape_config[0],
        'output_shape_type': output_shape_config[1],
        'output_shape_module': output_shape_config[2],
    }
    if self.mask is not None:
      mask_config = self._serialize_function_to_config(self.mask)
      config.update({
          'mask': mask_config[0],
          'mask_type': mask_config[1],
          'mask_module': mask_config[2]
      })
    config['arguments'] = self.arguments

    base_config = super(Lambda, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

  def _serialize_function_to_config(self, inputs, allow_raw=False):
    if isinstance(inputs, python_types.LambdaType):
      output = generic_utils.func_dump(inputs)
      output_type = 'lambda'
      module = inputs.__module__
    elif callable(inputs):
      output = inputs.__name__
      output_type = 'function'
      module = inputs.__module__
    elif allow_raw:
      output = inputs
      output_type = 'raw'
      module = None
    else:
      raise ValueError(
          'Invalid input for serialization, type: %s ' % type(inputs))

    return output, output_type, module

  @classmethod
  def from_config(cls, config, custom_objects=None):
    config = config.copy()
    function = cls._parse_function_from_config(
        config, custom_objects, 'function', 'module', 'function_type')

    output_shape = cls._parse_function_from_config(
        config, custom_objects, 'output_shape', 'output_shape_module',
        'output_shape_type')
    if 'mask' in config:
      mask = cls._parse_function_from_config(
          config, custom_objects, 'mask', 'mask_module', 'mask_type')
    else:
      mask = None

    config['function'] = function
    config['output_shape'] = output_shape
    config['mask'] = mask

    # If arguments were numpy array, they have been saved as
    # list. We need to recover the ndarray
    if 'arguments' in config:
      for key in config['arguments']:
        if isinstance(config['arguments'][key], dict):
          arg_dict = config['arguments'][key]
          if 'type' in arg_dict and arg_dict['type'] == 'ndarray':
            # Overwrite the argument with its numpy translation
            config['arguments'][key] = np.array(arg_dict['value'])

    return cls(**config)

  @classmethod
  def _parse_function_from_config(
      cls, config, custom_objects, func_attr_name, module_attr_name,
      func_type_attr_name):
    globs = globals()
    module = config.pop(module_attr_name, None)
    if module in sys.modules:
      globs.update(sys.modules[module].__dict__)
    elif module is not None:
      # Note: we don't know the name of the function if it's a lambda.
      warnings.warn('{} is not loaded, but a Lambda layer uses it. '
                    'It may cause errors.'.format(module)
                    , UserWarning)
    if custom_objects:
      globs.update(custom_objects)
    function_type = config.pop(func_type_attr_name)
    if function_type == 'function':
      # Simple lookup in custom objects
      function = generic_utils.deserialize_keras_object(
          config[func_attr_name],
          custom_objects=custom_objects,
          printable_module_name='function in Lambda layer')
    elif function_type == 'lambda':
      # Unsafe deserialization from bytecode
      function = generic_utils.func_load(
          config[func_attr_name], globs=globs)
    elif function_type == 'raw':
      function = config[func_attr_name]
    else:
      raise TypeError('Unknown function type:', function_type)
    return function

@keras_export('keras.layers.Dense')
class Dense(Layer):
  """Just your regular densely-connected NN layer.

  `Dense` implements the operation:
  `output = activation(dot(input, kernel) + bias)`
  where `activation` is the element-wise activation function
  passed as the `activation` argument, `kernel` is a weights matrix
  created by the layer, and `bias` is a bias vector created by the layer
  (only applicable if `use_bias` is `True`).

  Note: If the input to the layer has a rank greater than 2, then `Dense`
  computes the dot product between the `inputs` and the `kernel` along the
  last axis of the `inputs` and axis 1 of the `kernel` (using `tf.tensordot`).
  For example, if input has dimensions `(batch_size, d0, d1)`,
  then we create a `kernel` with shape `(d1, units)`, and the `kernel` operates
  along axis 2 of the `input`, on every sub-tensor of shape `(1, 1, d1)`
  (there are `batch_size * d0` such sub-tensors).
  The output in this case will have shape `(batch_size, d0, units)`.

  Besides, layer attributes cannot be modified after the layer has been called
  once (except the `trainable` attribute).

  Example:

  ```python
  # as first layer in a sequential model:
  model = Sequential()
  model.add(Dense(32, input_shape=(16,)))
  # now the model will take as input arrays of shape (*, 16)
  # and output arrays of shape (*, 32)

  # after the first layer, you don't need to specify
  # the size of the input anymore:
  model.add(Dense(32))
  ```

  Arguments:
    units: Positive integer, dimensionality of the output space.
    activation: Activation function to use.
      If you don't specify anything, no activation is applied
      (ie. "linear" activation: `a(x) = x`).
    use_bias: Boolean, whether the layer uses a bias vector.
    kernel_initializer: Initializer for the `kernel` weights matrix.
    bias_initializer: Initializer for the bias vector.
    kernel_regularizer: Regularizer function applied to
      the `kernel` weights matrix.
    bias_regularizer: Regularizer function applied to the bias vector.
    activity_regularizer: Regularizer function applied to
      the output of the layer (its "activation")..
    kernel_constraint: Constraint function applied to
      the `kernel` weights matrix.
    bias_constraint: Constraint function applied to the bias vector.

  Input shape:
    N-D tensor with shape: `(batch_size, ..., input_dim)`.
    The most common situation would be
    a 2D input with shape `(batch_size, input_dim)`.

  Output shape:
    N-D tensor with shape: `(batch_size, ..., units)`.
    For instance, for a 2D input with shape `(batch_size, input_dim)`,
    the output would have shape `(batch_size, units)`.
  """

  def __init__(self,
               units,
               activation=None,
               use_bias=True,
               kernel_initializer='glorot_uniform',
               bias_initializer='zeros',
               kernel_regularizer=None,
               bias_regularizer=None,
               activity_regularizer=None,
               kernel_constraint=None,
               bias_constraint=None,
               **kwargs):
    if 'input_shape' not in kwargs and 'input_dim' in kwargs:
      kwargs['input_shape'] = (kwargs.pop('input_dim'),)

    super(Dense, self).__init__(
        activity_regularizer=regularizers.get(activity_regularizer), **kwargs)

    self.units = int(units) if not isinstance(units, int) else units
    self.activation = activations.get(activation)
    self.use_bias = use_bias
    self.kernel_initializer = initializers.get(kernel_initializer)
    self.bias_initializer = initializers.get(bias_initializer)
    self.kernel_regularizer = regularizers.get(kernel_regularizer)
    self.bias_regularizer = regularizers.get(bias_regularizer)
    self.kernel_constraint = constraints.get(kernel_constraint)
    self.bias_constraint = constraints.get(bias_constraint)

    self.supports_masking = True
    self.input_spec = InputSpec(min_ndim=2)

  def build(self, input_shape):
    dtype = dtypes.as_dtype(self.dtype or K.floatx())
    if not (dtype.is_floating or dtype.is_complex):
      raise TypeError('Unable to build `Dense` layer with non-floating point '
                      'dtype %s' % (dtype,))
    input_shape = tensor_shape.TensorShape(input_shape)
    if tensor_shape.dimension_value(input_shape[-1]) is None:
      raise ValueError('The last dimension of the inputs to `Dense` '
                       'should be defined. Found `None`.')
    last_dim = tensor_shape.dimension_value(input_shape[-1])
    self.input_spec = InputSpec(min_ndim=2, axes={-1: last_dim})
    self.kernel = self.add_weight(
        'kernel',
        shape=[last_dim, self.units],
        initializer=self.kernel_initializer,
        regularizer=self.kernel_regularizer,
        constraint=self.kernel_constraint,
        dtype=self.dtype,
        trainable=True)
    if self.use_bias:
      self.bias = self.add_weight(
          'bias',
          shape=[self.units,],
          initializer=self.bias_initializer,
          regularizer=self.bias_regularizer,
          constraint=self.bias_constraint,
          dtype=self.dtype,
          trainable=True)
    else:
      self.bias = None
    self.built = True

  def call(self, inputs):
    rank = inputs.shape.rank
    if rank is not None and rank > 2:
      # Broadcasting is required for the inputs.
      outputs = standard_ops.tensordot(inputs, self.kernel, [[rank - 1], [0]])
      # Reshape the output back to the original ndim of the input.
      if not context.executing_eagerly():
        shape = inputs.shape.as_list()
        output_shape = shape[:-1] + [self.units]
        outputs.set_shape(output_shape)
    else:
      inputs = math_ops.cast(inputs, self._compute_dtype)
      if K.is_sparse(inputs):
        outputs = sparse_ops.sparse_tensor_dense_matmul(inputs, self.kernel)
      else:
        outputs = gen_math_ops.mat_mul(inputs, self.kernel)
    if self.use_bias:
      outputs = nn.bias_add(outputs, self.bias)
    if self.activation is not None:
      return self.activation(outputs)  # pylint: disable=not-callable
    return outputs

  def compute_output_shape(self, input_shape):
    input_shape = tensor_shape.TensorShape(input_shape)
    input_shape = input_shape.with_rank_at_least(2)
    if tensor_shape.dimension_value(input_shape[-1]) is None:
      raise ValueError(
          'The innermost dimension of input_shape must be defined, but saw: %s'
          % input_shape)
    return input_shape[:-1].concatenate(self.units)

  def get_config(self):
    config = {
        'units': self.units,
        'activation': activations.serialize(self.activation),
        'use_bias': self.use_bias,
        'kernel_initializer': initializers.serialize(self.kernel_initializer),
        'bias_initializer': initializers.serialize(self.bias_initializer),
        'kernel_regularizer': regularizers.serialize(self.kernel_regularizer),
        'bias_regularizer': regularizers.serialize(self.bias_regularizer),
        'activity_regularizer':
            regularizers.serialize(self.activity_regularizer),
        'kernel_constraint': constraints.serialize(self.kernel_constraint),
        'bias_constraint': constraints.serialize(self.bias_constraint)
    }
    base_config = super(Dense, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

@keras_export('keras.layers.ActivityRegularization')
class ActivityRegularization(Layer):
  """Layer that applies an update to the cost function based input activity.

  Arguments:
    l1: L1 regularization factor (positive float).
    l2: L2 regularization factor (positive float).

  Input shape:
    Arbitrary. Use the keyword argument `input_shape`
    (tuple of integers, does not include the samples axis)
    when using this layer as the first layer in a model.

  Output shape:
    Same shape as input.
  """

  def __init__(self, l1=0., l2=0., **kwargs):
    super(ActivityRegularization, self).__init__(
        activity_regularizer=regularizers.L1L2(l1=l1, l2=l2), **kwargs)
    self.supports_masking = True
    self.l1 = l1
    self.l2 = l2

  def compute_output_shape(self, input_shape):
    return input_shape

  def get_config(self):
    config = {'l1': self.l1, 'l2': self.l2}
    base_config = super(ActivityRegularization, self).get_config()
    return dict(list(base_config.items()) + list(config.items()))

max_stars_repo_name: NeerajBhadani/tensorflow

max_issues_repo_name: NeerajBhadani/tensorflow

max_forks_repo_name: NeerajBhadani/tensorflow


text:
import numpy as np
from sklearn.metrics import mean_squared_error
# Function to early stop with root mean squared percentage error
def rmspe(y_true, y_pred):
    return np.sqrt(np.mean(np.square((y_true - y_pred) / y_true)))

def feval_rmspe(y_pred, lgb_train):
    y_true = lgb_train.get_label()
    return 'RMSPE', rmspe(y_true, y_pred), False

def rmse(y_true, y_pred):
    return mean_squared_error(y_true, y_pred,squared=True)

ext: py

reason: import numpy


text:
import cv2
import numpy as np
import torch
import torchvision.transforms as transforms

def composed_transforms():
    # assert len(img.shape) == 3
    compose = transforms.Compose([
        transforms.Grayscale(3),
        Norm(),
        CLAHE(),
        AdjustGamma(),
        BiValue(),
        ToTensor()
    ])
    return compose

class Norm(object):
    def __init__(self):
        pass

    def __call__(self, img):
        img = np.array(img)
        assert (len(img.shape) == 3)
        assert(img.shape[2] == 3)
        img_norm = np.empty(img.shape)
        img_std = np.std(img)
        img_mean = np.mean(img)
        img_norm = (img - img_mean) / img_std
        img_norm = ((img_norm - np.min(img_norm)) /
                    np.max(img_norm) - np.min(img_norm)) * 255

        return img_norm

class CLAHE(object):
    def __init__(self, clipLimit=2.0, tileGridSize=(8, 8)):
        self.clipLimit = clipLimit
        self.tileGridSize = tileGridSize

    def __call__(self, img):
        img = np.array(img)
        img = img[:, :, 0]
        img = np.reshape(img, (img.shape[0], img.shape[1], 1))
        assert (len(img.shape) == 3)  # 3D arrays
        assert (img.shape[2] == 1)  # check the channel is 1
        # create a CLAHE object (Arguments are optional).
        clahe = cv2.createCLAHE(self.clipLimit, self.tileGridSize)
        return clahe.apply(np.array(img, dtype=np.uint8))

class AdjustGamma(object):
    def __init__(self, gamma=1.0):
        self.gamma = gamma

    def __call__(self, img):
        img = np.reshape(img, (img.shape[0], img.shape[1], 1))
        assert (len(img.shape) == 3)  # 4D arrays
        assert (img.shape[2] == 1)  # check the channel is 1
        # build a lookup table mapping the pixel values [0, 255] to
        # their adjusted gamma values
        invGamma = 1.0 / self.gamma
        table = np.array([((i / 255.0) ** invGamma) *
                          255 for i in np.arange(0, 256)]).astype("uint8")
        # apply gamma correction using the lookup table
        new_img = cv2.LUT(img, table)
        return new_img

class BiValue(object):
    def __call__(self, img):
        return np.array(img) / 25
#         return 1*(np.array(img) < 128)

class ToTensor(object):
    def __call__(self, img):
        #         img = img.transpose((2, 0, 1))
        return torch.from_numpy(img)

class RandomExtract(object):
    def __init__(self, patch_h, patch_w, N_patches, inside=True):
        self.patch_h = patch_h
        self.patch_w = patch_w
        self.N_patches = N_patches
        self.inside = inside

    def __call__(self, full_imgs, full_masks):
        if (self.N_patches % full_imgs.shape[0] != 0):
            print("N_patches: plase enter a multiple of 20")
            exit()
        assert (len(full_imgs.shape) == 4 and len(
            full_masks.shape) == 4)  # 4D arrays
        # check the channel is 1 or 3
        assert (full_imgs.shape[1] == 1 or full_imgs.shape[1] == 3)
        assert (full_masks.shape[1] == 1)  # masks only black and white
        assert (full_imgs.shape[2] == full_masks.shape[2]
                and full_imgs.shape[3] == full_masks.shape[3])
        patches = np.empty(
            (self.N_patches, full_imgs.shape[1], self.patch_h, self.patch_w))
        patches_masks = np.empty(
            (self.N_patches, full_masks.shape[1], self.patch_h, self.patch_w))
        img_h = full_imgs.shape[2]  # height of the full image
        img_w = full_imgs.shape[3]  # width of the full image
        # (0,0) in the center of the image
        # N_patches equally divided in the full images
        patch_per_img = int(self.N_patches/full_imgs.shape[0])
        print("patches per full image: " + str(patch_per_img))
        iter_tot = 0  # iter over the total numbe rof patches (N_patches)
        for i in range(full_imgs.shape[0]):  # loop over the full images
            k = 0
            while k < patch_per_img:
                x_center = np.random.randint(
                    0+int(self.patch_w/2), img_w-int(self.patch_w/2))
                # print "x_center " +str(x_center)
                y_center = np.random.randint(
                    0+int(self.patch_h/2), img_h-int(self.patch_h/2))
                # print "y_center " +str(y_center)
                # check whether the patch is fully contained in the FOV
                if self.inside == True:
                    if is_patch_inside_FOV(x_center, y_center, img_w, img_h, self.patch_h) == False:
                        continue
                patch = full_imgs[i, :, y_center-int(self.patch_h/2):y_center+int(
                    self.patch_h/2), x_center-int(self.patch_w/2):x_center+int(self.patch_w/2)]
                patch_mask = full_masks[i, :, y_center-int(self.patch_h/2):y_center+int(
                    self.patch_h/2), x_center-int(self.patch_w/2):x_center+int(self.patch_w/2)]
                patches[iter_tot] = patch
                patches_masks[iter_tot] = patch_mask
                iter_tot += 1  # total
                k += 1  # per full_img
        return patches, patches_masks

def is_patch_inside_FOV(x, y, img_w, img_h, patch_h):
    x_ = x - int(img_w/2)  # origin (0,0) shifted to image center
    y_ = y - int(img_h/2)  # origin (0,0) shifted to image center
    # radius is 270 (from DRIVE db docs), minus the patch diagonal (assumed it is a square #this is the limit to contain the full patch in the FOV
    R_inside = 270 - int(patch_h * np.sqrt(2.0) / 2.0)
    radius = np.sqrt((x_*x_)+(y_*y_))
    if radius < R_inside:
        return True
    else:
        return False

max_stars_repo_name: ZexuanTHU/deep-bi

max_issues_repo_name: ZexuanTHU/deep-bi

max_forks_repo_name: ZexuanTHU/deep-bi


text:
"""
Forward Simulation for Straight Ray Tomography in 2D
====================================================

Here we module *SimPEG.seismic.straight_ray_tomography* to predict arrival
time data for a synthetic velocity/slowness model. In this tutorial, we focus on the following:

    - How to define the survey
    - How to define the forward simulation
    - How to predict arrival time data

"""

#########################################################################
# Import Modules
# --------------
#

import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

from discretize import TensorMesh

from SimPEG import maps
from SimPEG.seismic import straight_ray_tomography as tomo
from SimPEG.utils import model_builder

save_file = False

#############################################
# Defining the Survey
# -------------------
#
# Here, we define survey that will be used for the forward simulation. The survey
# consists of a horizontal line of point receivers at Y = 100 m and a horizontal
# line of point sources at Y = -100 m. The shot by each source is measured by
# all receivers.
#

# Define the locations for the sources and receivers.
x = np.linspace(-100, 100, 11)
y_receivers = 100 * np.ones(len(x))
y_sources = -100 * np.ones(len(x))

receiver_locations = np.c_[x, y_receivers]
source_locations = np.c_[x, y_sources]

# Define the list of receivers used by each source
receiver_list = [tomo.Rx(receiver_locations)]

# Define an empty list to store sources objects. Define each source and
# provide its corresponding receivers list
source_list = []
for ii in range(0, len(y_sources)):
    source_list.append(
        tomo.Src(location=source_locations[ii, :], receiver_list=receiver_list)
    )

# Define they tomography survey
survey = tomo.Survey(source_list)

#############################################
# Defining a Tensor Mesh
# ----------------------
#
# Here, we create the tensor mesh that will be used to predict arrival time
# data.
#

dh = 10.0  # cell width
N = 21  # number of cells in X and Y direction
hx = [(dh, N)]
hy = [(dh, N)]
mesh = TensorMesh([hx, hy], "CC")

########################################################
# Model and Mapping on Tensor Mesh
# --------------------------------
#
# Here, we create the velocity model that will be used to predict the data. Since
# the physical parameter for straight ray tomography is slowness, we must define
# a mapping which converts velocity values to slowness values. The model
# consists of a lower velocity block within a higher velocity background.
#

# Define velocity of each unit in m/s
background_velocity = 3000.0
block_velocity = 1500.0

# Define the model. Models in SimPEG are vector arrays.
model = background_velocity * np.ones(mesh.nC)

ind_block = model_builder.getIndicesBlock(np.r_[-50, 20], np.r_[50, -20], mesh.gridCC)
model[ind_block] = block_velocity

# Define a mapping from the model (velocity) to the slowness. If your model
# consists of slowness values, you can use *maps.IdentityMap*.
model_mapping = maps.ReciprocalMap()

# Plot Velocity Model
fig = plt.figure(figsize=(6, 5.5))

ax1 = fig.add_axes([0.15, 0.15, 0.65, 0.75])
mesh.plotImage(model, ax=ax1, grid=True, pcolorOpts={"cmap": "viridis"})
ax1.set_xlabel("x (m)")
ax1.set_ylabel("y (m)")
ax1.plot(x, y_sources, "ro")  # source locations
ax1.plot(x, y_receivers, "ko")  # receiver locations

ax2 = fig.add_axes([0.82, 0.15, 0.05, 0.75])
norm = mpl.colors.Normalize(vmin=np.min(model), vmax=np.max(model))
cbar = mpl.colorbar.ColorbarBase(
    ax2, norm=norm, orientation="vertical", cmap=mpl.cm.viridis
)
cbar.set_label("$Velocity (m/s)$", rotation=270, labelpad=15, size=12)

#######################################################
# Simulation: Arrival Time
# ------------------------
#
# Here we demonstrate how to predict arrival time data for the 2D straight
# ray tomography problem using the 2D Integral formulation.
#

# Define the forward simulation. To do this we need the mesh, the survey and
# the mapping from the model to the slowness values on the mesh.
simulation = tomo.Simulation(mesh, survey=survey, slownessMap=model_mapping)

# Compute predicted data for some model
dpred = simulation.dpred(model)

#######################################################
# Plotting
# -----------------------------------------------
#

n_source = len(source_list)
n_receiver = len(x)
dpred_plotting = dpred.reshape(n_receiver, n_source)

fig = plt.figure(figsize=(8, 5))
ax = fig.add_subplot(111)
obs_string = []

for ii in range(0, n_source):
    ax.plot(x, dpred_plotting[:, ii])
    obs_string.append("source {}".format(ii + 1))

ax.set_xlim(np.min(x), np.max(x))
ax.set_xlabel("x (m)")
ax.set_ylabel("arrival time (s)")
ax.set_title("Positions vs. Arrival Time")
ax.legend(obs_string, loc="upper right")

#######################################################
# Optional: Exporting Results
# ---------------------------
#
# Write the data and true model
#

if save_file:

    dir_path = os.path.dirname(tomo.__file__).split(os.path.sep)[:-3]
    dir_path.extend(["tutorials", "seismic", "assets"])
    dir_path = os.path.sep.join(dir_path) + os.path.sep

    noise = 0.05 * dpred * np.random.rand(len(dpred))

    data_array = np.c_[
        np.kron(x, np.ones(n_receiver)),
        np.kron(y_sources, np.ones(n_receiver)),
        np.kron(np.ones(n_source), x),
        np.kron(np.ones(n_source), y_receivers),
        dpred + noise,
    ]

    fname = dir_path + "tomography2D_data.obs"
    np.savetxt(fname, data_array, fmt="%.4e")

    output_model = model
    fname = dir_path + "true_model_2D.txt"
    np.savetxt(fname, output_model, fmt="%.4e")

max_stars_repo_name: Prithwijit-Chak/simpeg

max_issues_repo_name: thast/simpeg

max_forks_repo_name: thast/simpeg


text:
import os
import torch
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import cv2
import numpy as np

# We can use an image folder dataset the way we have it setup.
# Create the dataset
def DataLoader(dataroot, image_size, batch_size, workers):
    print('Loading training data ...')
    dataset = dset.ImageFolder(root=dataroot,
                           transform=transforms.Compose([
                               transforms.Resize((image_size,image_size)),
                               transforms.ToTensor(),
                           ]))
    # Create the dataloader
    sampler = torch.utils.data.SequentialSampler(dataset)

    dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size,
                                         shuffle=False, num_workers=workers,
                                                  sampler= sampler,
                                                  drop_last=True)

    return dataloader

def confusionMatrix_compare(imBinary, imGT):
    """ Compares a binary frames with the groundtruth frame """
    v = 85
    TP = np.sum((imGT==255) * (imBinary==255))		# True Positive
    TN = np.sum((imGT<=v) * (imBinary==0))		# True Negative
    FP = np.sum((imGT<=v) * (imBinary==255))    	        # False Positive
    FN = np.sum((imGT==255) * (imBinary==0))		# False Negative
    SE = np.sum((imGT==v) * (imBinary==255))		# Shadow Error

    p = imGT.shape[0] * imGT.shape[1]

    #print(np.max(imGT), np.max(imBinary))

    TP = float(TP)/p
    TN = float(TN)/p
    FP = float(FP)/p
    FN = float(FN)/p
    SE = float(SE)/p

    confusionMatrix = [TP,FP,FN,TN,SE];

    return np.array(confusionMatrix)

def confusionMatrixToVar(confusionMatrix):
    TP = confusionMatrix[0];
    FP = confusionMatrix[1];
    FN = confusionMatrix[2];
    TN = confusionMatrix[3];
    SE = confusionMatrix[4];

    recall = TP / (TP + FN);
    specficity = TN / (TN + FP);
    FPR = FP / (FP + TN);
    FNR = FN / (TP + FN);
    PBC = 100.0 * (FN + FP) / (TP + FP + FN + TN);
    precision = TP / (TP + FP);
    FMeasure = 2.0 * (recall * precision) / (recall + precision);

    stats = np.array([recall,specficity,FPR,FNR,PBC,precision,FMeasure])

    return stats

def NumberOfDigits(Number):
    Count = 0
    while(Number > 0):
        Number = Number//10
        Count = Count + 1

    return Count

def saveList(myList,filename):
    # the filename should mention the extension 'npy'
    np.save(filename,myList)
    print("Saved successfully!")

def Calcul_metrics(datasets, results_path):

    for dataset in datasets:
        GT_path = '/home/simon/Desktop/Scene_Analysis/CDnet/dataset2014/dataset/nightVideos/' + dataset +'/groundtruth/img/'
        nb_images = len([name for name in os.listdir(GT_path)])
        print('number of images: ', nb_images)
        mypath = results_path + dataset
        for f in os.listdir(mypath):
            #print(f)
            imgs_path = mypath + '/' + f + '/masks/img/'

            nb = '000001'
            results_ = []
            confusionMatrix = np.array([0.0,0.0,0.0,0.0,0.0])
            for i in range(nb_images):
                print(i)
                img_binary = cv2.imread(imgs_path + str(i) + '.jpg')[:,:,0]
                img_gt = cv2.imread(GT_path + 'gt'+str(nb) + '.png')[:,:,0]
                img_gt = cv2.resize(img_gt, (256,256))
                # print('Shapes: ', img_binary.shape)
                #print('Shapes: ', img_gt.shape)

                nb = int(nb)+1
                nb_digits = NumberOfDigits(int(nb))
                nb = str('0'*(6-nb_digits)) + str(nb)
                #print(nb)

                confusionMatrix += confusionMatrix_compare(img_binary, img_gt)

            confusionMatrix = confusionMatrix/nb_images
            stats = confusionMatrixToVar(confusionMatrix)
            results_.append(stats)
            saveList(results_, results_path + 'results/' + f + '.npy')
            print('F1-measure: ', stats[-1])
            print('recall, precision: ', stats[0], stats[-2])
            #print(confusionMatrix.shape)
            #break
            #assert(0)

def loadList(filenames):
    for filename in os.listdir(filenames):
        # the filename should mention the extension 'npy'
        tempNumpyArray=np.load(filenames + filename)[0,-1]
        if True:#filename.split('_')[-1:][0] == 'abandonedBox.npy':
            print(filename.split('_')[0:2], filename.split('_')[-2:], tempNumpyArray)
    #return tempNumpyArray.tolist()

results_path = 'output_CDnet2014/nightVideos/'
datasets = ['streetCornerAtNight']

#Calcul_metrics(datasets, results_path)
loadList(results_path + 'results/')


text:
#
# Copyright (c) 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import numpy as np
import pygame
from pygame.locals import HWSURFACE, DOUBLEBUF

class Renderer(object):
    def __init__(self):
        self.size = (1, 1)
        self.screen = None
        self.clock = pygame.time.Clock()
        self.display = pygame.display
        self.fps = 30
        self.pressed_keys = []
        self.is_open = False

    def create_screen(self, width, height):
        """
        Creates a pygame window
        :param width: the width of the window
        :param height: the height of the window
        :return: None
        """
        self.size = (width, height)
        self.screen = self.display.set_mode(self.size, HWSURFACE | DOUBLEBUF)
        self.display.set_caption("Coach")
        self.is_open = True

    def normalize_image(self, image):
        """
        Normalize image values to be between 0 and 255
        :param image: 2D/3D array containing an image with arbitrary values
        :return: the input image with values rescaled to 0-255
        """
        image_min, image_max = image.min(), image.max()
        return 255.0 * (image - image_min) / (image_max - image_min)

    def render_image(self, image):
        """
        Render the given image to the pygame window
        :param image: a grayscale or color image in an arbitrary size. assumes that the channels are the last axis
        :return: None
        """
        if self.is_open:
            if len(image.shape) == 2:
                image = np.stack([image] * 3)
            if len(image.shape) == 3:
                if image.shape[0] == 3 or image.shape[0] == 1:
                    image = np.transpose(image, (1, 2, 0))
            surface = pygame.surfarray.make_surface(image.swapaxes(0, 1))
            surface = pygame.transform.scale(surface, self.size)
            self.screen.blit(surface, (0, 0))
            self.display.flip()
            self.clock.tick()
            self.get_events()

    def get_events(self):
        """
        Get all the window events in the last tick and reponse accordingly
        :return: None
        """
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                self.pressed_keys.append(event.key)
                # esc pressed
                if event.key == pygame.K_ESCAPE:
                    self.close()
            elif event.type == pygame.KEYUP:
                if event.key in self.pressed_keys:
                    self.pressed_keys.remove(event.key)
            elif event.type == pygame.QUIT:
                self.close()

    def get_key_names(self, key_ids):
        """
        Get the key name for each key index in the list
        :param key_ids: a list of key id's
        :return: a list of key names corresponding to the key id's
        """
        return [pygame.key.name(key_id) for key_id in key_ids]

    def close(self):
        """
        Close the pygame window
        :return: None
        """
        self.is_open = False
        pygame.quit()


text:
import os
import sys

from matplotlib import pyplot as plt

from astropy.io import fits, ascii as asc
from astropy.table import Table, Column

from utilities_az import spectroscopy as spec

#sys.path.append(<path to line_fitting>)
from fit_spectral_lines import define_feature

filename = '../../data/2014G/2014G_2014-03-17_19-09-29_Galileo_BC-Asi_None.dat'

tbdata = asc.read(filename, names=['wave', 'flux'])
error = tbdata['flux']*0.05
#error = None
spectrum = spec.spectrum1d(tbdata['wave'], tbdata['flux'], error)
spectrum.filename = filename
line_name = 'A'

min_list, pew_list, fig = define_feature(spectrum, line_name,
                                         absorption=True,
                                         similar_widths=True,
                                         interactive = True,
                                         define_fit_range=True,
                                         input_append=True,
                                         input_filename = 'test.yml')

min_wave = [i[0] for i in min_list]
min_wave_std = [j[1].value for j in min_list]
min_col = Column(min_wave, name='min')
min_err_col = Column(min_wave_std, name='min_err')

pew = [i[0] for i in pew_list]
pew_err = [j[1] for j in pew_list]
pew_col = Column(pew, name='pew')
pew_err_col = Column(pew_err, name='pew_err')
output = Table([min_col, min_err_col, pew_col, pew_err_col])
output.write(os.path.basename(filename).split('.')[0]+'line_fit_{}.csv'.format(line_name), format='csv')

fig.savefig(os.path.basename(filename).split('.')[0]+'line_fit_{}.pdf'.format(line_name))

reason: from astropy


text:
"""
 Network of IF cells - Sustained Activity

License: Modified BSD (see LICENSE.txt)
"""

import sys
from math import sqrt, pi
import numpy as np

SIMULATOR = sys.argv[-1]
exec("import pyNN.%s as pyNN" % SIMULATOR)

#-----------------------------------------------------------------
#  Parameters
#-----------------------------------------------------------------

# General parameters

SEED_LTS = 428577
SEED_CONN = 193566
SEED_GEN = 983651

DT = 0.1                                        # (ms) Time step
TSTART  = 0
TSTOP   = 1200
V_INIT  = -60.0

# Cell parameters

LENGTH          = sqrt(20000/pi)                # in um
DIAMETER        = sqrt(20000/pi)                # in um
AREA            = 1e-8 * pi * LENGTH * DIAMETER # membrane area in cm2
TAU             = 20                            # time constant in ms
CAPACITANCE     = 1                             # capacitance in muF/cm2
G_L             = 1e-3 * CAPACITANCE / TAU      # leak conductance in S/cm2
V_REST          = -60                           # resting potential

a_RS            = 0.001
b_RS            = 0.1   # full adaptation
b_RS            = 0.005 # weaker adaptation

b_RSa            = 0.04 # Figure 1a
b_RSb            = 0.005 # Figure 1b

a_LTS           = 0.02
b_LTS           = 0.0
a_FS            = 0.001
b_FS            = 0.0

TAU_W           = 600
DELTA           = 2.5

# Spike parameters

VTR             = -50           # threshold in mV
VTOP            = 40            # top voltage during spike in mV
VBOT            = -60           # reset voltage in mV
REFRACTORY      = 5.0/2         # refractory period in ms (correction for a bug in IF_CG4)

# Synapse parameters

scale = 1               # scaling factor (>1 = more synapses)

TAU_E           = 5             # excitation time constant in ms
TAU_I           = 10            # inhibition time constant in ms
V_E             = 0             # excitatory reversal potential
V_I             = -80           # inhibitory reversal potential

N_GEN = 1           # total number of cells

MODEL_ID        = "cx05_cells_%s" % SIMULATOR

NEURONS_TO_RECORD = range(0,N_GEN)

# NEURON-specific parameters

NEURONS_TO_PLOT = NEURONS_TO_RECORD
USE_CVODE = False # }

#-----------------------------------------------------------------
#  Create cells
#-----------------------------------------------------------------

# we now use a standard cell model from PyNN, so there is nothing to do here

all_populations = []

def netCreate():
    global nLTS, neurons_RS, neurons_LTS, neurons_FS, all_populations
    RS_parameters = {
        'cm': 1000*AREA*CAPACITANCE, 'tau_m': TAU, 'v_rest': V_REST,
        'v_thresh': VTR, 'tau_refrac': REFRACTORY+DT,
        'v_reset': VBOT, 'v_spike': VTR+1e-6, 'a': 1000.0*a_RS, 'b': b_RS,
        'tau_w': TAU_W, 'delta_T': DELTA, 'tau_syn_E': TAU_E, 'e_rev_E': V_E,
        'tau_syn_I': TAU_I, 'e_rev_I': V_I
    }
    #RS_parameters['i_offset'] = 0.1

    RSa_parameters = RS_parameters.copy()
    RSa_parameters.update({'b': b_RSa})

    RSb_parameters = RS_parameters.copy()
    RSb_parameters.update({'b': b_RSb})

    LTS_parameters = RS_parameters.copy()
    LTS_parameters.update({'a': 1000.0*a_LTS, 'b': b_LTS}) # 1000 is for uS --> nS
    FS_parameters = RS_parameters.copy()
    FS_parameters.update({'a': 1000.0*a_FS, 'b': b_FS})

    neurons_RSa = pyNN.Population(N_GEN, pyNN.EIF_cond_exp_isfa_ista, RSa_parameters, label="RSa")
    neurons_RSb = pyNN.Population(N_GEN, pyNN.EIF_cond_exp_isfa_ista, RSb_parameters, label="RSb")

    neurons_LTS = pyNN.Population(N_GEN, pyNN.EIF_cond_exp_isfa_ista, LTS_parameters, label="LTS")
    neurons_FS = pyNN.Population(N_GEN, pyNN.EIF_cond_exp_isfa_ista, FS_parameters, label="FS")

    all_populations = [neurons_RSa,neurons_RSb,neurons_LTS,neurons_FS]

    ################################################################
    #IClamp
    step_current = pyNN.DCSource(amplitude= 0.25, start=200.0, stop=700.0)

    for pop in all_populations:
        step_current.inject_into(pop)
        pyNN.initialize(pop, v=VBOT)

    ################################################################

#-----------------------------------------------------------------
# Simulation settings
#-----------------------------------------------------------------

pyNN.setup(DT, min_delay=DT, use_cvode=USE_CVODE, rng_seeds_seed=SEED_GEN)

#-----------------------------------------------------------------
#  Add graphs
#-----------------------------------------------------------------

print ""
print "======================================================================="
print "            Network of ",N_GEN," * 3 IF neurons in an active state"
print "======================================================================="
print ""

#------------------------------------------------------------------------------
#  creating cells
#------------------------------------------------------------------------------
print "----[ CREATING CELLS ]----"
netCreate()

#-----------------------------------------------------------------
# Procedure to run simulation and menu
#-----------------------------------------------------------------

def run_sim():

        # record the Vm

        for pop in all_populations:
            pop.record('v')

        print "----[ RUNNING SIMULATION ]----"
        pyNN.run(TSTOP)

        pyNN.end()

        for pop in all_populations:
            data =  pop.get_data('v', gather=False)
            filename = "%s_v.dat"%(pop.label)
            print("Writing data for %s"%pop)
            for segment in data.segments:
                vm = segment.analogsignals[0].transpose()[0]
                tt = np.array([t*DT/1000. for t in range(len(vm))])
                times_vm = np.array([tt, vm/1000.]).transpose()
                np.savetxt(filename, times_vm , delimiter = '\t', fmt='%s')
        '''
        if SIMULATOR in ['neuron', 'nest', 'brian']:
            import matplotlib.pyplot as plt

            plt.figure(1)
            vmrs = neurons_RS.get_v()
            vmlts = neurons_LTS.get_v()
            vmfs = neurons_FS.get_v()

            times = []
            voltsrs = []
            voltslts = []
            voltsfs = []
            for i in range(N_GEN):
                times.append([])
                voltsrs.append([])
                voltslts.append([])
                voltsfs.append([])

            ids = vmrs[:,0]
            ts = vmrs[:,1]
            vsrs = vmrs[:,2]
            vslts = vmlts[:,2]
            vsfs = vmfs[:,2]
            for i in range(len(ids)):
                times[int(ids[i])].append(ts[i])
                voltsrs[int(ids[i])].append(vsrs[i])
                voltslts[int(ids[i])].append(vslts[i])
                voltsfs[int(ids[i])].append(vsfs[i])

            for i in range(N_GEN):
                plt.plot(times[i],voltsrs[i], '-')
                plt.plot(times[i],voltslts[i], '-')
                plt.plot(times[i],voltsfs[i], '-')

            plt.show()'''

        print "----[ FINISHED ]----"

run_sim()


text:
import tensorflow as tf
import numpy as np
import optuna

import tensorflow.keras.backend as K

keras = tf.keras

class OptunaCallback(keras.callbacks.Callback):
    def __init__(self, trial):
        self.trial = trial

    def on_epoch_end(self, epoch, logs):
        current_val_error = 1.0 - logs["val_acc"]
        self.trial.report(current_val_error, step=epoch)
        # 打ち切り判定
        if self.trial.should_prune(epoch):
            raise optuna.structs.TrialPruned()

def create_dataset(batch_size):
    (x_train,y_train), (x_valid,y_valid)=keras.datasets.fashion_mnist.load_data()
    x_train = x_train / 255.0
    x_train = np.reshape(x_train,(60000,28,28,1))
    x_train = x_train.astype(np.float32)
    y_train = tf.keras.utils.to_categorical(y_train,num_classes=10)

    x_valid = x_valid / 255.0
    x_valid = np.reshape(x_valid, (10000,28,28,1))
    x_valid = x_valid.astype(np.float32)
    y_valid = tf.keras.utils.to_categorical(y_valid,num_classes=10)

    c = tf.Variable(0, dtype=tf.int32)

    def map_fn(x,y):
        # c.assign_add(1)
        return (x,y)

    train_set= tf.data.Dataset.from_tensor_slices((x_train,y_train)).map(map_func=map_fn).repeat().batch(batch_size)
    valid_set = tf.data.Dataset.from_tensor_slices((x_valid,y_valid)).repeat().batch(batch_size)
    return (train_set, 60000),(valid_set, 10000)

def create_model():
    model = tf.keras.Sequential()
    model.add(tf.keras.Input(shape=(28,28,1)))
    model.add(tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu'))
    model.add(tf.keras.layers.Conv2D(64, (3, 3), activation='relu'))
    model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))
    model.add(tf.keras.layers.Dropout(0.25))
    model.add(tf.keras.layers.Flatten())
    model.add(tf.keras.layers.Dense(128, activation='relu'))
    model.add(tf.keras.layers.Dropout(0.5))
    model.add(tf.keras.layers.Dense(10, activation='softmax'))

    return model

def train(lr, max_epoch, trial):
    batch_size = 100
    (train_set, train_num), (valid_set, valid_num) = create_dataset(batch_size)

    print(train_set)

    model = create_model()
    optimizer = tf.keras.optimizers.SGD(lr=lr)
    model.compile(loss='categorical_crossentropy',
              optimizer=optimizer,
              metrics=['accuracy'])
    model.summary()
    optuna_callback = OptunaCallback(trial)
    model.fit(train_set,steps_per_epoch=train_num/batch_size,validation_data=valid_set,validation_steps=valid_num/batch_size,epochs=max_epoch)

def objective(trial):
    max_epoch = 20
    learning_rate = trial.suggest_loguniform("learning_rate", 1e-7, 1e0)
    K.clear_session()
    train(learning_rate, max_epoch, trial)
    hist = train(learning_rate, max_epoch, trial)
    return 1.0 - np.max(hist["val_acc"])

if __name__ == '__main__':
    study = optuna.create_study()
    study.optimize(objective, n_trials=2)


text:
# -*- coding: utf-8 -*-
"""
:py:mod:`gpUtils.py` - Gaussian Process Utilities
-------------------------------------------------

Gaussian process utility functions for initializing GPs and optimizing their
hyperparameters.

"""

# Tell module what it's allowed to import
__all__ = ["defaultHyperPrior", "defaultGP", "optimizeGP"]

from . import utility as util
import numpy as np
import george
from scipy.optimize import minimize
from sklearn.model_selection import KFold
from sklearn.metrics import mean_squared_error

def defaultHyperPrior(p):
    """
    Default prior function for GP hyperparameters. This prior also keeps the
    hyperparameters within a reasonable huge range, [-20, 20]. Note that george
    operates on the *log* hyperparameters, except for the mean function.

    Parameters
    ----------
    p : array/iterable
        Array of GP hyperparameters

    Returns
    -------
    prior : float
    """

    # Restrict range of hyperparameters (ignoring mean term)
    if np.any(np.fabs(p)[1:] > 20):
        return -np.inf

    return 0.0
# end function

def _nll(p, gp, y, priorFn=None):
    """
    Given parameters and data, compute the negative log likelihood of the data
    under the george Gaussian process.

    Parameters
    ----------
    p : array
        GP hyperparameters
    gp : george.GP
    y : array
        data to condition GP on
    priorFn : callable
        Prior function for the GP hyperparameters, p

    Returns
    -------
    nll : float
        negative log-likelihood of y under gp
    """

    # Apply priors on GP hyperparameters
    if priorFn is not None:
        if not np.isfinite(priorFn(p)):
            return np.inf

    # Catch singular matrices
    try:
        gp.set_parameter_vector(p)
    except np.linalg.LinAlgError:
        return np.inf

    ll = gp.log_likelihood(y, quiet=True)
    return -ll if np.isfinite(ll) else np.inf
# end function

def _grad_nll(p, gp, y, priorFn=None):
    """
    Given parameters and data, compute the gradient of the negative log
    likelihood of the data under the george Gaussian process.

    Parameters
    ----------
    p : array
        GP hyperparameters
    gp : george.GP
    y : array
        data to condition GP on
    priorFn : callable
        Prior function for the GP hyperparameters, p

    Returns
    -------
    gnll : float
        gradient of the negative log-likelihood of y under gp
    """

    # Apply priors on GP hyperparameters
    if priorFn is not None:
        if not np.isfinite(priorFn(p)):
            return np.inf

    # Negative gradient of log likelihood
    return -gp.grad_log_likelihood(y, quiet=True)
# end function

def defaultGP(theta, y, order=None, white_noise=-12, fitAmp=False):
    """
    Basic utility function that initializes a simple GP with an ExpSquaredKernel.
    This kernel  works well in many applications as it effectively enforces a
    prior on the smoothness of the function and is infinitely differentiable.

    Parameters
    ----------
    theta : array
        Design points
    y : array
        Data to condition GP on, e.g. the lnlike + lnprior at each design point,
        theta.
    order : int, optional
        Order of PolynomialKernel to add to ExpSquaredKernel. Defaults to None,
        that is, no PolynomialKernel is added and the GP only uses the
        ExpSquaredKernel
    white_noise : float, optional
        From george docs: "A description of the logarithm of the white noise
        variance added to the diagonal of the covariance matrix". Defaults to
        ln(white_noise) = -12. Note: if order is not None, you might need to
        set the white_noise to a larger value for the computation to be
        numerically stable, but this, as always, depends on the application.
    fitAmp : bool, optional
        Whether or not to include an amplitude term. Defaults to False.

    Returns
    -------
    gp : george.GP
        Gaussian process with initialized kernel and factorized covariance
        matrix.
    """

    # Tidy up the shapes and determine dimensionality
    theta = np.asarray(theta).squeeze()
    y = np.asarray(y).squeeze()
    if theta.ndim <= 1:
        ndim = 1
    else:
        ndim = theta.shape[-1]

    # Guess initial metric, or scale length of the covariances (must be > 0)
    initialMetric = np.fabs(np.random.randn(ndim))

    # Create kernel: We'll model coveriances in loglikelihood space using a
    # ndim-dimensional Squared Expoential Kernel
    kernel = george.kernels.ExpSquaredKernel(metric=initialMetric,
                                             ndim=ndim)

    # Include an amplitude term?
    if fitAmp:
        kernel = np.var(y) * kernel

    # Add a linear regression kernel of order order?
    # Use a meh guess for the amplitude and for the scale length (log(gamma^2))
    if order is not None:
        kernel = kernel + (np.var(y)/10.0) * george.kernels.LinearKernel(log_gamma2=initialMetric[0],
                                                                         order=order,
                                                                         bounds=None,
                                                                         ndim=ndim)

    # Create GP and compute the kernel, aka factor the covariance matrix
    gp = george.GP(kernel=kernel, fit_mean=True, mean=np.median(y),
                   white_noise=white_noise, fit_white_noise=False)
    gp.compute(theta)

    return gp
# end function

def optimizeGP(gp, theta, y, seed=None, nGPRestarts=1, method="powell",
               options=None, p0=None, gpHyperPrior=defaultHyperPrior):
    """
    Optimize hyperparameters of an arbitrary george Gaussian Process by
    maximizing the marginal loglikelihood.

    Parameters
    ----------
    gp : george.GP
    theta : array
    y : array
        data to condition GP on
    seed : int, optional
        numpy RNG seed.  Defaults to None.
    nGPRestarts : int, optional
        Number of times to restart the optimization.  Defaults to 1. Increase
        this number if the GP isn't optimized well.
    method : str, optional
        scipy.optimize.minimize method.  Defaults to powell.
    options : dict, optional
        kwargs for the scipy.optimize.minimize function.  Defaults to None.
    p0 : array, optional
        Initial guess for kernel hyperparameters.  If None, defaults to
        np.random.randn for each parameter
    gpHyperPrior : str/callable, optional
        Prior function for GP hyperparameters. Defaults to the defaultHyperPrior fn.
        This function asserts that the mean must be negative and that each log
        hyperparameter is within the range [-20,20].

    Returns
    -------
    optimizedGP : george.GP
    """

    # Run the optimization routine nGPRestarts times
    res = []
    mll = []

    # Optimize GP hyperparameters by maximizing marginal log_likelihood
    for ii in range(nGPRestarts):
        # Initialize inputs for each minimization
        if p0 is None:
            # Pick random guesses for kernel hyperparameters
            x0 = [np.median(y)] + [np.random.randn() for _ in range(len(gp.get_parameter_vector())-1)]
        else:
            # Take user-supplied guess and slightly perturb it
            x0 = np.array(p0) + np.min(p0) * 1.0e-3 * np.random.randn(len(p0))

        # Minimize GP nll, save result, evaluate marginal likelihood
        if method not in ["nelder-mead", "powell", "cg"]:
            jac = _grad_nll
        else:
            jac = None

        resii = minimize(_nll, x0, args=(gp, y, gpHyperPrior), method=method,
                         jac=jac, bounds=None, options=options)["x"]
        res.append(resii)

        # Update the kernel with solution for computing marginal loglike
        gp.set_parameter_vector(resii)
        gp.recompute()

        # Compute marginal log likelihood for this set of kernel hyperparameters
        mll.append(gp.log_likelihood(y, quiet=True))

    # Pick result with largest marginal log likelihood
    ind = np.argmax(mll)

    # Update gp
    gp.set_parameter_vector(res[ind])
    gp.recompute()

    return gp
# end function

max_stars_repo_name: RoryBarnes/approxposterior

max_issues_repo_name: RoryBarnes/approxposterior

max_forks_repo_name: RoryBarnes/approxposterior

reason: import numpy,from scipy


text:
# MIT License
#
# Copyright (c) 2019 Chris Choy (chrischoy@ai.stanford.edu)
#                    Junha Lee (junhakiwi@postech.ac.kr)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import re
import h5py
import numpy as np
from os.path import isdir, join

def sorted_alphanum(file_list_ordered):
  convert = lambda text: int(text) if text.isdigit() else text
  alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
  return sorted(file_list_ordered, key=alphanum_key)

def get_folder_list(path):
  folder_list = [join(path, f) for f in os.listdir(path) if isdir(join(path, f))]
  folder_list = sorted_alphanum(folder_list)
  return folder_list

def read_txt(path):
  """Read txt file into lines.
  """
  with open(path) as f:
    lines = f.readlines()
  lines = [x.strip() for x in lines]
  return lines

def ensure_dir(path):
  if not os.path.exists(path):
    os.makedirs(path, mode=0o755)

def random_sample(arr, num_sample, fix=True):
  """Sample elements from array

  Args:
    arr (array): array to sample
    num_sample (int): maximum number of elements to sample

  Returns:
    array: sampled array

  """
  # Fix seed
  if fix:
    np.random.seed(0)

  total = len(arr)
  num_sample = min(total, num_sample)
  idx = sorted(np.random.choice(range(total), num_sample, replace=False))
  return np.asarray(arr)[idx]

def loadh5(path):
  """Load h5 file as dictionary

  Args:
    path (str): h5 file path

  Returns:
    dict_file (dict): loaded dictionary

  """
  try:
    with h5py.File(path, "r") as h5file:
      return readh5(h5file)
  except Exception as e:
    print("Error while loading {}".format(path))
    raise e

def readh5(h5node):
  """Read h5 node recursively and loaded into a dict

  Args:
    h5node (h5py._hl.files.File): h5py File object

  Returns:
    dict_file (dict): loaded dictionary

  """
  dict_file = {}
  for key in h5node.keys():
    if type(h5node[key]) == h5py._hl.group.Group:
      dict_file[key] = readh5(h5node[key])
    else:
      dict_file[key] = h5node[key][...]
  return dict_file

def saveh5(dict_file, target_path):
  """Save dictionary as h5 file

  Args:
    dict_file (dict): dictionary to save
    target_path (str): target path string

  """

  with h5py.File(target_path, "w") as h5file:
    if isinstance(dict_file, list):
      for i, d in enumerate(dict_file):
        newdict = {"dict" + str(i): d}
        writeh5(newdict, h5file)
    else:
      writeh5(dict_file, h5file)

def writeh5(dict_file, h5node):
  """Write dictionaly recursively into h5py file

  Args:
    dict_file (dict): dictionary to write
    h5node (h5py._hl.file.File): target h5py file
  """

  for key in dict_file.keys():
    if isinstance(dict_file[key], dict):
      h5node.create_group(key)
      cur_grp = h5node[key]
      writeh5(dict_file[key], cur_grp)
    else:
      h5node[key] = dict_file[key]

max_stars_repo_name: junha-l/open-ucn

max_issues_repo_name: junha-l/open-ucn

max_forks_repo_name: junha-l/open-ucn


text:
import os
from flask import Flask, request, send_file, redirect, render_template
import easyocr
import PIL
from PIL import Image, ImageOps
import base64
import numpy as np
import io
from queue import Queue, Empty
import time
import threading

UPLOAD_FOLDER = 'static/uploads'

app = Flask(__name__, template_folder='templates')
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024*5

requests_queue = Queue()
BATCH_SIZE = 1
CHECK_INTERVAL = 0.1

def handle_requests_by_batch():
    while True:
        requests_batch = []
        while not (len(requests_batch) >= BATCH_SIZE):
            try:
                requests_batch.append(requests_queue.get(timeout=CHECK_INTERVAL))
            except Empty:
                continue
            batch_outputs = []
            for request in requests_batch:
                batch_outputs.append(run(request['input'][0], request['input'][1]))

            for request, output in zip(requests_batch, batch_outputs):
                request['output'] = output

threading.Thread(target=handle_requests_by_batch).start()

def run(file, lang):
    try:
        imgFile = np.array(PIL.Image.open(file).convert("RGB"))

        if lang == 'eng':
            reader = easyocr.Reader(['en'])
        else:
            reader = easyocr.Reader([lang, 'en'])

        text = reader.readtext(imgFile)
        res_list = list()

        for i in text:
            res_list.append(i[1])

        res_str = ''

        for i in res_list:
            res_str = res_str + ' ' + i

        imgFile = PIL.Image.fromarray(imgFile)
        img_io = io.BytesIO()
        imgFile.save(img_io, 'jpeg', quality=100)
        img_io.seek(0)
        img = base64.b64encode(img_io.getvalue())

        return [res_str, img]
    except Exception as e:
        print("error : ",e)
        return 500

# Web server
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            print('no file')
            return redirect(request.url)

        lang = str(request.form['lang'])
        file = request.files['file']

        if lang in ['ko', 'ja', 'th', 'ch_tra', 'ch_sim', 'af', 'eng']:
            pass
        else:
            return render_template('index.html', result = 'Import valid language.'), 400

        try:
            PIL.Image.open(file).convert("RGB")
        except Exception:
            return render_template('index.html', result = 'Import image please'), 400

        if file.filename == '':
            print('no filename')
            return redirect(request.url)

        # stateless image
        if requests_queue.qsize() >= BATCH_SIZE:
            return render_template('index.html', result = 'TooMany requests try again'), 429

        req = {
            'input': [file, lang]
        }
        requests_queue.put(req)

        while 'output' not in req:
            time.sleep(CHECK_INTERVAL)

        if req['output'] == 500:
            return render_template('index.html', result = 'server error'), 500

        [res, img] = req['output']
        return render_template('index.html', result=str(res), rawimg=img.decode('ascii'))
    return render_template('index.html')

# Start Swagger API Server
@app.route('/word_extraction', methods=['POST'])
def word_extraction():
    if not request.files.get('base_image'):
        return {'error': 'must have a base image'}, 400

    target_language = str(request.form['language'])
    file = request.files['base_image']

    if target_language not in ['ko', 'ja', 'th', 'ch_tra', 'ch_sim', 'af', 'eng']:
        return {'error': f'please check language. {target_language} is not supported.'}

    try:
        PIL.Image.open(file).convert("RGB")
    except Exception:
        return {'error': 'please upload image file.'}, 400

    if requests_queue.qsize() >= BATCH_SIZE:
        return {'error': 'TooMany requests try again'}, 429

    req = {
        'input': [file, target_language]
    }
    requests_queue.put(req)

    while 'output' not in req:
        time.sleep(CHECK_INTERVAL)
    if req['output'] == 500:
        return {'error': 'server error'}, 500
    [res, img] = req['output']
    return str(res)

@app.route('/healthz', methods=['GET'])
def checkHealth():
	return "Pong",200

@app.errorhandler(413)
def request_entity_too_large(error):
    return render_template('index.html', result = 'The image size is too large'), 413

if __name__ == '__main__':
    app.run(debug=False, port=8000, host='0.0.0.0', threaded=True)

max_stars_repo_name: Laeyoung/EasyOCR

max_issues_repo_name: Laeyoung/EasyOCR

max_forks_repo_name: Laeyoung/EasyOCR


text:
#
#
# Regression and Classification programming exercises
#
#

#
#	In this exercise we will be taking a small data set and computing a linear function
#	that fits it, by hand.
#

#	the data set

import numpy as np

sleep = [5,6,7,8,10]
scores = [65,51,75,75,86]

def compute_regression(sleep,scores):

    #	First, compute the average amount of each list

    avg_sleep = np.mean(sleep)
    avg_scores = np.mean(scores)

    #	Then normalize the lists by subtracting the mean value from each entry

    normalized_sleep = sleep - avg_sleep
    normalized_scores = scores - avg_scores

    #	Compute the slope of the line by taking the sum over each student
    #	of the product of their normalized sleep times their normalized test score.
    #	Then divide this by the sum of squares of the normalized sleep times.

    slope = sum(normalized_sleep*normalized_scores) /  sum(normalized_sleep * normalized_sleep)

    #	Finally, We have a linear function of the form
    #	y - avg_y = slope * ( x - avg_x )
    #	Rewrite this function in the form
    #	y = m * x + b
    #	Then return the values m, b

    m = slope
    b = avg_scores - (slope * avg_sleep)

    return m,b

if __name__=="__main__":
    m,b = compute_regression(sleep,scores)
    print "Your linear model is y={}*x+{}".format(m,b)

max_stars_repo_name: armandosrz/UdacityNanoMachine

max_issues_repo_name: armandosrz/UdacityNanoMachine

max_forks_repo_name: armandosrz/UdacityNanoMachine