基础神经网络权重更新异常,总误差与预期不符求解决方案
问题根因
- 代码核心问题是函数内更新的权重没有同步到外层的全局权重变量:你在
calculate函数中执行weights = weights - (weights_delta * alpha)时,只是给函数内的局部变量weights重新赋值,并没有修改外层传入的weights_matrix对象,所有迭代全程都在用初始权重计算,误差自然和预期不符。 - 你之前尝试返回权重但运行错误,是因为没有正确接收返回的权重值并更新全局的权重变量。
修正方案
- 修改
calculate函数的返回值,同时返回单样本误差和更新后的权重 - 每次调用
calculate函数时,接收返回的误差和新权重,用新权重覆盖原有的weights_matrix,保证后续计算用的是更新后的权重。
完整修正代码
import numpy as np def calculate(input_numbers: list[float], weights: np.array, iterations: int, alpha: float, goal: list[float]): num_rows, num_cols = weights.shape if not len(input_numbers) == num_cols: print("Wrong matrix") return 0, weights error = 0 prediction = np.dot(input_numbers, np.transpose(weights)) delta = prediction - goal weights_delta = np.outer(delta, input_numbers) weights = weights - (weights_delta * alpha) error = error + (pow(prediction - goal, 2)) # 不需要调试可以注释掉下面的打印语句,减少输出内容 # print("\nXXXXXXXXXXXXXXXX SUMMARY XXXXXXXXXXXXXXXXX") # print("delta :" + str(delta)) # print("weights_delta :" + str(weights_delta)) # print("Weights : " + str(weights)) # print("error : " + str(error)) return np.sum(error), weights input_1 = [8.5, 0.65, 1.2] goal_1 = [0.1, 1, 0.1] input_2 = [9.5, 0.8, 1.3] goal_2 = [0, 1, 0] input_3 = [9.9, 0.8, 0.5] goal_3 = [0, 0, 0.1] input_4 = [9.0, 0.9, 1.0] goal_4 = [0.1, 1, 0.2] weights_matrix = np.array([[0.1, 0.1, -0.3], [0.1, 0.2, 0.0], [0.0, 1.3, 0.1]]) for x in range(50): print("\nITERATION: ", x) err, weights_matrix = calculate(input_1, weights_matrix, 1, 0.01, goal_1) error_sum = err err, weights_matrix = calculate(input_2, weights_matrix, 1, 0.01, goal_2) error_sum += err err, weights_matrix = calculate(input_3, weights_matrix, 1, 0.01, goal_3) error_sum += err err, weights_matrix = calculate(input_4, weights_matrix, 1, 0.01, goal_4) error_sum += err print("TOTAL ERROR: ", error_sum)
效果验证
修改后运行50轮迭代,最终总误差会收敛到你预期的1.501535左右区间。
内容的提问来源于stack exchange,提问作者FilipA
相关产品推荐
相关产品推荐

