机器学习和优化 scipy

machine learning and optimizing scipy

我有编码机器学习,为了优化我的成本函数,我使用了 scipy.optimize.minimum 但 scipy 不 return 正确 answer.so 我应该怎么做?

代码:

data1 = pd.read_csv('ex2data1.txt', header = None, names = 
['exam1','exam2', 'y'])
data1['ones'] = pd.Series(np.ones(100), dtype = int)
data1 = data1[['ones', 'exam1', 'exam2', 'y']]
X = np.matrix(data1.iloc[:, 0:3])
y = np.matrix(data1.iloc[:, 3:])  

def gFunction(z):
    return sc.special.expit(-z)  

def hFunction(theta, X):
    theta = np.matrix(theta).T
    h = np.matrix(gFunction(X.dot(theta)))
    return h  

def costFunction(theta, X, y):
    m = y.size
    h = hFunction(theta, X).T
    j = (-1 / m) * (np.dot(np.log(h), y) + np.dot(np.log(1-h), (1-y)))
    return j

def gradientDescent(theta, X, y):
    theta = np.matrix(theta)
    m = y.size
    h = hFunction(theta, X)
    gradient = (1 / m) * X.T.dot(h - y)
    return gradient.flatten()  

initial_theta = np.zeros(X.shape[1])
cost = costFunction(initial_theta, X, y)
grad = gradientDescent(initial_theta, X, y)
print('Cost: \n', cost)
print('Grad: \n', grad)
Cost: 
   [[ 0.69314718]]
Grad: 
   [[ -0.1        -12.00921659 -11.26284221]]

def optimizer(costFunction, theta, X, y, gradientDescent):
    optimum = sc.optimize.minimize(costFunction, theta, args = (X, y), 
     method = None, jac = gradientDescent, options={'maxiter':400})
    return optimum  

 Warning: Desired error not necessarily achieved due to precision loss.
      Current function value: 0.693147
      Iterations: 0
      Function evaluations: 106
      Gradient evaluations: 94
Out[46]:
     fun: matrix([[ 0.69314718]])
hess_inv: array([[1, 0, 0],
                 [0, 1, 0],
                 [0, 0, 1]])
    jac: matrix([[ -0.1       , -12.00921659, -11.26284221]])
message: 'Desired error not necessarily achieved due to precision loss.'
   nfev: 106
    nit: 0
   njev: 94
 status: 2
success: False
      x: array([ 0.,  0.,  0.])

这是表示成功的消息 False 我做的一切都是对的我不知道发生了什么

在以下情况下很难调试这样的东西:

  • 由于外部数据,代码无法重现
  • 问题甚至没有试图解释这里优化了什么

有一些奇怪的设计决定:

  • 使用 np.matrix -> 使用 np.array!
  • 不要调用雅可比梯度下降

然后关于您的观察:

Iterations: 0
Function evaluations: 106
Gradient evaluations: 94

在进行如此多的功能评估时进行零迭代是一个非常糟糕的迹象。东西很破。可能线搜索在上面变得疯狂,但这只是一个猜测。

现在什么坏了?:

  • 你的雅可比绝对坏了!
    • 我没有检查数学,但是:
      • 当变量数量固定时,你的雅可比形状取决于样本数量 -> 不!这没有意义!

完成步骤:

  • 运行 和 jac=False
    • 如果工作:你的成本看起来不错
    • 如果不工作:你的麻烦可能(没有证据)甚至从那里开始
  • 修复雅可比矩阵!
  • 对照 check_grad
  • 检查雅可比矩阵

我想知道为什么你在这里没有任何形状错误。当我尝试模仿您的输入形状并尝试使用样本大小时,我会这样做!