Logistic回归python代码

来源:互联网 发布:数组 reverse 编辑:程序博客网 时间:2024/04/30 00:18

参考文献:http://blog.csdn.net/dongtingzhizi/article/details/15962797

将逻辑回归的cost函数向量化

给出了线性回归的cost函数为:
这里写图片描述

对上式对每个theta求偏导:
这里写图片描述

将没给theta求得的偏导向量化:
这里写图片描述

其中,最后一步将求和去掉的原理如下:
这里写图片描述

__author__ = 'Chen'from numpy import *#calculate the costdef costFunction(X,Y,theta):    mse = ( 1/(1+exp(-theta*X.T)) - Y.T)    return mse *mse.T#linearReresiondef linearRegresion(x,y,alpha=0.01):    xrow = shape(x)[0]    xcol = shape(x)[1]    x = matrix(x)    Y = matrix(y)    # fill ones    xone = ones((xrow,1))    X = hstack((xone,x))    X = matrix(X)    # gradiant    theta = matrix(random.random(xcol+1))    # iterations    for iteration in range(1,10000):        # return the cost        print costFunction(X,Y,theta),theta        sums = 0        #begin  gradient method        error = ( 1.0/(1+exp(-X*theta.T)) - Y)          test = X.T * error        theta -= alpha * test.T        #end  gradient method    return thetax= [[0.1,0.2],[0.3,0.2],[1,1],[0.9,0.8]]y= [[0],[0],[1],[1]]#gradient descenttheta2 = linearRegresion(x,y)print theta2
0 0
原创粉丝点击