
import pickle

import numpy as np
from matplotlib import pyplot as plt





class     __UpperCamelCase :






     """simple docstring"""







     def __init__(				self							:							Optional[int]     ,						_A							:							Dict     ,						_A							:							List[Any]     ,						_A							:							Optional[Any]     ,						_A							:							Optional[int]     ,						_A							:							Union[str, Any]     ,						_A							:							Optional[int]=0.2     ,						_A							:							Tuple=0.2 ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		bp_numa
       __SCREAMING_SNAKE_CASE      :	Tuple					=		bp_numa
       __SCREAMING_SNAKE_CASE      :	int					=		bp_numa
       __SCREAMING_SNAKE_CASE      :	Tuple					=		conva_get[:2]
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		conva_get[2]
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		size_pa
       __SCREAMING_SNAKE_CASE      :	Any					=		rate_w
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		rate_t
       __SCREAMING_SNAKE_CASE      :	Dict					=		[
           np.mat(-1 * np.random.rand(self.conva[0]     ,						self.conva[0] ) + 0.5 )
           for i in range(self.conva[1] )
       ]
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		np.mat(-1 * np.random.rand(self.num_bpa     ,						self.num_bpa ) + 0.5 )
       __SCREAMING_SNAKE_CASE      :	Dict					=		np.mat(-1 * np.random.rand(self.num_bpa     ,						self.num_bpa ) + 0.5 )
       __SCREAMING_SNAKE_CASE      :	Dict					=		-2 * np.random.rand(self.conva[1] ) + 1
       __SCREAMING_SNAKE_CASE      :	int					=		-2 * np.random.rand(self.num_bpa ) + 1
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		-2 * np.random.rand(self.num_bpa ) + 1



     def  UpperCAmelCase__							(				self							:							Optional[int]     ,						_A							:							int ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		{
           '''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  UpperCAmelCase__							(				cls							:							List[str]     ,						_A							:							int ):







       """simple docstring"""




       with open(_A     ,						'''rb''' ) as f:
         __SCREAMING_SNAKE_CASE      :	Tuple					=		pickle.load(_A )  # noqa: S301

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



     def  UpperCAmelCase__							(				self							:							List[Any]     ,						_A							:							List[Any] ):







       """simple docstring"""




       return 1 / (1 + np.exp(-1 * x ))



     def  UpperCAmelCase__							(				self							:							str     ,						_A							:							List[str] ):







       """simple docstring"""




       return round(_A     ,						3 )



     def  UpperCAmelCase__							(				self							:							int     ,						_A							:							int     ,						_A							:							str     ,						_A							:							List[Any]     ,						_A							:							Tuple     ,						_A							:							List[Any] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		convs[0]
       __SCREAMING_SNAKE_CASE      :	Any					=		convs[1]
       __SCREAMING_SNAKE_CASE      :	int					=		np.shape(_A )[0]
       # get the data slice of original image data, data_focus
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		[]
       for i_focus in range(0     ,						size_data - size_conv + 1     ,						_A ):
         for j_focus in range(0     ,						size_data - size_conv + 1     ,						_A ):
           __SCREAMING_SNAKE_CASE      :	Optional[int]					=		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
       __SCREAMING_SNAKE_CASE      :	Dict					=		[]
       __SCREAMING_SNAKE_CASE      :	List[str]					=		int((size_data - size_conv) / conv_step + 1 )
       for i_map in range(_A ):
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		[]
         for i_focus in range(len(_A ) ):
           __SCREAMING_SNAKE_CASE      :	int					=		(
               np.sum(np.multiply(data_focus[i_focus]     ,						w_convs[i_map] ) )
               - thre_convs[i_map]
           )
           featuremap.append(self.sig(_A ) )
         __SCREAMING_SNAKE_CASE      :	str					=		np.asmatrix(_A ).reshape(
             _A     ,						_A )
         data_featuremap.append(_A )

       # expanding the data slice to One dimenssion
       __SCREAMING_SNAKE_CASE      :	int					=		[]
       for each_focus in data_focus:
         focusa_list.extend(self.Expand_Mat(_A ) )
       __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		np.asarray(_A )
       return focus_list, data_featuremap



     def  UpperCAmelCase__							(				self							:							List[str]     ,						_A							:							str     ,						_A							:							Union[str, Any]     ,						_A							:							Optional[int]="average_pool" ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Any					=		len(featuremaps[0] )
       __SCREAMING_SNAKE_CASE      :	List[Any]					=		int(size_map / size_pooling )
       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		[]
       for i_map in range(len(_A ) ):
         __SCREAMING_SNAKE_CASE      :	Tuple					=		featuremaps[i_map]
         __SCREAMING_SNAKE_CASE      :	Dict					=		[]
         for i_focus in range(0     ,						_A     ,						_A ):
           for j_focus in range(0     ,						_A     ,						_A ):
             __SCREAMING_SNAKE_CASE      :	Tuple					=		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 ) )
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		np.asmatrix(_A ).reshape(_A     ,						_A )
         featuremap_pooled.append(_A )
       return featuremap_pooled



     def  UpperCAmelCase__							(				self							:							Dict     ,						_A							:							str ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Tuple					=		[]
       for i in range(len(_A ) ):
         __SCREAMING_SNAKE_CASE      :	Optional[int]					=		np.shape(data[i] )
         __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		data[i].reshape(1     ,						shapes[0] * shapes[1] )
         __SCREAMING_SNAKE_CASE      :	List[Any]					=		data_listed.getA().tolist()[0]
         data_expanded.extend(_A )
       __SCREAMING_SNAKE_CASE      :	Tuple					=		np.asarray(_A )
       return data_expanded



     def  UpperCAmelCase__							(				self							:							List[Any]     ,						_A							:							Dict ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Any					=		np.asarray(_A )
       __SCREAMING_SNAKE_CASE      :	List[str]					=		np.shape(_A )
       __SCREAMING_SNAKE_CASE      :	Optional[int]					=		data_mat.reshape(1     ,						shapes[0] * shapes[1] )
       return data_expanded



     def  UpperCAmelCase__							(				self							:							Dict     ,						_A							:							Any     ,						_A							:							Optional[Any]     ,						_A							:							List[Any]     ,						_A							:							Tuple     ,						_A							:							Optional[Any] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	int					=		[]
       __SCREAMING_SNAKE_CASE      :	List[str]					=		0
       for i_map in range(_A ):
         __SCREAMING_SNAKE_CASE      :	Dict					=		np.ones((size_map, size_map) )
         for i in range(0     ,						_A     ,						_A ):
           for j in range(0     ,						_A     ,						_A ):
             __SCREAMING_SNAKE_CASE      :	Union[str, Any]					=		pd_pool[
                 i_pool
             ]
             __SCREAMING_SNAKE_CASE      :	List[str]					=		i_pool + 1
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		np.multiply(
             _A     ,						np.multiply(out_map[i_map]     ,						(1 - out_map[i_map]) ) )
         pd_all.append(_A )
       return pd_all



     def  UpperCAmelCase__							(				self							:							List[str]     ,						_A							:							List[Any]     ,						_A							:							str     ,						_A							:							Any     ,						_A							:							Union[str, Any]     ,						_A							:							List[Any]     ,						_A							:							Any=bool ):







       """simple docstring"""




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

           __SCREAMING_SNAKE_CASE      :	Tuple					=		np.dot(_A     ,						self.vji.T ) - self.thre_bpa
           __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		self.sig(_A )
           __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		np.dot(_A     ,						self.wkj.T ) - self.thre_bpa
           __SCREAMING_SNAKE_CASE      :	Dict					=		self.sig(_A )

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

           __SCREAMING_SNAKE_CASE      :	List[Any]					=		pd_i_all / (self.size_poolinga * self.size_poolinga)
           __SCREAMING_SNAKE_CASE      :	Dict					=		pd_conva_pooled.T.getA().tolist()
           __SCREAMING_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] ):
             __SCREAMING_SNAKE_CASE      :	str					=		self._expand_mat(pd_conva_all[k_conv] )
             __SCREAMING_SNAKE_CASE      :	Any					=		self.rate_weight * np.dot(_A     ,						_A )

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

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

       def draw_error():
         __SCREAMING_SNAKE_CASE      :	Optional[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  UpperCAmelCase__							(				self							:							Tuple     ,						_A							:							Dict ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		[]
       print('''-------------------Start Testing-------------------------''' )
       print((''' - - Shape: Test_Data  ''', np.shape(_A )) )
       for p in range(len(_A ) ):
         __SCREAMING_SNAKE_CASE      :	int					=		np.asmatrix(datas_test[p] )
         __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Optional[Any]					=		self.convolute(
             _A     ,						self.conva     ,						self.w_conva     ,						self.thre_conva     ,						conv_step=self.step_conva     ,						)
         __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		self.pooling(_A     ,						self.size_poolinga )
         __SCREAMING_SNAKE_CASE      :	Dict					=		self._expand(_A )

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




     def  UpperCAmelCase__							(				self							:							Union[str, Any]     ,						_A							:							Optional[int] ):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE      :	Tuple					=		np.asmatrix(_A )
       __SCREAMING_SNAKE_CASE,		__SCREAMING_SNAKE_CASE      :	Dict					=		self.convolute(
           _A     ,						self.conva     ,						self.w_conva     ,						self.thre_conva     ,						conv_step=self.step_conva     ,						)
       __SCREAMING_SNAKE_CASE      :	Optional[Any]					=		self.pooling(_A     ,						self.size_poolinga )

       return data_conveda, data_pooleda


if __name__ == "__main__":
   pass



"""simple docstring"""
import requests




def 					a__						(						lowerCAmelCase			,	lowerCAmelCase    )	-> None:
      UpperCAmelCase__			:							List[str]							=    {"""Content-Type""": """application/json"""}
      UpperCAmelCase__			:							List[str]							=    requests.post(lowerCAmelCase			,	json={"""text""": message_body}			,	headers=lowerCAmelCase    )
      if response.status_code != 2_00:
            UpperCAmelCase__			:							str							=    (
                """Request to slack returned an error """
                F"""{response.status_code}, the response is:\n{response.text}"""
            )
            raise ValueError(lowerCAmelCase    )


if __name__ == "__main__":
    # Set the slack url to the one provided by Slack when you create the webhook at
    # https://my.slack.com/services/new/incoming-webhook/
    send_slack_message("""<YOUR MESSAGE BODY>""", """<SLACK CHANNEL URL>""")

