机器学习 Python实现逻辑回归

# -*- coding: cp936 -*-
from numpy import *

def loadDataSet():
    dataMat = []; labelMat = []
    fr = open('testSet.txt')
    for line in fr.readlines():
        lineArr = line.strip().split()
        dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
        labelMat.append(int(lineArr[2]))
    return dataMat,labelMat

def sigmoid(inX):  #逻辑函数
    return 1.0/(1+exp(-inX))

#梯度上升算法
def gradAscent(dataMatIn, classLabels):
    dataMatrix = mat(dataMatIn)             #convert to NumPy matrix
    labelMat = mat(classLabels).transpose() #convert to NumPy matrix
    m,n = shape(dataMatrix)
    alpha = 0.001 #梯度上升的步长
    maxCycles = 500 #迭代的最大次数
    weights = ones((n,1))
    for k in range(maxCycles):              #heavy on matrix operations
        h = sigmoid(dataMatrix*weights)     #matrix mult
        error = (labelMat - h)              #vector subtraction
        weights = weights + alpha * dataMatrix.transpose()* error #matrix mult
    return weights #迭代计算回归系数

def plotBestFit(weights):
    import matplotlib.pyplot as plt
    dataMat,labelMat=loadDataSet()
    dataArr = array(dataMat)
    n = shape(dataArr)[0]
    xcord1 = []; ycord1 = []
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelMat[i])== 1:
            xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
        else:
            xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
    ax.scatter(xcord2, ycord2, s=30, c='green')
    x = arange(-3.0, 3.0, 0.1)
    y = (-weights[0]-weights[1]*x)/weights[2]
    ax.plot(x, y)
    plt.xlabel('X1'); plt.ylabel('X2');
    plt.show()

#随机梯度上升算法
def stocGradAscent0(dataMatrix, classLabels):
    m,n = shape(dataMatrix)
    alpha = 0.01
    weights = ones(n)   #initialize to all ones
    for i in range(m):
        h = sigmoid(sum(dataMatrix[i]*weights))
        error = classLabels[i] - h   #error和h都相当于是矩阵
        weights = weights + alpha * error * dataMatrix[i]
    return weights

def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    m,n = shape(dataMatrix)
    weights = ones(n)   #initialize to all ones
    for j in range(numIter):
        dataIndex = range(m)
        for i in range(m):
            alpha = 4/(1.0+j+i)+0.0001    #apha decreases with iteration, does not
            randIndex = int(random.uniform(0,len(dataIndex)))#go to 0 because of the constant
            h = sigmoid(sum(dataMatrix[randIndex]*weights))
            error = classLabels[randIndex] - h
            weights = weights + alpha * error * dataMatrix[randIndex]
            del(dataIndex[randIndex]) #计算完的样本就进行删除就好
    return weights

def classifyVector(inX, weights):
    prob = sigmoid(sum(inX*weights))
    if prob > 0.5: return 1.0
    else: return 0.0

#利用疝气病的例子进行计算
def colicTest():
    frTrain = open('horseColicTraining.txt'); frTest = open('horseColicTest.txt')
    trainingSet = []; trainingLabels = []
    for line in frTrain.readlines():
        currLine = line.strip().split('\t')
        lineArr =[]
        for i in range(21):
            lineArr.append(float(currLine[i]))
        trainingSet.append(lineArr) #获取样本的特征向量
        trainingLabels.append(float(currLine[21])) #获取样本的类型标志
    trainWeights = stocGradAscent1(array(trainingSet), trainingLabels, 1000)#训练获得回归系数
    errorCount = 0; numTestVec = 0.0
    for line in frTest.readlines(): #测试样本的测试
        numTestVec += 1.0
        currLine = line.strip().split('\t')
        lineArr =[]
        for i in range(21):
            lineArr.append(float(currLine[i]))
        if int(classifyVector(array(lineArr), trainWeights))!= int(currLine[21]):
            errorCount += 1 #计算错误率
    errorRate = (float(errorCount)/numTestVec)
    print "the error rate of this test is: %f" % errorRate
    return errorRate

def multiTest():
    numTests = 10; errorSum=0.0
    for k in range(numTests):
        errorSum += colicTest()
    print "after %d iterations the average error rate is: %f" % (numTests, errorSum/float(numTests))
        

实现结果:

the error rate of this test is: 0.358209
the error rate of this test is: 0.417910
the error rate of this test is: 0.268657
the error rate of this test is: 0.298507
the error rate of this test is: 0.358209
the error rate of this test is: 0.343284
the error rate of this test is: 0.358209
the error rate of this test is: 0.373134
the error rate of this test is: 0.358209
the error rate of this test is: 0.402985
after 10 iterations the average error rate is: 0.353731

时间: 2024-08-24 10:27:50

机器学习 Python实现逻辑回归的相关文章

机器学习python实战----逻辑回归

当看到这部分内容的时候我是激动的,因为它终于能跟我之前学习的理论内容联系起来了,这部分内容就是对之前逻辑回归理论部分的代码实现,所以如果有不甚理解的内容可以返回对照着理论部分来理解,下面我们进入主题----logistic regression 一.sigmoid函数 在之前的理论部分我们知道,如果我们需要对某物进行二分类,那么我们希望输出函数的值在区间[0,1],于是我们引入了sigmoid函数.函数的形式为. 曲线图 根据函数表达式,我们可以用代码来表示 def sigmoid(Inx):

机器学习总结之逻辑回归Logistic Regression

机器学习总结之逻辑回归Logistic Regression 逻辑回归logistic regression,虽然名字是回归,但是实际上它是处理分类问题的算法.简单的说回归问题和分类问题如下: 回归问题:预测一个连续的输出. 分类问题:离散输出,比如二分类问题输出0或1. 逻辑回归常用于垃圾邮件分类,天气预测.疾病判断和广告投放. 一.假设函数 因为是一个分类问题,所以我们希望有一个假设函数,使得: 而sigmoid 函数可以很好的满足这个性质: 故假设函数: 其实逻辑回归为什么要用sigmoi

遵循统一的机器学习框架理解逻辑回归

遵循统一的机器学习框架理解逻辑回归 标签: 机器学习 LR 分类 一.前言 我的博客不是科普性质的博客,仅记录我的观点和思考过程.欢迎大家指出我思考的盲点,更希望大家能有自己的理解. 本文参考了网络上诸多资料. 二.理解 统一的机器学习框架(MLA): 1.模型(Model) 2.策略(Loss) 3.算法(Algorithm) 按照如上所说框架,LR最核心的就是损失函数使用了 Sigmoid 和 Cross Entropy . LR: Sigmoid + Cross Entropy Model

21-城里人套路深之用python实现逻辑回归算法

如果和一个人交流时,他的思想像弹幕一样飘散在空中,将是怎样的一种景象?我想大概会毫不犹豫的点关闭的.生活为啥不能简单明了?因为太直白了令人乏味.保留一些不确定性反而扑朔迷离,引人入胜.我们学习了线性回归,对于损失函数及权重更新公式理解起来毫无压力,这是具体直白的好处.然而遇到抽象晦涩的逻辑回归,它的损失函数及权重更新公式就经历了从p(取值范围0~1)->p/(1-p)(取值范围0~+oo)->z=log(p/(1-p))(取值范围-oo~+oo)->p=1/1+e^(-z)->极大

Stanford机器学习---第三讲. 逻辑回归和过拟合问题的解决 logistic Regression & Regularization

原文地址:http://blog.csdn.net/abcjennifer/article/details/7716281 本栏目(Machine learning)包括单参数的线性回归.多参数的线性回归.Octave Tutorial.Logistic Regression.Regularization.神经网络.机器学习系统设计.SVM(Support Vector Machines 支持向量机).聚类.降维.异常检测.大规模机器学习等章节.所有内容均来自Standford公开课machin

机器学习的简单逻辑回归的Advanced Optimization

Learning Course: One variable logistic regression optimization 单变量(只有一个特征)的用于分类的逻辑回归的cost function的最小值求解, here: x=[x1;x2]; y={0,1}; theta=[theta(1);theta(2)] 由于分类中的y值需为0-1之间的数值,因此这里的cost function不同于线性回归的cost function. hθ(x)=g(θTx), where g(x)= 1/(1-e

Python之逻辑回归模型来预测

建立一个逻辑回归模型来预测一个学生是否被录取. import numpy as np import pandas as pd import matplotlib.pyplot as plt import os path='data'+os.sep+'Logireg_data.txt' pdData=pd.read_csv(path,header=None,names=['Exam1','Exam2','Admitted']) pdData.head() print(pdData.head())

Python实现机器学习算法:逻辑回归

import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_classification def initialize_params(dims): w = np.zeros((dims, 1)) b = 0 return w, b def sigmoid(x): z = 1 / (1 + np.exp(-x)) return z def logisti

Python之逻辑回归

代码: 1 import numpy as np 2 from sklearn import datasets 3 from sklearn.linear_model import LogisticRegression 4 import matplotlib.pyplot as plt 5 6 __author__ = 'zhen' 7 8 iris = datasets.load_iris() 9 10 for i in range(0, 4): 11 x = iris['data'][:,