




import pickle

import numpy as np
from matplotlib import pyplot as plt





class     SCREAMING_SNAKE_CASE__		:
     def __init__(						self	:		Optional[Any]       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		Union[str, Any]       ,						__lowerCamelCase	:		Any       ,						__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		List[Any]=0.2       ,						__lowerCamelCase	:		Any=0.2						):



       """simple docstring"""
       lowerCAmelCase__										=      bp_numa
       lowerCAmelCase__										=      bp_numa
       lowerCAmelCase__										=      bp_numa
       lowerCAmelCase__										=      conva_get[:2]
       lowerCAmelCase__										=      conva_get[2]
       lowerCAmelCase__										=      size_pa
       lowerCAmelCase__										=      rate_w
       lowerCAmelCase__										=      rate_t
       lowerCAmelCase__										=      [
           np.mat(-1 * np.random.rand(self.conva[0]       ,						self.conva[0]						) + 0.5						)
           for i in range(self.conva[1]						)
       ]
       lowerCAmelCase__										=      np.mat(-1 * np.random.rand(self.num_bpa       ,						self.num_bpa						) + 0.5						)
       lowerCAmelCase__										=      np.mat(-1 * np.random.rand(self.num_bpa       ,						self.num_bpa						) + 0.5						)
       lowerCAmelCase__										=      -2 * np.random.rand(self.conva[1]						) + 1
       lowerCAmelCase__										=      -2 * np.random.rand(self.num_bpa						) + 1
       lowerCAmelCase__										=      -2 * np.random.rand(self.num_bpa						) + 1
     def        A__      (						self	:		str       ,						__lowerCamelCase	:		Optional[Any]						):



       """simple docstring"""
       # save model dict with pickle
       lowerCAmelCase__										=      {
           '''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(__lowerCamelCase       ,						'''wb'''						) as f:
         pickle.dump(__lowerCamelCase       ,						__lowerCamelCase						)

       print(F"""Model saved： {save_path}"""						)
     @classmethod
     def        A__      (						cls	:		Dict       ,						__lowerCamelCase	:		str						):



       """simple docstring"""
       # read saved model
       with open(__lowerCamelCase       ,						'''rb'''						) as f:
         lowerCAmelCase__										=      pickle.load(__lowerCamelCase						)  # noqa: S301

       lowerCAmelCase__										=      model_dic.get('''conv1'''						)
       conv_get.append(model_dic.get('''step_conv1'''						)						)
       lowerCAmelCase__										=      model_dic.get('''size_pooling1'''						)
       lowerCAmelCase__										=      model_dic.get('''num_bp1'''						)
       lowerCAmelCase__										=      model_dic.get('''num_bp2'''						)
       lowerCAmelCase__										=      model_dic.get('''num_bp3'''						)
       lowerCAmelCase__										=      model_dic.get('''rate_weight'''						)
       lowerCAmelCase__										=      model_dic.get('''rate_thre'''						)
       # create model instance
       lowerCAmelCase__										=      CNN(__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase       ,						__lowerCamelCase						)
       # modify model parameter
       lowerCAmelCase__										=      model_dic.get('''w_conv1'''						)
       lowerCAmelCase__										=      model_dic.get('''wkj'''						)
       lowerCAmelCase__										=      model_dic.get('''vji'''						)
       lowerCAmelCase__										=      model_dic.get('''thre_conv1'''						)
       lowerCAmelCase__										=      model_dic.get('''thre_bp2'''						)
       lowerCAmelCase__										=      model_dic.get('''thre_bp3'''						)
       return conv_ins
     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		List[Any]						):



       """simple docstring"""
       return 1 / (1 + np.exp(-1 * x						))
     def        A__      (						self	:		Optional[Any]       ,						__lowerCamelCase	:		Any						):



       """simple docstring"""
       return round(__lowerCamelCase       ,						3						)
     def        A__      (						self	:		int       ,						__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		str       ,						__lowerCamelCase	:		List[Any]       ,						__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		List[Any]						):



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

       # expanding the data slice to One dimenssion
       lowerCAmelCase__										=      []
       for each_focus in data_focus:
         focusa_list.extend(self.Expand_Mat(__lowerCamelCase						)						)
       lowerCAmelCase__										=      np.asarray(__lowerCamelCase						)
       return focus_list, data_featuremap
     def        A__      (						self	:		Union[str, Any]       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		Dict="average_pool"						):



       """simple docstring"""
       # pooling process
       lowerCAmelCase__										=      len(featuremaps[0]						)
       lowerCAmelCase__										=      int(size_map / size_pooling						)
       lowerCAmelCase__										=      []
       for i_map in range(len(__lowerCamelCase						)						):
         lowerCAmelCase__										=      featuremaps[i_map]
         lowerCAmelCase__										=      []
         for i_focus in range(0       ,						__lowerCamelCase       ,						__lowerCamelCase						):
           for j_focus in range(0       ,						__lowerCamelCase       ,						__lowerCamelCase						):
             lowerCAmelCase__										=      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(__lowerCamelCase						)						)
             elif pooling_type == "max_pooling":
               # max pooling
               map_pooled.append(np.max(__lowerCamelCase						)						)
         lowerCAmelCase__										=      np.asmatrix(__lowerCamelCase						).reshape(__lowerCamelCase       ,						__lowerCamelCase						)
         featuremap_pooled.append(__lowerCamelCase						)
       return featuremap_pooled
     def        A__      (						self	:		int       ,						__lowerCamelCase	:		Union[str, Any]						):



       """simple docstring"""
       # expanding three dimension data to one dimension list
       lowerCAmelCase__										=      []
       for i in range(len(__lowerCamelCase						)						):
         lowerCAmelCase__										=      np.shape(data[i]						)
         lowerCAmelCase__										=      data[i].reshape(1       ,						shapes[0] * shapes[1]						)
         lowerCAmelCase__										=      data_listed.getA().tolist()[0]
         data_expanded.extend(__lowerCamelCase						)
       lowerCAmelCase__										=      np.asarray(__lowerCamelCase						)
       return data_expanded
     def        A__      (						self	:		List[Any]       ,						__lowerCamelCase	:		List[Any]						):



       """simple docstring"""
       # expanding matrix to one dimension list
       lowerCAmelCase__										=      np.asarray(__lowerCamelCase						)
       lowerCAmelCase__										=      np.shape(__lowerCamelCase						)
       lowerCAmelCase__										=      data_mat.reshape(1       ,						shapes[0] * shapes[1]						)
       return data_expanded
     def        A__      (						self	:		Tuple       ,						__lowerCamelCase	:		Optional[Any]       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		List[str]       ,						__lowerCamelCase	:		Optional[int]       ,						__lowerCamelCase	:		int						):



       """simple docstring"""
       lowerCAmelCase__										=      []
       lowerCAmelCase__										=      0
       for i_map in range(__lowerCamelCase						):
         lowerCAmelCase__										=      np.ones((size_map, size_map)						)
         for i in range(0       ,						__lowerCamelCase       ,						__lowerCamelCase						):
           for j in range(0       ,						__lowerCamelCase       ,						__lowerCamelCase						):
             lowerCAmelCase__										=      pd_pool[
                 i_pool
             ]
             lowerCAmelCase__										=      i_pool + 1
         lowerCAmelCase__										=      np.multiply(
             __lowerCamelCase       ,						np.multiply(out_map[i_map]       ,						(1 - out_map[i_map])						)						)
         pd_all.append(__lowerCamelCase						)
       return pd_all
     def        A__      (						self	:		List[Any]       ,						__lowerCamelCase	:		Optional[int]       ,						__lowerCamelCase	:		Optional[int]       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		Dict       ,						__lowerCamelCase	:		Any       ,						__lowerCamelCase	:		str=bool						):



       """simple docstring"""
       # model traning
       print('''----------------------Start Training-------------------------'''						)
       print((''' - - Shape: Train_Data  ''', np.shape(__lowerCamelCase						))						)
       print((''' - - Shape: Teach_Data  ''', np.shape(__lowerCamelCase						))						)
       lowerCAmelCase__										=      0
       lowerCAmelCase__										=      []
       lowerCAmelCase__										=      1_00_00
       while rp < n_repeat and mse >= error_accuracy:
         lowerCAmelCase__										=      0
         print(F"""-------------Learning Time {rp}--------------"""						)
         for p in range(len(__lowerCamelCase						)						):
           # print('------------Learning Image: %d--------------'%p)
           lowerCAmelCase__										=      np.asmatrix(datas_train[p]						)
           lowerCAmelCase__										=      np.asarray(datas_teach[p]						)
           lowerCAmelCase__				,      lowerCAmelCase__										=      self.convolute(
               __lowerCamelCase       ,						self.conva       ,						self.w_conva       ,						self.thre_conva       ,						conv_step=self.step_conva       ,						)
           lowerCAmelCase__										=      self.pooling(__lowerCamelCase       ,						self.size_poolinga						)
           lowerCAmelCase__										=      np.shape(__lowerCamelCase						)
           lowerCAmelCase__										=      self._expand(__lowerCamelCase						)
           lowerCAmelCase__										=      data_bp_input

           lowerCAmelCase__										=      np.dot(__lowerCamelCase       ,						self.vji.T						) - self.thre_bpa
           lowerCAmelCase__										=      self.sig(__lowerCamelCase						)
           lowerCAmelCase__										=      np.dot(__lowerCamelCase       ,						self.wkj.T						) - self.thre_bpa
           lowerCAmelCase__										=      self.sig(__lowerCamelCase						)

           # --------------Model Leaning ------------------------
           # calculate error and gradient---------------
           lowerCAmelCase__										=      np.multiply(
               (data_teach - bp_outa)       ,						np.multiply(__lowerCamelCase       ,						(1 - bp_outa)						)						)
           lowerCAmelCase__										=      np.multiply(
               np.dot(__lowerCamelCase       ,						self.wkj						)       ,						np.multiply(__lowerCamelCase       ,						(1 - bp_outa)						)						)
           lowerCAmelCase__										=      np.dot(__lowerCamelCase       ,						self.vji						)

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

             lowerCAmelCase__										=      self.w_conva[k_conv] + delta_w.reshape(
                 (self.conva[0], self.conva[0])						)

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

       def draw_error():
         lowerCAmelCase__										=      [error_accuracy for i in range(int(n_repeat * 1.2						)						)]
         plt.plot(__lowerCamelCase       ,						'''+-'''						)
         plt.plot(__lowerCamelCase       ,						'''r--'''						)
         plt.xlabel('''Learning Times'''						)
         plt.ylabel('''All_mse'''						)
         plt.grid(__lowerCamelCase       ,						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	:		Union[str, Any]       ,						__lowerCamelCase	:		List[str]						):



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

         lowerCAmelCase__										=      data_bp_input
         lowerCAmelCase__										=      bp_outa * self.vji.T - self.thre_bpa
         lowerCAmelCase__										=      self.sig(__lowerCamelCase						)
         lowerCAmelCase__										=      bp_outa * self.wkj.T - self.thre_bpa
         lowerCAmelCase__										=      self.sig(__lowerCamelCase						)
         produce_out.extend(bp_outa.getA().tolist()						)
       lowerCAmelCase__										=      [list(map(self.do_round       ,						__lowerCamelCase						)						) for each in produce_out]
       return np.asarray(__lowerCamelCase						)



     def        A__      (						self	:		List[str]       ,						__lowerCamelCase	:		Optional[Any]						):



       """simple docstring"""
       # return the data of image after convoluting process so we can check it out
       lowerCAmelCase__										=      np.asmatrix(__lowerCamelCase						)
       lowerCAmelCase__				,      lowerCAmelCase__										=      self.convolute(
           __lowerCamelCase       ,						self.conva       ,						self.w_conva       ,						self.thre_conva       ,						conv_step=self.step_conva       ,						)
       lowerCAmelCase__										=      self.pooling(__lowerCamelCase       ,						self.size_poolinga						)

       return data_conveda, data_pooleda


if __name__ == "__main__":
      pass







from scipy.stats import pearsonr

import datasets


__magic_name__  :  Union[str, Any]					=       """
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
"""


__magic_name__  :  Tuple					=       """
Args:
    predictions (`list` of `int`): Predicted class labels, as returned by a model.
    references (`list` of `int`): Ground truth labels.
    return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.

Returns:
    pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
    p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.

Examples:

    Example 1-A simple example using only predictions and references.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
        >>> print(round(results['pearsonr'], 2))
        -0.74

    Example 2-The same as Example 1, but that also returns the `p-value`.
        >>> pearsonr_metric = datasets.load_metric(\"pearsonr\")
        >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
        >>> print(sorted(list(results.keys())))
        ['p-value', 'pearsonr']
        >>> print(round(results['pearsonr'], 2))
        -0.74
        >>> print(round(results['p-value'], 2))
        0.15
"""


__magic_name__  :  int					=       """
@article{2020SciPy-NMeth,
author  = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
      Haberland, Matt and Reddy, Tyler and Cournapeau, David and
      Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
      Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
      Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
      Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
      Kern, Robert and Larson, Eric and Carey, C J and
      Polat, Ilhan and Feng, Yu and Moore, Eric W. and
      {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
      Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
      Harris, Charles R. and Archibald, Anne M. and
      Ribeiro, Antonio H. and Pedregosa, Fabian and
      {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title   = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
      Computing in Python}},
journal = {Nature Methods},
year    = {2020},
volume  = {17},
pages   = {261--272},
adsurl  = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
"""





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION    ,					_KWARGS_DESCRIPTION			)
class     SCREAMING_SNAKE_CASE__		(datasets.Metric			):
     def        A__      (						self	:		List[str]						):



       """simple docstring"""
       return datasets.MetricInfo(
           description=_DESCRIPTION       ,						citation=_CITATION       ,						inputs_description=_KWARGS_DESCRIPTION       ,						features=datasets.Features(
               {
                   '''predictions''': datasets.Value('''float'''						),
                   '''references''': datasets.Value('''float'''						),
               }						)       ,						reference_urls=['''https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html''']       ,						)



     def        A__      (						self	:		Any       ,						__lowerCamelCase	:		int       ,						__lowerCamelCase	:		Tuple       ,						__lowerCamelCase	:		Dict=False						):



       """simple docstring"""
       if return_pvalue:
         lowerCAmelCase__										=      pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)
         return {"pearsonr": results[0], "p-value": results[1]}
       else:
         return {"pearsonr": float(pearsonr(__lowerCamelCase       ,						__lowerCamelCase						)[0]						)}

