我正在尝试理解使用梯度下降的线性回归,但在下面的loss_gradients
函数中我对这部分不太理解。
import numpy as npdef forward_linear_regression(X, y, weights): # dot product weights * inputs N = np.dot(X, weights['W']) # add bias P = N + weights['B'] # compute loss with MSE loss = np.mean(np.power(y - P, 2)) forward_info = {} forward_info['X'] = X forward_info['N'] = N forward_info['P'] = P forward_info['y'] = y return loss, forward_info
这是我理解上卡住的地方,我已经在代码中注释了我的问题:
def loss_gradients(forward_info, weights): # to update weights, we need: dLdW = dLdP * dPdN * dNdW dLdP = -2 * (forward_info['y'] - forward_info['P']) dPdN = np.ones_like(forward_info['N']) dNdW = np.transpose(forward_info['X'], (1, 0)) dLdW = np.dot(dNdW, dLdP * dPdN) # 为什么我们在这里混合使用矩阵乘法和点积? # 为什么不直接使用 dLdP * dPdN * dNdW? # to update biases, we need: dLdB = dLdP * dPdB dPdB = np.ones_like(forward_info[weights['B']]) dLdB = np.sum(dLdP * dPdB, axis=0) # 为什么我们沿着轴0对这些值求和? # 为什么不直接使用 dLdP * dPdB?
回答:
看起来这段代码是预期处理一批数据。也就是说,当你调用forward_info
和loss_gradients
时,你实际上是一次性传递了多个(X, y)对。假设你传递了B个这样的对。你的所有前向信息的第一维大小将是B。
现在,你两个问题的答案是相同的:基本上,这些代码行是为B个项计算梯度(使用你预测的公式),然后将所有梯度加总起来,从而得到一个梯度更新。我建议你自己推导点积背后的逻辑,因为这在机器学习中是一个非常常见的模式,虽然刚开始可能有点难以掌握。