Back Propagation Neural Network model
| 97 | |
| 98 | |
| 99 | class BPNN: |
| 100 | """ |
| 101 | Back Propagation Neural Network model |
| 102 | """ |
| 103 | |
| 104 | def __init__(self): |
| 105 | self.layers = [] |
| 106 | self.train_mse = [] |
| 107 | self.fig_loss = plt.figure() |
| 108 | self.ax_loss = self.fig_loss.add_subplot(1, 1, 1) |
| 109 | |
| 110 | def add_layer(self, layer): |
| 111 | self.layers.append(layer) |
| 112 | |
| 113 | def build(self): |
| 114 | for i, layer in enumerate(self.layers[:]): |
| 115 | if i < 1: |
| 116 | layer.is_input_layer = True |
| 117 | else: |
| 118 | layer.initializer(self.layers[i - 1].units) |
| 119 | |
| 120 | def summary(self): |
| 121 | for i, layer in enumerate(self.layers[:]): |
| 122 | print(f"------- layer {i} -------") |
| 123 | print("weight.shape ", np.shape(layer.weight)) |
| 124 | print("bias.shape ", np.shape(layer.bias)) |
| 125 | |
| 126 | def train(self, xdata, ydata, train_round, accuracy): |
| 127 | self.train_round = train_round |
| 128 | self.accuracy = accuracy |
| 129 | |
| 130 | self.ax_loss.hlines(self.accuracy, 0, self.train_round * 1.1) |
| 131 | |
| 132 | x_shape = np.shape(xdata) |
| 133 | for _ in range(train_round): |
| 134 | all_loss = 0 |
| 135 | for row in range(x_shape[0]): |
| 136 | _xdata = np.asmatrix(xdata[row, :]).T |
| 137 | _ydata = np.asmatrix(ydata[row, :]).T |
| 138 | |
| 139 | # forward propagation |
| 140 | for layer in self.layers: |
| 141 | _xdata = layer.forward_propagation(_xdata) |
| 142 | |
| 143 | loss, gradient = self.cal_loss(_ydata, _xdata) |
| 144 | all_loss = all_loss + loss |
| 145 | |
| 146 | # back propagation: the input_layer does not upgrade |
| 147 | for layer in self.layers[:0:-1]: |
| 148 | gradient = layer.back_propagation(gradient) |
| 149 | |
| 150 | mse = all_loss / x_shape[0] |
| 151 | self.train_mse.append(mse) |
| 152 | |
| 153 | self.plot_loss() |
| 154 | |
| 155 | if mse < self.accuracy: |
| 156 | print("----达到精度----") |