【问题标题】:optimize.fmin_tnc is not giving right answer in scipy.optimize?optimize.fmin_tnc 在 scipy.optimize 中没有给出正确答案?
【发布时间】:2019-10-28 00:22:18
【问题描述】:

我正在实施 Andrew ng 的 Python 机器学习课程。在编程练习 2 中,在第一个问题上,我得到了成本函数和梯度的写答案,但是当计算优化 theta 时,我得到了一个灾难性的答案!

我已经尽力了,但找不到错误

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def cost_compute(  theta,x, y):
    J = (-1/m) * np.sum(np.multiply(Y, np.log(sigmoid(X @ theta))) 
        + np.multiply((1-Y), np.log(1 - sigmoid(X @ theta))))
    return J

[m, n] = X.shape
X = np.hstack( (np.ones((m,1)) , X) )
Y = Y[:, np.newaxis]
theta = np.zeros((n+1,1))

def grad( theta, X, Y):
    temp = (1/m) * X.T @ (sigmoid(X @ theta) - Y)  
    return temp

temp = opt.fmin_tnc(func = cost_compute, x0 = theta.flatten() , fprime = grad , args = (X, Y.flatten()))

print(temp)

预期成本是 0.693,我知道了。 预期的毕业生也与实际答案完全相同。 但是我得到的优化的 theta 是数组([4.42735730e-05, 5.31690927e-03, 4.98646266e-03],给了我大约 60 的新成本!(而不是 0.203)

【问题讨论】:

    标签: python-3.x numpy machine-learning optimization scipy


    【解决方案1】:

    我做了一些测试,改变了数组的形状,把它展平,重塑它,但没有任何效果。

    由于我们通过展平 theta 在 fmin_tnc 中输入一维 theta,所以我想改变梯度函数,假设它将接收一维 theta 而不是 3*1。

    之前是

    def grad( theta, X, Y):
        temp = (1/m) * X.T @ (sigmoid(X @ theta) - Y)  
        return temp
    

    现在是

    def grad( theta, X, Y):
        temp = (1/m) * (X.T @ (sigmoid(X @ theta[:,np.newaxis]) - Y))  
        return temp
    

    现在可以了!

    【讨论】:

      【解决方案2】:

      问题是您将np.sum 与np.multiply 一起调用,而不是使用例如np.dot,这些操作一般不等价。

      np.multiply 运算计算元素乘积,而np.dot 计算适当的矩阵乘积,请参阅 Anuj Gautam 的 this answer on SO:

      np.dot 是两个矩阵的dot product。

      |A B| . |E F| = |A*E+B*G A*F+B*H|
      |C D|   |G H|   |C*E+D*G C*F+D*H|
      

      而np.multiply 执行element-wise multiplication 两个矩阵。

      |A B| ⊙ |E F| = |A*E B*F|
      |C D|   |G H|   |C*G D*H|
      

      要计算交叉熵损失,需要矩阵乘法。

      将成本函数更改为

      def cost_compute(  theta, X, Y):
          J = (-1/m) * (np.dot(Y.T, np.log(sigmoid(X @ theta))) 
              + np.dot((1-Y).T, np.log(1 - sigmoid(X @ theta))))
          return J
      

      得到我想要的结果:

      >> cost_compute(temp[0], X, Y)
      array([0.2034977])
      

      此外,cost_compute 函数的参数x 和y 的大小写错误,因为您在函数内部使用了大写版本的X 和Y。

      【讨论】:

      • 感谢您指出大写错误。但是在这种特定情况下使用 sum 和 multiply 并没有错,因为 Y 和 sigmoid 的形状为 m*1,所以如果我要使用点积,那么我需要这样做``` YT @ np.log(sigmoid(X @theta))```
      猜你喜欢
      • 2020-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 2015-06-23
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      相关资源
      最近更新 更多