微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python scipy.optimize.fmin_tnc自我实现

如何解决Python scipy.optimize.fmin_tnc自我实现

我是Junior开发人员,开始学习Logistic回归。
我在Ng课程中实现了算法,但有一点让我感到困惑。

我在任何搜索过的地方都使用:

fmin_tnc(func=self.cost_function,x0=theta,fprime=self.gradient,args=(x,y.flatten()),ftol=0.001)

但是我想自己实现它,以完全理解算法。 现在我有

    def fit(self,x,y,theta):
    
    self.cost_ = []  # hold the cost function output value of each iteration.
    self.theta = np.zeros((x.shape[1],1))  # the initial thetot values (defined to 0's)
    m = x.shape[0]  # number of samples(1,m). x.shape[1] == num of features (1,n)

    for iteration in range(self.n_iterations):

        ####  Calculate the Gradient Descent :
        gradient_vector_log = self.gradient(self.theta,y) # calculate the vectors of derivates

        # this is our theta,update it according the formula.
        self.theta -= gradient_vector_log

        #### Calculate the cost function of the current iteration :

        # here we add the cost: note that this should be decreasing all the time !
        cost = self.cost_function(self.theta,y)

        self.cost_.append(cost)  # COST FUNCTION values.


    return self

对我来说看起来不错,但是程序在我的成本函数中崩溃了:

    def cost_function(self,theta,y):
    # Computes the cost function for all the training samples
    m = x.shape[0]

    total_cost = -(1 / m) * np.sum(y * np.log(self.probability(theta,x)) + (1 - y) * np.log(1 - self.probability(theta,x)))

    return total_cost

给出的错误部分在于:

RuntimeWarning:exp返回1 /(1 + np.exp(-x))遇到溢出
...
ValueError:形状(100,3)和(3,1,1)不对齐:3(dim 1)!= 1(dim 1)
...

因此,我认为它与ndarray有关,但不确定。

完整的原始代码可以从这里获取https://github.com/animesh-agarwal/Machine-Learning/tree/master/LogisticRegression

*请注意,没有上面我详细介绍的更改。

我可以代替使用'fmin_tnc'吗? 怎么样?

谢谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。