引言:
本人在做机器学习的练习1的时候,时常抛出错误:
Not aligned是什么意思呢?
意思是两个矩阵相乘无意义。
线性代数中mxn 和 nxp的矩阵才能相乘,其结果是mxp的矩阵。
出错源代码:
def gradientDescent(X,y,theta,alpha,iteration):
colunms = int(theta.ravel().shape[1])
thetai = np.matrix(np.zeros(theta.shape))
cost = np.zeros(iteration)
for i in range(iteration):
error = X*theta.T-y
for j in range(colunms):
a = np.sum(error*X[:,j])/len(X) ########## error!
thetai[0,j] = thetai[0,j] - alpha*a
theta = thetai
cost[i] = computeCost(X, y, theta)
return theta,cost
这里error是一个nx1的矩阵,theta.T也是一个nx1的矩阵。
而矩阵之间*运算符表示矩阵乘法。我们这里想实现矩阵的对应元素相乘,因此应该用np.multiply()实现。
总结:
(读者可使用简单的举例自行验证)
1.*用法:
矩阵与矩阵:矩阵乘法(matrix)
数组与数组:对应位置相乘(array)
2.np.dot()用法:
矩阵相乘的结果
3.np.multiply()用法:
数组、矩阵都得到对应位置相乘。