
"""simple docstring"""




# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
    import torch







class     lowercase(TensorFormatter[Mapping, 'torch.Tensor', Mapping]       ):



     def __init__(							self     ,				__SCREAMING_SNAKE_CASE=None     ,				**__SCREAMING_SNAKE_CASE   )		->     Optional[int]:







         """simple docstring"""



         super().__init__(features=__SCREAMING_SNAKE_CASE   )
         a__		=			torch_tensor_kwargs
         import torch  # noqa import torch at initialization



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     Any:







         """simple docstring"""



         import torch

         if isinstance(__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   ) and column:
             if all(
                 isinstance(__SCREAMING_SNAKE_CASE     ,				torch.Tensor   ) and x.shape == column[0].shape and x.dtype == column[0].dtype
                 for x in column   ):
                 return torch.stack(__SCREAMING_SNAKE_CASE   )
         return column



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     Union[str, Any]:







         """simple docstring"""



         import torch

         if isinstance(__SCREAMING_SNAKE_CASE     ,				(str, bytes, type(__SCREAMING_SNAKE_CASE   ))   ):
             return value
         elif isinstance(__SCREAMING_SNAKE_CASE     ,				(np.character, np.ndarray)   ) and np.issubdtype(value.dtype     ,				np.character   ):
             return value.tolist()

         a__		=			{}

         if isinstance(__SCREAMING_SNAKE_CASE     ,				(np.number, np.ndarray)   ) and np.issubdtype(value.dtype     ,				np.integer   ):
             a__		=			{'dtype': torch.intaa}
         elif isinstance(__SCREAMING_SNAKE_CASE     ,				(np.number, np.ndarray)   ) and np.issubdtype(value.dtype     ,				np.floating   ):
             a__		=			{'dtype': torch.floataa}
         elif config.PIL_AVAILABLE and "PIL" in sys.modules:
             import PIL.Image

             if isinstance(__SCREAMING_SNAKE_CASE     ,				PIL.Image.Image   ):
                 a__		=			np.asarray(__SCREAMING_SNAKE_CASE   )
         return torch.tensor(__SCREAMING_SNAKE_CASE     ,				**{**default_dtype, **self.torch_tensor_kwargs}   )



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     Tuple:







         """simple docstring"""



         import torch

         # support for torch, tf, jax etc.
         if hasattr(__SCREAMING_SNAKE_CASE     ,				'__array__'   ) and not isinstance(__SCREAMING_SNAKE_CASE     ,				torch.Tensor   ):
             a__		=			data_struct.__array__()
         # support for nested types like struct of list of struct
         if isinstance(__SCREAMING_SNAKE_CASE     ,				np.ndarray   ):
             if data_struct.dtype == object:  # torch tensors cannot be instantied from an array of objects
                 return self._consolidate([self.recursive_tensorize(__SCREAMING_SNAKE_CASE   ) for substruct in data_struct]   )
         elif isinstance(__SCREAMING_SNAKE_CASE     ,				(list, tuple)   ):
             return self._consolidate([self.recursive_tensorize(__SCREAMING_SNAKE_CASE   ) for substruct in data_struct]   )
         return self._tensorize(__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     Any:







         """simple docstring"""



         return map_nested(self._recursive_tensorize     ,				__SCREAMING_SNAKE_CASE     ,				map_list=__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     Mapping:







         """simple docstring"""



         a__		=			self.numpy_arrow_extractor().extract_row(__SCREAMING_SNAKE_CASE   )
         a__		=			self.python_features_decoder.decode_row(__SCREAMING_SNAKE_CASE   )
         return self.recursive_tensorize(__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     "torch.Tensor":







         """simple docstring"""



         a__		=			self.numpy_arrow_extractor().extract_column(__SCREAMING_SNAKE_CASE   )
         a__		=			self.python_features_decoder.decode_column(__SCREAMING_SNAKE_CASE     ,				pa_table.column_names[0]   )
         a__		=			self.recursive_tensorize(__SCREAMING_SNAKE_CASE   )
         a__		=			self._consolidate(__SCREAMING_SNAKE_CASE   )
         return column




     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE   )		->     Mapping:







         """simple docstring"""



         a__		=			self.numpy_arrow_extractor().extract_batch(__SCREAMING_SNAKE_CASE   )
         a__		=			self.python_features_decoder.decode_batch(__SCREAMING_SNAKE_CASE   )
         a__		=			self.recursive_tensorize(__SCREAMING_SNAKE_CASE   )
         for column_name in batch:
             a__		=			self._consolidate(batch[column_name]   )
         return batch




"""simple docstring"""




import math







class     lowercase:



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     int:







         """simple docstring"""



         a__		=			0.0
         a__		=			0.0
         for i in range(len(__SCREAMING_SNAKE_CASE   )   ):
             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     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     list[list[int | float]]:







         """simple docstring"""



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




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

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

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

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

            # Compute the winning vector
            a__		=			self_organizing_map.get_winner(UpperCamelCase							,		UpperCamelCase     )

            # Update the winning vector
            a__		=			self_organizing_map.update(UpperCamelCase							,		UpperCamelCase							,		UpperCamelCase							,		UpperCamelCase     )

    # classify test sample
    a__		=			[0, 0, 0, 1]
    a__		=			self_organizing_map.get_winner(UpperCamelCase							,		UpperCamelCase     )

    # 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()


