1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
| class NeuralNetworkLearner: """完整的神经网络学习器""" def __init__(self, layers, learning_rate=0.01, batch_size=32): """ 初始化学习器 参数: layers: 网络层结构列表,如 [2, 4, 1] learning_rate: 学习率 batch_size: 批量大小 """ self.layers = layers self.learning_rate = learning_rate self.batch_size = batch_size self.num_layers = len(layers) self.weights = [] self.biases = [] for i in range(1, self.num_layers): w = np.random.randn(layers[i-1], layers[i]) * np.sqrt(2.0 / layers[i-1]) b = np.zeros((1, layers[i])) self.weights.append(w) self.biases.append(b) self.loss_history = [] self.accuracy_history = [] def relu(self, x): """ReLU激活函数""" return np.maximum(0, x) def relu_derivative(self, x): """ReLU函数的导数""" return (x > 0).astype(float) def sigmoid(self, x): """Sigmoid激活函数""" return 1 / (1 + np.exp(-np.clip(x, -500, 500))) def sigmoid_derivative(self, x): """Sigmoid函数的导数""" s = self.sigmoid(x) return s * (1 - s) def forward_propagation(self, X): """前向传播""" activations = [X] z_values = [] current_input = X for i in range(len(self.weights)): z = np.dot(current_input, self.weights[i]) + self.biases[i] z_values.append(z) if i < len(self.weights) - 1: a = self.relu(z) else: a = self.sigmoid(z) activations.append(a) current_input = a return activations, z_values def backward_propagation(self, X, y, activations, z_values): """反向传播""" m = X.shape[0] weight_gradients = [] bias_gradients = [] delta = (activations[-1] - y) * self.sigmoid_derivative(z_values[-1]) for i in range(len(self.weights) - 1, -1, -1): weight_grad = np.dot(activations[i].T, delta) / m bias_grad = np.mean(delta, axis=0, keepdims=True) weight_gradients.insert(0, weight_grad) bias_gradients.insert(0, bias_grad) if i > 0: delta = np.dot(delta, self.weights[i].T) * self.relu_derivative(z_values[i-1]) return weight_gradients, bias_gradients def update_parameters(self, weight_gradients, bias_gradients): """更新网络参数""" for i in range(len(self.weights)): self.weights[i] -= self.learning_rate * weight_gradients[i] self.biases[i] -= self.learning_rate * bias_gradients[i] def create_mini_batches(self, X, y): """创建小批量数据""" m = X.shape[0] mini_batches = [] permutation = np.random.permutation(m) shuffled_X = X[permutation] shuffled_y = y[permutation] num_complete_minibatches = m // self.batch_size for k in range(num_complete_minibatches): mini_batch_X = shuffled_X[k * self.batch_size:(k + 1) * self.batch_size] mini_batch_y = shuffled_y[k * self.batch_size:(k + 1) * self.batch_size] mini_batches.append((mini_batch_X, mini_batch_y)) if m % self.batch_size != 0: mini_batch_X = shuffled_X[num_complete_minibatches * self.batch_size:] mini_batch_y = shuffled_y[num_complete_minibatches * self.batch_size:] mini_batches.append((mini_batch_X, mini_batch_y)) return mini_batches def train(self, X, y, epochs, verbose=True): """ 训练神经网络 参数: X: 训练数据 y: 训练标签 epochs: 训练轮数 verbose: 是否打印训练过程 """ for epoch in range(epochs): epoch_loss = 0 epoch_accuracy = 0 num_batches = 0 mini_batches = self.create_mini_batches(X, y) for mini_batch_X, mini_batch_y in mini_batches: activations, z_values = self.forward_propagation(mini_batch_X) batch_loss = LossFunctions.mse(mini_batch_y, activations[-1]) epoch_loss += batch_loss predictions = (activations[-1] > 0.5).astype(int) batch_accuracy = np.mean(predictions == mini_batch_y) epoch_accuracy += batch_accuracy weight_gradients, bias_gradients = self.backward_propagation( mini_batch_X, mini_batch_y, activations, z_values ) self.update_parameters(weight_gradients, bias_gradients) num_batches += 1 avg_loss = epoch_loss / num_batches avg_accuracy = epoch_accuracy / num_batches self.loss_history.append(avg_loss) self.accuracy_history.append(avg_accuracy) if verbose and epoch % 100 == 0: print(f"Epoch {epoch}, Loss: {avg_loss:.6f}, Accuracy: {avg_accuracy:.4f}") def predict(self, X): """预测函数""" activations, _ = self.forward_propagation(X) return activations[-1]
def comprehensive_learning_example(): """综合学习示例""" np.random.seed(42) n_samples = 1000 def generate_spiral_data(n_points, n_classes): X = np.zeros((n_points * n_classes, 2)) y = np.zeros(n_points * n_classes, dtype='uint8') for j in range(n_classes): ix = range(n_points * j, n_points * (j + 1)) r = np.linspace(0.0, 1, n_points) t = np.linspace(j * 4, (j + 1) * 4, n_points) + np.random.randn(n_points) * 0.2 X[ix] = np.c_[r * np.sin(t), r * np.cos(t)] y[ix] = j return X, y X, y = generate_spiral_data(n_samples // 2, 2) y = y.reshape(-1, 1) X_mean = np.mean(X, axis=0) X_std = np.std(X, axis=0) X_normalized = (X - X_mean) / X_std learner = NeuralNetworkLearner( layers=[2, 16, 8, 1], learning_rate=0.1, batch_size=64 ) print("开始训练综合学习示例...") learner.train(X_normalized, y, epochs=2000, verbose=True) predictions = learner.predict(X_normalized) predicted_classes = (predictions > 0.5).astype(int) accuracy = np.mean(predicted_classes == y) print(f"\n训练完成!") print(f"最终准确率: {accuracy:.4f}") plt.figure(figsize=(15, 5)) plt.subplot(1, 3, 1) plt.scatter(X[y.flatten() == 0, 0], X[y.flatten() == 0, 1], c='red', alpha=0.6, label='Class 0') plt.scatter(X[y.flatten() == 1, 0], X[y.flatten() == 1, 1], c='blue', alpha=0.6, label='Class 1') plt.title('原始数据分布') plt.legend() plt.grid(True, alpha=0.3) plt.subplot(1, 3, 2) plt.scatter(X[predicted_classes.flatten() == 0, 0], X[predicted_classes.flatten() == 0, 1], c='red', alpha=0.6, label='Predicted Class 0') plt.scatter(X[predicted_classes.flatten() == 1, 0], X[predicted_classes.flatten() == 1, 1], c='blue', alpha=0.6, label='Predicted Class 1') plt.title('预测结果') plt.legend() plt.grid(True, alpha=0.3) plt.subplot(1, 3, 3) plt.plot(learner.loss_history, label='Loss', alpha=0.7) plt.plot(learner.accuracy_history, label='Accuracy', alpha=0.7) plt.title('训练历史') plt.xlabel('Epoch') plt.ylabel('Value') plt.legend() plt.grid(True, alpha=0.3) plt.tight_layout() plt.show() return learner
if __name__ == "__main__": print("=== 综合学习示例 ===") comprehensive_learning_example()
|