IndexError:数组scipy.optimize.fmin_cg的索引过多

时间:2018-07-26 12:48:34

标签: python machine-learning scipy logistic-regression

当我偶然发现python时,我正在用Andrew NG的机器学习课程编写3rd assignment。我不知道问题是什么。任何帮助,将不胜感激。 代码:

def cost_grad(p_theta, p_x, p_y, p_lambda=1.0):
    m, n = p_x.shape
    h = sigmoid(p_x.dot(p_theta))
    delta = h - p_y

    val1 = (-p_y.transpose().dot(np.log(h)) - (1 - p_y).transpose().dot(np.log(1 - h))) / m
    val2 = p_lambda / (2 * m) * (p_theta[1:, :] ** 2).sum()
    cost = val1 + val2

    grad = p_x.transpose().dot(delta) / m
    grad[1:, :] = grad[1:, :] + p_lambda / m * p_theta[1:, :]

    return cost, grad


def get_ones(p_y, i):
    p = np.zeros(p_y.shape)
    p[np.where(p_y == i)] = 1
    return p


def one_vs_all(p_x, p_y, p_num_labels, p_lambda=1.0):
    all_grads = np.zeros((p_num_labels, p_x.shape[1]))
    for i in range(1, p_num_labels + 1):
        ones = get_ones(p_y, i)
        all_grads[i, :] = op.fmin_cg(cost_grad, x0=all_grads[i, :], args=(p_x, ones, p_lambda))
    return 0
  

第16行,在cost_grad中       val2 = p_lambda /(2 * m)*(p_theta [1 :,:] ** 2).sum()IndexError:数组的索引过多

0 个答案:

没有答案