总结:numpy中三个乘法运算multiply,dot和* 的区别

人走茶凉 提交于 2020-01-14 23:57:23

引言:
本人在做机器学习的练习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()用法:
数组、矩阵都得到对应位置相乘。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!