机器学习 Python实现逻辑回归
2015-03-06 15:29
609 查看
# -*- 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
相关文章推荐
- 机器学习——Python实现逻辑回归
- Python数据分析与机器学习-Python实现逻辑回归与梯度下降策略
- 《机器学习》第2章中候选消除(CANDIDATE-ELIMINATION)算法的python实现随笔
- 【机器学习系列】logistic回归python实现
- 【机器学习】决策树-ID3算法的Python实现
- [机器学习]kNN算法python实现(实例:数字识别)
- 用Python从零实现贝叶斯分类器的机器学习的教程
- 推荐一个机器学习框架——python实现
- Python语言实现机器学习的K-近邻算法
- 机器学习之PYTHON实现KNN算法
- 机器学习经典算法详解及Python实现--聚类及K均值、二分K-均值聚类算法
- 机器学习三 -- 用Python实现K-近邻算法
- 机器学习-Logistic回归python实现
- 机器学习经典算法详解及Python实现---朴素贝叶斯分类及其在文本分类、垃圾邮件检测中的应用
- 机器学习经典算法详解及Python实现---Logistic回归(LR)分类器
- 【机器学习】K-近邻算法的Python实现
- 【机器学习系列】kNN(k近邻算法)的python实现
- 机器学习经典算法详解及Python实现--元算法、AdaBoost
- 机器学习经典算法详解及Python实现--K近邻(KNN)算法
- 机器学习Python实现 SVD 分解