parameters = int(theta.ravel().shape[1]) 是什么意思?
what does parameters = int(theta.ravel().shape[1]) mean?
有人可以为我解释一下该代码吗?
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
在样本上逐步评估它:
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
A 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
循环要求 X
、theta
和 temp
都具有相同的二维。我还认为 theta
必须是一个 (1,n) 矩阵开始。否则这个 ravel 参数会太大。但在那种情况下,首先就不需要 ravel。
有人可以为我解释一下该代码吗?
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
在样本上逐步评估它:
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
A 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
循环要求 X
、theta
和 temp
都具有相同的二维。我还认为 theta
必须是一个 (1,n) 矩阵开始。否则这个 ravel 参数会太大。但在那种情况下,首先就不需要 ravel。