



'''simple docstring'''


import numpy as np
from matplotlib import pyplot as plt






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







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







class 						UpperCAmelCase						:


 '''simple docstring'''




 def __init__( self				,	lowerCAmelCase_				,	lowerCAmelCase_=None				,	lowerCAmelCase_=None				,	lowerCAmelCase_=False)			->   List[Any]:



      """simple docstring"""







      a_									=units
      a_									=None
      a_									=None
      a_									=activation
      if learning_rate is None:
           a_									=0.3
      a_									=learning_rate
      a_									=is_input_layer




 def    lowercase_	( self				,	lowerCAmelCase_)			->   int:



      """simple docstring"""







      a_									=np.asmatrix(np.random.normal(0				,	0.5				,	(self.units, back_units)))
      a_									=np.asmatrix(np.random.normal(0				,	0.5				,	self.units)).T
      if self.activation is None:
           a_									=sigmoid




 def    lowercase_	( self)			->   str:



      """simple docstring"""







      if self.activation == sigmoid:
           a_									=np.dot(self.output				,	(1 - self.output).T)
           a_									=np.diag(np.diag(lowerCAmelCase_))
      else:
           a_									=1
      return gradient_activation




 def    lowercase_	( self				,	lowerCAmelCase_)			->   int:



      """simple docstring"""







      a_									=xdata
      if self.is_input_layer:
           # input layer
           a_									=xdata
           a_									=xdata
           return xdata
      else:
           a_									=np.dot(self.weight				,	self.xdata) - self.bias
           a_									=self.activation(self.wx_plus_b)
           return self.output




 def    lowercase_	( self				,	lowerCAmelCase_)			->   Dict:



      """simple docstring"""







      a_									=self.cal_gradient()  # i * i 维
      a_									=np.asmatrix(np.dot(gradient.T				,	lowerCAmelCase_))

      a_									=np.asmatrix(self.xdata)
      a_									=-1
      a_									=self.weight

      a_									=np.dot(gradient.T				,	self._gradient_weight.T)
      a_									=gradient * self._gradient_bias
      a_									=np.dot(lowerCAmelCase_				,	self._gradient_x).T
      # upgrade: the Negative gradient direction
      a_									=self.weight - self.learn_rate * self.gradient_weight
      a_									=self.bias - self.learn_rate * self.gradient_bias.T
      # updates the weights and bias according to learning rate (0.3 if undefined)
      return self.gradient







class 						UpperCAmelCase						:


 '''simple docstring'''




 def __init__( self)			->   Any:



      """simple docstring"""







      a_									=[]
      a_									=[]
      a_									=plt.figure()
      a_									=self.fig_loss.add_subplot(1				,	1				,	1)




 def    lowercase_	( self				,	lowerCAmelCase_)			->   Optional[int]:



      """simple docstring"""







      self.layers.append(lowerCAmelCase_)




 def    lowercase_	( self)			->   Any:



      """simple docstring"""







      for i, layer in enumerate(self.layers[:]):
           if i < 1:
                a_									=True
           else:
                layer.initializer(self.layers[i - 1].units)




 def    lowercase_	( self)			->   int:



      """simple docstring"""







      for i, layer in enumerate(self.layers[:]):
           print(f"""------- layer {i} -------""")
           print("weight.shape "				,	np.shape(layer.weight))
           print("bias.shape "				,	np.shape(layer.bias))




 def    lowercase_	( self				,	lowerCAmelCase_				,	lowerCAmelCase_				,	lowerCAmelCase_				,	lowerCAmelCase_)			->   Tuple:



      """simple docstring"""







      a_									=train_round
      a_									=accuracy

      self.ax_loss.hlines(self.accuracy				,	0				,	self.train_round * 1.1)

      a_									=np.shape(lowerCAmelCase_)
      for _ in range(lowerCAmelCase_):
           a_									=0
           for row in range(x_shape[0]):
                a_									=np.asmatrix(xdata[row, :]).T
                a_									=np.asmatrix(ydata[row, :]).T

                # forward propagation
                for layer in self.layers:
                     a_									=layer.forward_propagation(_xdata)

                a_		,    a_									=self.cal_loss(_ydata				,	_xdata)
                a_									=all_loss + loss

                # back propagation: the input_layer does not upgrade
                for layer in self.layers[:0:-1]:
                     a_									=layer.back_propagation(lowerCAmelCase_)

           a_									=all_loss / x_shape[0]
           self.train_mse.append(lowerCAmelCase_)

           self.plot_loss()

           if mse < self.accuracy:
                print("----达到精度----")
                return mse
      return None




 def    lowercase_	( self				,	lowerCAmelCase_				,	lowerCAmelCase_)			->   str:



      """simple docstring"""







      a_									=np.sum(np.power((ydata - ydata_)				,	2))
      a_									=2 * (ydata_ - ydata)
      # vector (shape is the same as _ydata.shape)
      return self.loss, self.loss_gradient




 def    lowercase_	( self)			->   Optional[Any]:



      """simple docstring"""







      if self.ax_loss.lines:
           self.ax_loss.lines.remove(self.ax_loss.lines[0])
      self.ax_loss.plot(self.train_mse				,	"r-")
      plt.ion()
      plt.xlabel("step")
      plt.ylabel("loss")
      plt.show()
      plt.pause(0.1)






def 			UpperCAmelCase_							(		):


     '''simple docstring'''







     a_									=np.random.randn(1_0							,						1_0							)
     a_									=np.asarray(
         [
             [0.8, 0.4],
             [0.4, 0.3],
             [0.34, 0.45],
             [0.67, 0.32],
             [0.88, 0.67],
             [0.78, 0.77],
             [0.55, 0.66],
             [0.55, 0.43],
             [0.54, 0.1],
             [0.1, 0.5],
         ]							)
     a_									=BPNN()
     for i in (1_0, 2_0, 3_0, 2):
          model.add_layer(DenseLayer(lowercase__							)							)
     model.build()
     model.summary()
     model.train(xdata=lowercase__							,						ydata=lowercase__							,						train_round=1_0_0							,						accuracy=0.01							)


if __name__ == "__main__":
  example()







'''simple docstring'''


lowercase											=      (1, 153, 370, 371, 1_634, 24_678_051, 115_132_219_018_763_992_565_095_597_973_971_522_401)
lowercase											=      (-153, -1, 0, 1.2, 200, "A", [], {}, None)






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     if not isinstance(lowercase__							,						lowercase__							) or n < 1:
          return False

     # Initialization of sum and number of digits.
     a_									=0
     a_									=0
     a_									=n
     # Calculation of digits of the number
     while temp > 0:
          number_of_digits += 1
          temp //= 1_0
     # Dividing number into separate digits and find Armstrong number
     a_									=n
     while temp > 0:
          a_									=temp % 1_0
          total += rem**number_of_digits
          temp //= 1_0
     return n == total






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     if not isinstance(lowercase__							,						lowercase__							) or n < 1:
          return False

     # Init a "histogram" of the digits
     a_									=[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
     a_									=0
     a_									=0
     a_									=n
     while temp > 0:
          a_		,    a_									=divmod(lowercase__							,						1_0							)
          digit_histogram[rem] += 1
          digit_total += 1

     for cnt, i in zip(lowercase__							,						range(len(lowercase__							)							)							):
          total += cnt * i**digit_total

     return n == total






def 			UpperCAmelCase_							(		lowercase__							):


     '''simple docstring'''







     if not isinstance(lowercase__							,						lowercase__							) or n < 1:
          return False
     a_									=len(str(lowercase__							)							)  # the power that all digits will be raised to
     # check if sum of each digit multiplied expo times is equal to number
     return n == sum(int(lowercase__							) ** expo for i in str(lowercase__							)							)






def 			UpperCAmelCase_							(		):


     '''simple docstring'''







     a_									=int(input("Enter an integer to see if it is an Armstrong number: "							).strip()							)
     print(F"""{num} is {'' if armstrong_number(lowercase__							) else 'not '}an Armstrong number."""							)
     print(F"""{num} is {'' if narcissistic_number(lowercase__							) else 'not '}an Armstrong number."""							)
     print(F"""{num} is {'' if pluperfect_number(lowercase__							) else 'not '}an Armstrong number."""							)


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()


