【问题标题】:Logistic regression: the cost function is not decreasing逻辑回归:成本函数不递减
【发布时间】:2019-07-20 05:50:24
【问题描述】:

我目前正在 Coursera 上学习 Andrew Ng 课程,我尝试将我学到的关于逻辑回归的知识用于数据集。但我不能让成本函数减少。

我尝试了不同的学习率(0.001、0.003、0.0001……)和迭代次数。可能是我写错了函数但是找不到错误

import numpy as np
import scipy as sc
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data[:,:2]
Y = (iris.target != 0)*1
m = Y.size
th = np.random.rand(1,3)#theta
xo = np.ones((m,1))
Xi = np.concatenate((xo,X),axis=1)#X intercept
sigma = lambda z: 1/(1+(np.e**-z))
cost = lambda h,y: (np.sum(-y.T*np.log(h)-(1-y).T*np.log(1-h)))/m
grad = lambda h,y,x : np.sum(x.T@(h-y))/m
ite = 100000
lr = 0.0015
for i in range(ite):
    z = Xi@th.T
    th = th- lr*grad(sigma(z),Y,Xi)
    print(cost(sigma(z),Y))

【问题讨论】:

  • 无法重现:NameError: name 'Y' is not defined
  • 欢迎来到 SO;请查看如何创建minimal reproducible example
  • @desertnaut 对不起,我是 stackoverflow 的新手,我编辑了它,所以现在可以重现

标签: python machine-learning jupyter-notebook logistic-regression


【解决方案1】:

已修复,我不知道为什么我在渐变之前写了 np.sum。但现在有效

grad = lambda h,y,x : x.T@(h-y))/m

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 2021-02-16
    • 2019-04-24
    • 2020-05-08
    • 1970-01-01
    • 2016-05-26
    • 2015-09-28
    • 2021-07-20
    相关资源
    最近更新 更多