


from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
 from PIL import Image

 from ..image_utils import load_image

if is_tf_available():
 import tensorflow as tf

 from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
 from ..tf_utils import stable_softmax

if is_torch_available():
 from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

__a     =			logging.get_logger(__name__)






@add_end_docstrings(__snake_case  )
class   __lowercase				(  __snake_case  ):





      def __init__(		self						:					Union[str, Any]					,       *__lowerCamelCase						:					Optional[Any]					,       **__lowerCamelCase						:					Optional[Any]       )    ->   Optional[int]:






         """simple docstring"""







         super().__init__(*__lowerCamelCase					,       **__lowerCamelCase       )
         requires_backends(self					,       """vision"""       )
         self.check_model_type(
             TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
             if self.framework == """tf"""
             else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING       )





      def        _lowercase				(		self						:					Optional[int]					,       __lowerCamelCase						:					Optional[int]=None       )    ->   Dict:






         """simple docstring"""







         UpperCAmelCase							=     {}
         if top_k is not None:
            UpperCAmelCase							=     top_k
         return {}, {}, postprocess_params





      def __call__(		self						:					Optional[int]					,       __lowerCamelCase						:					Union[str, List[str], "Image.Image", List["Image.Image"]]					,       **__lowerCamelCase						:					Optional[int]       )    ->   int:






         """simple docstring"""







         return super().__call__(__lowerCamelCase					,       **__lowerCamelCase       )





      def        _lowercase				(		self						:					Tuple					,       __lowerCamelCase						:					List[str]       )    ->   Optional[int]:






         """simple docstring"""







         UpperCAmelCase							=     load_image(__lowerCamelCase       )
         UpperCAmelCase							=     self.image_processor(images=__lowerCamelCase					,       return_tensors=self.framework       )
         return model_inputs





      def        _lowercase				(		self						:					List[str]					,       __lowerCamelCase						:					Optional[int]       )    ->   Any:






         """simple docstring"""







         UpperCAmelCase							=     self.model(**__lowerCamelCase       )
         return model_outputs





      def        _lowercase				(		self						:					Dict					,       __lowerCamelCase						:					Optional[Any]					,       __lowerCamelCase						:					str=5       )    ->   Any:






         """simple docstring"""







         if top_k > self.model.config.num_labels:
            UpperCAmelCase							=     self.model.config.num_labels

         if self.framework == "pt":
            UpperCAmelCase							=     model_outputs.logits.softmax(-1       )[0]
            UpperCAmelCase				,  UpperCAmelCase							=     probs.topk(__lowerCamelCase       )
         elif self.framework == "tf":
            UpperCAmelCase							=     stable_softmax(model_outputs.logits					,       axis=-1       )[0]
            UpperCAmelCase							=     tf.math.top_k(__lowerCamelCase					,       k=__lowerCamelCase       )
            UpperCAmelCase				,  UpperCAmelCase							=     topk.values.numpy(), topk.indices.numpy()
         else:
            raise ValueError(F"""Unsupported framework: {self.framework}"""       )

         UpperCAmelCase							=     scores.tolist()
         UpperCAmelCase							=     ids.tolist()
         return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(__lowerCamelCase					,       __lowerCamelCase       )]







import math






class   __lowercase				:





      def        _lowercase				(		self						:					Union[str, Any]					,       __lowerCamelCase						:					list[list[float]]					,       __lowerCamelCase						:					list[int]       )    ->   int:






         """simple docstring"""







         UpperCAmelCase							=     0.0
         UpperCAmelCase							=     0.0
         for i in range(len(__lowerCamelCase       )       ):
            da += math.pow((sample[i] - weights[0][i])					,       2       )
            da += math.pow((sample[i] - weights[1][i])					,       2       )
            return 0 if da > da else 1
         return 0





      def        _lowercase				(		self						:					List[Any]					,       __lowerCamelCase						:					list[list[int | float]]					,       __lowerCamelCase						:					list[int]					,       __lowerCamelCase						:					int					,       __lowerCamelCase						:					float       )    ->   list[list[int | float]]:






         """simple docstring"""







         for i in range(len(__lowerCamelCase       )       ):
            weights[j][i] += alpha * (sample[i] - weights[j][i])
         return weights

def   _UpperCamelCase				(						)						->None:
   # Training Examples ( m, n )
   UpperCAmelCase							=     [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]]

   # weight initialization ( n, C )
   UpperCAmelCase							=     [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]]

   # training
   UpperCAmelCase							=     SelfOrganizingMap()
   UpperCAmelCase							=     3
   UpperCAmelCase							=     0.5

   for _ in range(lowerCAmelCase_   ):
      for j in range(len(lowerCAmelCase_   )   ):
         # training sample
         UpperCAmelCase							=     training_samples[j]

         # Compute the winning vector
         UpperCAmelCase							=     self_organizing_map.get_winner(lowerCAmelCase_  ,						lowerCAmelCase_   )

         # Update the winning vector
         UpperCAmelCase							=     self_organizing_map.update(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_   )

    # classify test sample
   UpperCAmelCase							=     [0, 0, 0, 1]
   UpperCAmelCase							=     self_organizing_map.get_winner(lowerCAmelCase_  ,						lowerCAmelCase_   )

   # results
   print(F"""Clusters that the test sample belongs to : {winner}"""   )
   print(F"""Weights that have been trained : {weights}"""   )


# running the main() function
if __name__ == "__main__":
 main()



