在进行感知机学习时,我对权重的初始化和更新感到非常困惑。如果我有一个包含两个输入 x0 和 x1 的样本数据,并且有 80 行这样的输入数据,因此是一个 80×2 的矩阵。
我需要将权重初始化为一个 80×2 的矩阵,还是只初始化为两个值 w0 和 w1?感知机学习的最终目标是找到适合所有 80 行输入样本的两个权重 w0 和 w1 吗?
我有以下代码,尽管迭代次数达到 10,000 次,我的错误始终无法降到 0。
x=input matrix of 80x2y=output matrix of 80x1n = number of iterationsw=[0.1,0.1] learningRate = 0.1for i in range(n): expectedT = y.transpose(); xT = x.transpose() prediction = np.dot (w,xT) for i in range (len(x)): if prediction[i] >= 0: ypred[i] = 1 else: ypred[i] = 0 error = expectedT - ypred # updating the weights w = np.add(w,learningRate*(np.dot(error,x))) globalError = globalError + np.square(error)
回答:
每个特征都会有一个对应的权重。因此你有两个特征和两个权重。引入偏置会增加另一个权重。关于偏置的更多信息,请查看这篇文章神经网络中偏置的作用。权重确实应该学会如何最好地拟合样本数据。根据数据的不同,这可能意味着你永远无法达到 0 错误。例如,单层感知机在使用单调激活函数时无法学习 XOR 门。(用单层感知机解决 XOR)。
对于你的例子,我建议做两件事。引入偏置,并在错误低于某个阈值或错误为 0 时停止训练。
我完成了你的示例,用于学习逻辑 AND 门:
# AND input and outputx = np.array([[0,0],[0,1],[1,0],[1,1]])y = np.array([0,1,1,1])n = 1000w=[0.1,0.1,0.1] learningRate = 0.01globalError = 0def predict(X): prediction = np.dot(w[0:2],X) + w[2] ypred = np.zeros(len(y)) for i in range (len(y)): if prediction[i] >= 0: ypred[i] = 1 else: ypred[i] = 0 return ypredfor i in range(n): expectedT = y.transpose(); xT = x.transpose() ypred = predict(xT) error = expectedT - ypred if sum(error) == 0: break # updating the weights w[0:2] = np.add(w[0:2],learningRate*(np.dot(error,x))) w[2] += learningRate*sum(error) globalError = globalError + np.square(error)
训练后错误为 0
print(error)# [0. 0. 0. 0.]
权重如下
print(w)#[0.1, 0.1, -0.00999999999999999]
现在感知机可以用作 AND 门:
predict(x.transpose())#array([0., 1., 1., 1.])
希望这对你有帮助