



'''simple docstring'''





import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
    from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
    A__    :   List[Any]           =					True
    from torch.cuda.amp import autocast

A__    :   Optional[int]           =					logging.getLogger(__name__)





def   a_   (		_UpperCAmelCase    :      Optional[Any]=None ,_UpperCAmelCase    :      Any=None				)    ->  int:
      return field(default_factory=lambda: default ,metadata=_UpperCAmelCase				)



@dataclass
class  snake_case__						:
 A__				= field(
     metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}				)
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}  ,     )
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={'''help''': '''Whether to freeze the feature extractor layers of the model.'''}				)
 A__				= field(
     default=0.1  ,     metadata={'''help''': '''The dropout ratio for the attention probabilities.'''}				)
 A__				= field(
     default=0.1  ,     metadata={'''help''': '''The dropout ratio for activations inside the fully connected layer.'''}				)
 A__				= field(
     default=0.1  ,     metadata={
         '''help''': '''The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'''
     }  ,     )
 A__				= field(
     default=0.1  ,     metadata={'''help''': '''The dropout probabilitiy for all 1D convolutional layers in feature extractor.'''}  ,     )
 A__				= field(
     default=0.0_5  ,     metadata={
         '''help''': (
             '''Propability of each feature vector along the time axis to be chosen as the start of the vector'''
             '''span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'''
             '''vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'''
         )
     }  ,     )
 A__				= field(default=0.0  ,     metadata={'''help''': '''The LayerDrop probability.'''}				)



@dataclass
class  snake_case__						:
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}				)
 A__				= field(
     default='''train+validation'''  ,     metadata={
         '''help''': '''The name of the training data set split to use (via the datasets library). Defaults to \'train\''''
     }  ,     )
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}				)
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={'''help''': '''The number of processes to use for the preprocessing.'''}  ,     )
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of training examples to this '''
             '''value if set.'''
         )
     }  ,     )
 A__				= field(
     default=SCREAMING_SNAKE_CASE_  ,     metadata={
         '''help''': (
             '''For debugging purposes or quicker training, truncate the number of validation examples to this '''
             '''value if set.'''
         )
     }  ,     )
 A__				= list_field(
     default=[''',''', '''?''', '''.''', '''!''', '''-''', ''';''', ''':''', '''""''', '''%''', '''\'''', '''"''', '''�''']  ,     metadata={'''help''': '''A list of characters to remove from the transcripts.'''}  ,     )



@dataclass
class  snake_case__						:
 A__				= 42
 A__				= True
 A__				= None
 A__				= None
 A__				= None
 A__				= None
 def __call__(   self						:							Any      ,     __a						:							List[Dict[str, Union[List[int], torch.Tensor]]]  )      ->   Dict[str, torch.Tensor]:







       '''simple docstring'''
       # split inputs and labels since they have to be of different lenghts and need
       # different padding methods
       __snake_case :   Any													=    [{'input_values': feature['input_values']} for feature in features]
       __snake_case :   List[str]													=    [{'input_ids': feature['labels']} for feature in features]

       __snake_case :   List[str]													=    self.processor.pad(
           __a      ,     padding=self.padding      ,     max_length=self.max_length      ,     pad_to_multiple_of=self.pad_to_multiple_of      ,     return_tensors='pt'      ,     )
       __snake_case :   List[Any]													=    self.processor.pad(
           labels=__a      ,     padding=self.padding      ,     max_length=self.max_length_labels      ,     pad_to_multiple_of=self.pad_to_multiple_of_labels      ,     return_tensors='pt'      ,     )

       # replace padding with -100 to ignore loss correctly
       __snake_case :   Union[str, Any]													=    labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1  )      ,     -100  )

       __snake_case :   List[Any]													=    labels

       return batch



class  snake_case__						(    SCREAMING_SNAKE_CASE_				):
 def A_   (   self						:							Any      ,     __a						:							nn.Module      ,     __a						:							Dict[str, Union[torch.Tensor, Any]]  )      ->   torch.Tensor:







       '''simple docstring'''
       model.train()
       __snake_case :   Union[str, Any]													=    self._prepare_inputs(__a  )

       if self.use_amp:
             with autocast():
                   __snake_case :   Tuple													=    self.compute_loss(__a      ,     __a  )
       else:
             __snake_case :   str													=    self.compute_loss(__a      ,     __a  )

       if self.args.n_gpu > 1:
             if model.module.config.ctc_loss_reduction == "mean":
                   __snake_case :   Optional[int]													=    loss.mean()
             elif model.module.config.ctc_loss_reduction == "sum":
                   __snake_case :   Any													=    loss.sum() / (inputs['labels'] >= 0).sum()
             else:
                   raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'''  )

       if self.args.gradient_accumulation_steps > 1:
             __snake_case :   Tuple													=    loss / self.args.gradient_accumulation_steps

       if self.use_amp:
             self.scaler.scale(__a  ).backward()
       elif self.use_apex:
             with amp.scale_loss(__a      ,     self.optimizer  ) as scaled_loss:
                   scaled_loss.backward()
       elif self.deepspeed:
             self.deepspeed.backward(__a  )
       else:
             loss.backward()

       return loss.detach()





def   a_   (		)    ->  Optional[int]:
      # See all possible arguments in src/transformers/training_args.py
      # or by passing the --help flag to this script.
      # We now keep distinct sets of args, for a cleaner separation of concerns.

      __snake_case :   Optional[Any]													=    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
      if len(sys.argv				) == 2 and sys.argv[1].endswith('.json'				):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            __snake_case							,     __snake_case							,     __snake_case :   Optional[Any]													=    parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
      else:
            __snake_case							,     __snake_case							,     __snake_case :   Optional[int]													=    parser.parse_args_into_dataclasses()

      # Detecting last checkpoint.
      __snake_case :   Optional[Any]													=    None
      if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
            __snake_case :   List[str]													=    get_last_checkpoint(training_args.output_dir				)
            if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
                  raise ValueError(
                      f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                      'Use --overwrite_output_dir to overcome.'				)
            elif last_checkpoint is not None:
                  logger.info(
                      f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                      'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'				)

    # Setup logging
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' ,datefmt='%m/%d/%Y %H:%M:%S' ,handlers=[logging.StreamHandler(sys.stdout				)] ,)
      logger.setLevel(logging.INFO if is_main_process(training_args.local_rank				) else logging.WARN				)

      # Log on each process the small summary:
      logger.warning(
          f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
          + f'''distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}'''				)
      # Set the verbosity to info of the Transformers logger (on main process only):
      if is_main_process(training_args.local_rank				):
            transformers.utils.logging.set_verbosity_info()
      logger.info('Training/evaluation parameters %s' ,_UpperCAmelCase				)

      # Set seed before initializing model.
      set_seed(training_args.seed				)

      # Get the datasets:
      __snake_case :   Union[str, Any]													=    datasets.load_dataset(
          'common_voice' ,data_args.dataset_config_name ,split=data_args.train_split_name				)
      __snake_case :   Dict													=    datasets.load_dataset('common_voice' ,data_args.dataset_config_name ,split='test'				)

      # Create and save tokenizer
      __snake_case :   List[str]													=    f'''[{"".join(data_args.chars_to_ignore				)}]'''

      def remove_special_characters(_UpperCAmelCase    :      Union[str, Any]				):
            __snake_case :   str													=    re.sub(_UpperCAmelCase ,'' ,batch['sentence']				).lower() + ' '
            return batch

      __snake_case :   str													=    train_dataset.map(_UpperCAmelCase ,remove_columns=['sentence']				)
      __snake_case :   Tuple													=    eval_dataset.map(_UpperCAmelCase ,remove_columns=['sentence']				)

      def extract_all_chars(_UpperCAmelCase    :      Optional[Any]				):
            __snake_case :   List[Any]													=    ' '.join(batch['text']				)
            __snake_case :   Union[str, Any]													=    list(set(_UpperCAmelCase				)				)
            return {"vocab": [vocab], "all_text": [all_text]}

      __snake_case :   int													=    train_dataset.map(
          _UpperCAmelCase ,batched=_UpperCAmelCase ,batch_size=-1 ,keep_in_memory=_UpperCAmelCase ,remove_columns=train_dataset.column_names ,)
      __snake_case :   str													=    train_dataset.map(
          _UpperCAmelCase ,batched=_UpperCAmelCase ,batch_size=-1 ,keep_in_memory=_UpperCAmelCase ,remove_columns=eval_dataset.column_names ,)

      __snake_case :   int													=    list(set(vocab_train['vocab'][0]				) | set(vocab_test['vocab'][0]				)				)
      __snake_case :   Any													=    {v: k for k, v in enumerate(_UpperCAmelCase				)}
      __snake_case :   Optional[int]													=    vocab_dict[' ']
      del vocab_dict[" "]
      __snake_case :   Optional[Any]													=    len(_UpperCAmelCase				)
      __snake_case :   Union[str, Any]													=    len(_UpperCAmelCase				)

      with open('vocab.json' ,'w'				) as vocab_file:
            json.dump(_UpperCAmelCase ,_UpperCAmelCase				)

      # Load pretrained model and tokenizer
      #
      # Distributed training:
      # The .from_pretrained methods guarantee that only one local process can concurrently
      # download model & vocab.
      __snake_case :   List[Any]													=    WavaVecaCTCTokenizer(
          'vocab.json' ,unk_token='[UNK]' ,pad_token='[PAD]' ,word_delimiter_token='|' ,)
      __snake_case :   Dict													=    WavaVecaFeatureExtractor(
          feature_size=1 ,sampling_rate=1_60_00 ,padding_value=0.0 ,do_normalize=_UpperCAmelCase ,return_attention_mask=_UpperCAmelCase				)
      __snake_case :   Union[str, Any]													=    WavaVecaProcessor(feature_extractor=_UpperCAmelCase ,tokenizer=_UpperCAmelCase				)
      __snake_case :   Union[str, Any]													=    WavaVecaForCTC.from_pretrained(
          model_args.model_name_or_path ,cache_dir=model_args.cache_dir ,activation_dropout=model_args.activation_dropout ,attention_dropout=model_args.attention_dropout ,hidden_dropout=model_args.hidden_dropout ,feat_proj_dropout=model_args.feat_proj_dropout ,mask_time_prob=model_args.mask_time_prob ,gradient_checkpointing=training_args.gradient_checkpointing ,layerdrop=model_args.layerdrop ,ctc_loss_reduction='mean' ,pad_token_id=processor.tokenizer.pad_token_id ,vocab_size=len(processor.tokenizer				) ,)

      if data_args.max_train_samples is not None:
            __snake_case :   Union[str, Any]													=    min(len(_UpperCAmelCase				) ,data_args.max_train_samples				)
            __snake_case :   Dict													=    train_dataset.select(range(_UpperCAmelCase				)				)

      if data_args.max_val_samples is not None:
            __snake_case :   str													=    eval_dataset.select(range(data_args.max_val_samples				)				)

      __snake_case :   Optional[int]													=    torchaudio.transforms.Resample(4_80_00 ,1_60_00				)

      # Preprocessing the datasets.
      # We need to read the aduio files as arrays and tokenize the targets.
      def speech_file_to_array_fn(_UpperCAmelCase    :      List[str]				):
            __snake_case							,     __snake_case :   Dict													=    torchaudio.load(batch['path']				)
            __snake_case :   List[Any]													=    resampler(_UpperCAmelCase				).squeeze().numpy()
            __snake_case :   int													=    1_60_00
            __snake_case :   Union[str, Any]													=    batch['text']
            return batch

      __snake_case :   Dict													=    train_dataset.map(
          _UpperCAmelCase ,remove_columns=train_dataset.column_names ,num_proc=data_args.preprocessing_num_workers ,)
      __snake_case :   Optional[int]													=    eval_dataset.map(
          _UpperCAmelCase ,remove_columns=eval_dataset.column_names ,num_proc=data_args.preprocessing_num_workers ,)

      def prepare_dataset(_UpperCAmelCase    :      Optional[int]				):
            # check that all files have the correct sampling rate
            assert (
                len(set(batch['sampling_rate']				)				) == 1
            ), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

            __snake_case :   Union[str, Any]													=    processor(
                audio=batch['speech'] ,text=batch['target_text'] ,sampling_rate=batch['sampling_rate'][0]				)
            batch.update(_UpperCAmelCase				)
            return batch

      __snake_case :   str													=    train_dataset.map(
          _UpperCAmelCase ,remove_columns=train_dataset.column_names ,batch_size=training_args.per_device_train_batch_size ,batched=_UpperCAmelCase ,num_proc=data_args.preprocessing_num_workers ,)
      __snake_case :   int													=    eval_dataset.map(
          _UpperCAmelCase ,remove_columns=eval_dataset.column_names ,batch_size=training_args.per_device_train_batch_size ,batched=_UpperCAmelCase ,num_proc=data_args.preprocessing_num_workers ,)

      # Metric
      __snake_case :   Optional[int]													=    datasets.load_metric('wer'				)

      def compute_metrics(_UpperCAmelCase    :      Tuple				):
            __snake_case :   Union[str, Any]													=    pred.predictions
            __snake_case :   Dict													=    np.argmax(_UpperCAmelCase ,axis=-1				)

            __snake_case :   Dict													=    processor.tokenizer.pad_token_id

            __snake_case :   List[Any]													=    processor.batch_decode(_UpperCAmelCase				)
            # we do not want to group tokens when computing the metrics
            __snake_case :   Optional[Any]													=    processor.batch_decode(pred.label_ids ,group_tokens=_UpperCAmelCase				)

            __snake_case :   Tuple													=    wer_metric.compute(predictions=_UpperCAmelCase ,references=_UpperCAmelCase				)

            return {"wer": wer}

      if model_args.freeze_feature_extractor:
            model.freeze_feature_extractor()

      # Data collator
      __snake_case :   List[Any]													=    DataCollatorCTCWithPadding(processor=_UpperCAmelCase ,padding=_UpperCAmelCase				)

      # Initialize our Trainer
      __snake_case :   Optional[int]													=    CTCTrainer(
          model=_UpperCAmelCase ,data_collator=_UpperCAmelCase ,args=_UpperCAmelCase ,compute_metrics=_UpperCAmelCase ,train_dataset=train_dataset if training_args.do_train else None ,eval_dataset=eval_dataset if training_args.do_eval else None ,tokenizer=processor.feature_extractor ,)

      # Training
      if training_args.do_train:
            if last_checkpoint is not None:
                  __snake_case :   Optional[int]													=    last_checkpoint
            elif os.path.isdir(model_args.model_name_or_path				):
                  __snake_case :   Optional[int]													=    model_args.model_name_or_path
            else:
                  __snake_case :   int													=    None

            # Save the feature_extractor and the tokenizer
            if is_main_process(training_args.local_rank				):
                  processor.save_pretrained(training_args.output_dir				)

            __snake_case :   List[str]													=    trainer.train(resume_from_checkpoint=_UpperCAmelCase				)
            trainer.save_model()

            __snake_case :   Union[str, Any]													=    train_result.metrics
            __snake_case :   List[str]													=    (
                data_args.max_train_samples if data_args.max_train_samples is not None else len(_UpperCAmelCase				)
            )
            __snake_case :   int													=    min(_UpperCAmelCase ,len(_UpperCAmelCase				)				)

            trainer.log_metrics('train' ,_UpperCAmelCase				)
            trainer.save_metrics('train' ,_UpperCAmelCase				)
            trainer.save_state()

      # Evaluation
      __snake_case :   Any													=    {}
      if training_args.do_eval:
            logger.info('*** Evaluate ***'				)
            __snake_case :   List[str]													=    trainer.evaluate()
            __snake_case :   List[str]													=    data_args.max_val_samples if data_args.max_val_samples is not None else len(_UpperCAmelCase				)
            __snake_case :   List[str]													=    min(_UpperCAmelCase ,len(_UpperCAmelCase				)				)

            trainer.log_metrics('eval' ,_UpperCAmelCase				)
            trainer.save_metrics('eval' ,_UpperCAmelCase				)

      return results


if __name__ == "__main__":
    main()








'''simple docstring'''





import pickle

import numpy as np
from matplotlib import pyplot as plt



class  snake_case__						:
 def __init__(   self						:							List[Any]      ,     __a						:							str      ,     __a						:							Dict      ,     __a						:							List[Any]      ,     __a						:							str      ,     __a						:							str      ,     __a						:							List[str]=0.2      ,     __a						:							Any=0.2  )      ->   Any:







       '''simple docstring'''
       __snake_case :   Any													=    bp_numa
       __snake_case :   str													=    bp_numa
       __snake_case :   Optional[Any]													=    bp_numa
       __snake_case :   Any													=    conva_get[:2]
       __snake_case :   Dict													=    conva_get[2]
       __snake_case :   Optional[int]													=    size_pa
       __snake_case :   str													=    rate_w
       __snake_case :   Optional[Any]													=    rate_t
       __snake_case :   Optional[Any]													=    [
           np.mat(-1 * np.random.rand(self.conva[0]      ,     self.conva[0]  ) + 0.5  )
           for i in range(self.conva[1]  )
       ]
       __snake_case :   List[Any]													=    np.mat(-1 * np.random.rand(self.num_bpa      ,     self.num_bpa  ) + 0.5  )
       __snake_case :   Any													=    np.mat(-1 * np.random.rand(self.num_bpa      ,     self.num_bpa  ) + 0.5  )
       __snake_case :   Optional[int]													=    -2 * np.random.rand(self.conva[1]  ) + 1
       __snake_case :   Optional[Any]													=    -2 * np.random.rand(self.num_bpa  ) + 1
       __snake_case :   str													=    -2 * np.random.rand(self.num_bpa  ) + 1
 def A_   (   self						:							int      ,     __a						:							Dict  )      ->   Optional[Any]:







       '''simple docstring'''
       # save model dict with pickle
       __snake_case :   int													=    {
           'num_bp1': self.num_bpa,
           'num_bp2': self.num_bpa,
           'num_bp3': self.num_bpa,
           'conv1': self.conva,
           'step_conv1': self.step_conva,
           'size_pooling1': self.size_poolinga,
           'rate_weight': self.rate_weight,
           'rate_thre': self.rate_thre,
           'w_conv1': self.w_conva,
           'wkj': self.wkj,
           'vji': self.vji,
           'thre_conv1': self.thre_conva,
           'thre_bp2': self.thre_bpa,
           'thre_bp3': self.thre_bpa,
       }
       with open(__a      ,     'wb'  ) as f:
             pickle.dump(__a      ,     __a  )

       print(f'''Model saved： {save_path}'''  )
 @classmethod
 def A_   (   cls						:							List[Any]      ,     __a						:							Union[str, Any]  )      ->   int:







       '''simple docstring'''
       # read saved model
       with open(__a      ,     'rb'  ) as f:
             __snake_case :   Dict													=    pickle.load(__a  )  # noqa: S301

       __snake_case :   Tuple													=    model_dic.get('conv1'  )
       conv_get.append(model_dic.get('step_conv1'  )  )
       __snake_case :   Optional[Any]													=    model_dic.get('size_pooling1'  )
       __snake_case :   int													=    model_dic.get('num_bp1'  )
       __snake_case :   Optional[Any]													=    model_dic.get('num_bp2'  )
       __snake_case :   Optional[Any]													=    model_dic.get('num_bp3'  )
       __snake_case :   Any													=    model_dic.get('rate_weight'  )
       __snake_case :   Optional[int]													=    model_dic.get('rate_thre'  )
       # create model instance
       __snake_case :   Any													=    CNN(__a      ,     __a      ,     __a      ,     __a      ,     __a      ,     __a      ,     __a  )
       # modify model parameter
       __snake_case :   Dict													=    model_dic.get('w_conv1'  )
       __snake_case :   Any													=    model_dic.get('wkj'  )
       __snake_case :   List[str]													=    model_dic.get('vji'  )
       __snake_case :   int													=    model_dic.get('thre_conv1'  )
       __snake_case :   Optional[int]													=    model_dic.get('thre_bp2'  )
       __snake_case :   List[Any]													=    model_dic.get('thre_bp3'  )
       return conv_ins
 def A_   (   self						:							List[Any]      ,     __a						:							Tuple  )      ->   Optional[int]:







       '''simple docstring'''
       return 1 / (1 + np.exp(-1 * x  ))
 def A_   (   self						:							Any      ,     __a						:							Union[str, Any]  )      ->   List[Any]:







       '''simple docstring'''
       return round(__a      ,     3  )
 def A_   (   self						:							Optional[Any]      ,     __a						:							Tuple      ,     __a						:							List[str]      ,     __a						:							Dict      ,     __a						:							Optional[int]      ,     __a						:							List[str]  )      ->   str:







       '''simple docstring'''
       # convolution process
       __snake_case :   int													=    convs[0]
       __snake_case :   List[str]													=    convs[1]
       __snake_case :   Optional[Any]													=    np.shape(__a  )[0]
       # get the data slice of original image data, data_focus
       __snake_case :   str													=    []
       for i_focus in range(0      ,     size_data - size_conv + 1      ,     __a  ):
             for j_focus in range(0      ,     size_data - size_conv + 1      ,     __a  ):
                   __snake_case :   Any													=    data[
                       i_focus : i_focus + size_conv, j_focus : j_focus + size_conv
                   ]
                   data_focus.append(__a  )
        # calculate the feature map of every single kernel, and saved as list of matrix
       __snake_case :   Optional[int]													=    []
       __snake_case :   Dict													=    int((size_data - size_conv) / conv_step + 1  )
       for i_map in range(__a  ):
             __snake_case :   Optional[int]													=    []
             for i_focus in range(len(__a  )  ):
                   __snake_case :   List[Any]													=    (
                       np.sum(np.multiply(data_focus[i_focus]      ,     w_convs[i_map]  )  )
                       - thre_convs[i_map]
                   )
                   featuremap.append(self.sig(__a  )  )
             __snake_case :   List[Any]													=    np.asmatrix(__a  ).reshape(
                 __a      ,     __a  )
             data_featuremap.append(__a  )

       # expanding the data slice to One dimenssion
       __snake_case :   Union[str, Any]													=    []
       for each_focus in data_focus:
             focusa_list.extend(self.Expand_Mat(__a  )  )
       __snake_case :   List[Any]													=    np.asarray(__a  )
       return focus_list, data_featuremap
 def A_   (   self						:							Any      ,     __a						:							int      ,     __a						:							Tuple      ,     __a						:							List[Any]="average_pool"  )      ->   Dict:







       '''simple docstring'''
       # pooling process
       __snake_case :   List[str]													=    len(featuremaps[0]  )
       __snake_case :   Tuple													=    int(size_map / size_pooling  )
       __snake_case :   int													=    []
       for i_map in range(len(__a  )  ):
             __snake_case :   str													=    featuremaps[i_map]
             __snake_case :   Optional[Any]													=    []
             for i_focus in range(0      ,     __a      ,     __a  ):
                   for j_focus in range(0      ,     __a      ,     __a  ):
                         __snake_case :   Dict													=    feature_map[
                             i_focus : i_focus + size_pooling,
                             j_focus : j_focus + size_pooling,
                         ]
                         if pooling_type == "average_pool":
                               # average pooling
                               map_pooled.append(np.average(__a  )  )
                         elif pooling_type == "max_pooling":
                               # max pooling
                               map_pooled.append(np.max(__a  )  )
             __snake_case :   List[str]													=    np.asmatrix(__a  ).reshape(__a      ,     __a  )
             featuremap_pooled.append(__a  )
       return featuremap_pooled
 def A_   (   self						:							List[str]      ,     __a						:							Union[str, Any]  )      ->   int:







       '''simple docstring'''
       # expanding three dimension data to one dimension list
       __snake_case :   Tuple													=    []
       for i in range(len(__a  )  ):
             __snake_case :   Optional[int]													=    np.shape(data[i]  )
             __snake_case :   List[str]													=    data[i].reshape(1      ,     shapes[0] * shapes[1]  )
             __snake_case :   List[Any]													=    data_listed.getA().tolist()[0]
             data_expanded.extend(__a  )
       __snake_case :   Optional[int]													=    np.asarray(__a  )
       return data_expanded
 def A_   (   self						:							Union[str, Any]      ,     __a						:							int  )      ->   Any:







       '''simple docstring'''
       # expanding matrix to one dimension list
       __snake_case :   int													=    np.asarray(__a  )
       __snake_case :   str													=    np.shape(__a  )
       __snake_case :   Any													=    data_mat.reshape(1      ,     shapes[0] * shapes[1]  )
       return data_expanded
 def A_   (   self						:							List[Any]      ,     __a						:							str      ,     __a						:							Optional[int]      ,     __a						:							List[str]      ,     __a						:							int      ,     __a						:							List[str]  )      ->   Dict:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    []
       __snake_case :   Tuple													=    0
       for i_map in range(__a  ):
             __snake_case :   Union[str, Any]													=    np.ones((size_map, size_map)  )
             for i in range(0      ,     __a      ,     __a  ):
                   for j in range(0      ,     __a      ,     __a  ):
                         __snake_case :   Any													=    pd_pool[
                             i_pool
                         ]
                         __snake_case :   List[Any]													=    i_pool + 1
             __snake_case :   List[Any]													=    np.multiply(
                 __a      ,     np.multiply(out_map[i_map]      ,     (1 - out_map[i_map])  )  )
             pd_all.append(__a  )
       return pd_all
 def A_   (   self						:							Tuple      ,     __a						:							List[str]      ,     __a						:							Optional[int]      ,     __a						:							Union[str, Any]      ,     __a						:							Dict      ,     __a						:							Tuple      ,     __a						:							Optional[int]=bool  )      ->   List[Any]:







       '''simple docstring'''
       # model traning
       print('----------------------Start Training-------------------------'  )
       print((' - - Shape: Train_Data  ', np.shape(__a  ))  )
       print((' - - Shape: Teach_Data  ', np.shape(__a  ))  )
       __snake_case :   str													=    0
       __snake_case :   List[str]													=    []
       __snake_case :   List[Any]													=    10000
       while rp < n_repeat and mse >= error_accuracy:
             __snake_case :   int													=    0
             print(f'''-------------Learning Time {rp}--------------'''  )
             for p in range(len(__a  )  ):
                   # print('------------Learning Image: %d--------------'%p)
                   __snake_case :   List[Any]													=    np.asmatrix(datas_train[p]  )
                   __snake_case :   Optional[Any]													=    np.asarray(datas_teach[p]  )
                   __snake_case							,     __snake_case :   List[Any]													=    self.convolute(
                       __a      ,     self.conva      ,     self.w_conva      ,     self.thre_conva      ,     conv_step=self.step_conva      ,     )
                   __snake_case :   Tuple													=    self.pooling(__a      ,     self.size_poolinga  )
                   __snake_case :   Dict													=    np.shape(__a  )
                   __snake_case :   Tuple													=    self._expand(__a  )
                   __snake_case :   str													=    data_bp_input

                   __snake_case :   List[Any]													=    np.dot(__a      ,     self.vji.T  ) - self.thre_bpa
                   __snake_case :   Any													=    self.sig(__a  )
                   __snake_case :   Tuple													=    np.dot(__a      ,     self.wkj.T  ) - self.thre_bpa
                   __snake_case :   Optional[Any]													=    self.sig(__a  )

                   # --------------Model Leaning ------------------------
                   # calculate error and gradient---------------
                   __snake_case :   Tuple													=    np.multiply(
                       (data_teach - bp_outa)      ,     np.multiply(__a      ,     (1 - bp_outa)  )  )
                   __snake_case :   Tuple													=    np.multiply(
                       np.dot(__a      ,     self.wkj  )      ,     np.multiply(__a      ,     (1 - bp_outa)  )  )
                   __snake_case :   Union[str, Any]													=    np.dot(__a      ,     self.vji  )

                   __snake_case :   Optional[int]													=    pd_i_all / (self.size_poolinga * self.size_poolinga)
                   __snake_case :   Tuple													=    pd_conva_pooled.T.getA().tolist()
                   __snake_case :   Optional[Any]													=    self._calculate_gradient_from_pool(
                       __a      ,     __a      ,     shape_featuremapa[0]      ,     shape_featuremapa[1]      ,     self.size_poolinga      ,     )
                   # weight and threshold learning process---------
                   # convolution layer
                   for k_conv in range(self.conva[1]  ):
                         __snake_case :   int													=    self._expand_mat(pd_conva_all[k_conv]  )
                         __snake_case :   Optional[int]													=    self.rate_weight * np.dot(__a      ,     __a  )

                         __snake_case :   List[Any]													=    self.w_conva[k_conv] + delta_w.reshape(
                             (self.conva[0], self.conva[0])  )

                         __snake_case :   Optional[Any]													=    (
                             self.thre_conva[k_conv]
                             - np.sum(pd_conva_all[k_conv]  ) * self.rate_thre
                         )
                   # all connected layer
                   __snake_case :   Tuple													=    self.wkj + pd_k_all.T * bp_outa * self.rate_weight
                   __snake_case :   Optional[Any]													=    self.vji + pd_j_all.T * bp_outa * self.rate_weight
                   __snake_case :   str													=    self.thre_bpa - pd_k_all * self.rate_thre
                   __snake_case :   Optional[int]													=    self.thre_bpa - pd_j_all * self.rate_thre
                   # calculate the sum error of all single image
                   __snake_case :   Any													=    np.sum(abs(data_teach - bp_outa  )  )
                   error_count += errors
                   # print('   ----Teach      ',data_teach)
                   # print('   ----BP_output  ',bp_out3)
             __snake_case :   Tuple													=    rp + 1
             __snake_case :   Tuple													=    error_count / patterns
             all_mse.append(__a  )

       def draw_error():
             __snake_case :   Union[str, Any]													=    [error_accuracy for i in range(int(n_repeat * 1.2  )  )]
             plt.plot(__a      ,     '+-'  )
             plt.plot(__a      ,     'r--'  )
             plt.xlabel('Learning Times'  )
             plt.ylabel('All_mse'  )
             plt.grid(__a      ,     alpha=0.5  )
             plt.show()

       print('------------------Training Complished---------------------'  )
       print((' - - Training epoch: ', rp, f'''     - - Mse: {mse:.6f}''')  )
       if draw_e:
             draw_error()
       return mse
 def A_   (   self						:							Tuple      ,     __a						:							Union[str, Any]  )      ->   List[Any]:







       '''simple docstring'''
       # model predict
       __snake_case :   str													=    []
       print('-------------------Start Testing-------------------------'  )
       print((' - - Shape: Test_Data  ', np.shape(__a  ))  )
       for p in range(len(__a  )  ):
             __snake_case :   int													=    np.asmatrix(datas_test[p]  )
             __snake_case							,     __snake_case :   str													=    self.convolute(
                 __a      ,     self.conva      ,     self.w_conva      ,     self.thre_conva      ,     conv_step=self.step_conva      ,     )
             __snake_case :   List[str]													=    self.pooling(__a      ,     self.size_poolinga  )
             __snake_case :   List[Any]													=    self._expand(__a  )

             __snake_case :   Optional[Any]													=    data_bp_input
             __snake_case :   Optional[Any]													=    bp_outa * self.vji.T - self.thre_bpa
             __snake_case :   Any													=    self.sig(__a  )
             __snake_case :   Any													=    bp_outa * self.wkj.T - self.thre_bpa
             __snake_case :   str													=    self.sig(__a  )
             produce_out.extend(bp_outa.getA().tolist()  )
       __snake_case :   List[Any]													=    [list(map(self.do_round      ,     __a  )  ) for each in produce_out]
       return np.asarray(__a  )





 def A_   (   self						:							Optional[Any]      ,     __a						:							Optional[int]  )      ->   Tuple:







       '''simple docstring'''
       # return the data of image after convoluting process so we can check it out
       __snake_case :   int													=    np.asmatrix(__a  )
       __snake_case							,     __snake_case :   int													=    self.convolute(
           __a      ,     self.conva      ,     self.w_conva      ,     self.thre_conva      ,     conv_step=self.step_conva      ,     )
       __snake_case :   Dict													=    self.pooling(__a      ,     self.size_poolinga  )

       return data_conveda, data_pooleda


if __name__ == "__main__":
    pass



