Python实现逻辑斯蒂回归

本文阅读 1 分钟
首页 Python笔记 正文

使用Python实现Logistic回归,代码思路来源于机器学习实战,改正了原代码中的一些在Python3.5上运行存在的bug。对随机梯度上升法进行了简单的修改。

  1. from math import exp
  2. from numpy import *
  3. def loadDataSet():
  4. dataMat = []; labelMat = []
  5. fr = open('testSet.txt')
  6. for line in fr.readlines():
  7. lineArr = line.strip().split()
  8. dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
  9. labelMat.append(int(lineArr[2]))
  10. return dataMat, labelMat
  11. def sigmoid(inX):
  12. return 1/(1+exp(-inX))
  13. def gradAscent(dataMatIn, classLabels):
  14. dataMatrix = mat(dataMatIn)
  15. labelMat = mat(classLabels).transpose()
  16. m, n = shape(dataMatrix)
  17. alpha = 0.001
  18. maxCycles = 500
  19. weights = ones((n, 1))
  20. for k in range(maxCycles):
  21. h = sigmoid(dataMatrix*weights)
  22. error = (labelMat - h)
  23. weights += alpha * dataMatrix.transpose() * error
  24. return weights
  25. def stocGradAscent0(dataMatrix, classLabels):
  26. m, n = shape(dataMatrix)
  27. alpha = 0.01
  28. weights = ones(n)
  29. for i in range(m):
  30. h = sigmoid(sum(dataMatrix[i]*weights))
  31. error = classLabels[i] - h
  32. weights = weights + alpha * error * dataMatrix[i]
  33. return weights
  34. def stocGradAscent1(dataMatrix, classLabels, numIter=150):
  35. m, n = shape(dataMatrix)
  36. weights = ones(n)
  37. for i in range(numIter):
  38. dataIndex = len(list(range(m)))
  39. for j in range(m):
  40. alpha = 4/(1.0+i+j)+0.01
  41. randIndex = int(random.uniform(0, dataIndex))
  42. h = sigmoid(sum(dataMatrix[randIndex]*weights))
  43. error = classLabels[randIndex] - h
  44. weights = weights + alpha * error * dataMatrix[randIndex]
  45. dataIndex -= 1
  46. return weights
  47. def plotBestFit(weights):
  48. import matplotlib.pyplot as plt
  49. dataMat,labelMat=loadDataSet()
  50. dataArr = array(dataMat)
  51. n = shape(dataArr)[0]
  52. xcord1 = []; ycord1 = []
  53. xcord2 = []; ycord2 = []
  54. for i in range(n):
  55. if int(labelMat[i])== 1:
  56. xcord1.append(dataArr[i,1]); ycord1.append(dataArr[i,2])
  57. else:
  58. xcord2.append(dataArr[i,1]); ycord2.append(dataArr[i,2])
  59. fig = plt.figure()
  60. ax = fig.add_subplot(111)
  61. ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
  62. ax.scatter(xcord2, ycord2, s=30, c='green')
  63. if weights is not None:
  64. x = arange(-3.0, 3.0, 0.1)
  65. y = (-weights[0]-weights[1]*x)/weights[2] #令w0*x0 + w1*x1 + w2*x2 = 0,其中x0=1,解出x1和x2的关系
  66. ax.plot(x, y) #一个作为X一个作为Y,画出直线
  67. plt.xlabel('X1'); plt.ylabel('X2');
  68. plt.show()
  69. def classifyVector(inX, weights):
  70. prob = sigmoid(sum(inX*weights))
  71. if prob > 0.5: return 1.0
  72. else: return 0.0
  73. def colicTest():
  74. frTrain = open('horseColicTraining.txt')
  75. frTest = open('horseColicTest.txt')
  76. trainingSet = []; trainingLabels = []
  77. for line in frTrain.readlines():
  78. currLine = line.strip().split('\t')
  79. lineArr = []
  80. for i in range(21):
  81. lineArr.append(float(currLine[i]))
  82. trainingSet.append(lineArr)
  83. trainingLabels.append(float(currLine[21]))
  84. trainWeights = stocGradAscent1(array(trainingSet), trainingLabels, 500)
  85. errorCount = 0; numTestVec = 0.0
  86. for line in frTest.readlines():
  87. numTestVec += 1.0
  88. currLine = line.strip().split('\t')
  89. lineArr = []
  90. for i in range(21):
  91. lineArr.append(float(currLine[i]))
  92. if int(classifyVector(array(lineArr), trainWeights)) != int(currLine[21]):
  93. errorCount += 1
  94. errorRate = float(errorCount)/numTestVec
  95. print("the error rate of this test is: %f" % errorRate)
  96. return errorRate
  97. def multiTest():
  98. numTests = 10; errorSum = 0.0
  99. for k in range(numTests):
  100. errorSum += colicTest()
  101. print("after %d iterations the average error rate is: %f" % (numTests, errorSum/float(numTests)))
  102. dataArr, labelMat = loadDataSet()
  103. weights = stocGradAscent1(array(dataArr), labelMat)
  104. multiTest()
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python求树的宽度
« 上一篇 01-21
写一个函数,获取一篇文章内容中的全部图片,并下载
下一篇 » 01-30

发表评论