parameters = int(theta.ravel()。shape [1])是什么意思?

时间:2018-04-15 23:59:40

标签: python numpy linear-regression gradient-descent

有人可以为我解释一下代码吗?

def gradientDescent(X, y, theta, alpha, iters):  
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    for i in range(iters):
    error = (X * theta.T) - y

    for j in range(parameters):
        term = np.multiply(error, X[:,j])
        temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))

    theta = temp
    cost[i] = computeCost(X, y, theta)

return theta, cost

1 个答案:

答案 0 :(得分:0)

逐步评估样本:

In [13]: np.matrix(np.zeros((3,4)))
Out[13]: 
matrix([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])
In [14]: _.ravel()
Out[14]: matrix([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]])
In [15]: _.shape
Out[15]: (1, 12)
In [16]: _[1]
Out[16]: 12

np.matrix总是2d,即使是在狂欢时也是如此。

如果我们使用的是数组,而不是matrix

In [17]: np.zeros((3,4))
Out[17]: 
array([[0., 0., 0., 0.],
       [0., 0., 0., 0.],
       [0., 0., 0., 0.]])
In [18]: _.ravel()
Out[18]: array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
In [19]: _.shape
Out[19]: (12,)
In [20]: _[0]
Out[20]: 12

循环要求Xthetatemp都具有相同的第二维。我还认为theta必须是(1,n)矩阵才能开始。否则这个ravel参数会太大。但在这种情况下,首先不需要拉扯。

相关问题