当前位置:   article > 正文

逻辑回归代码详解版

逻辑回归代码详解
  1. import numpy as np
  2. import pandas as pd
  3. import matplotlib.pyplot as plt
  4. import os
  5. path = 'C:/Users/Sherlock/data/LogiReg_data.csv'
  6. pdData = pd.read_csv(path, header=None, names=['Exam1', 'Exam2', 'Admitted'])
  7. pdData.head()
  8. print(pdData.head())
  9. print(pdData.shape)
  10. positive = pdData[pdData['Admitted'] == 1] # 定义正
  11. nagative = pdData[pdData['Admitted'] == 0] # 定义负
  12. fig, ax = plt.subplots(figsize=(10, 5))#子图的行数为10,列数为5
  13. ax.scatter(positive['Exam1'], positive['Exam2'], s=30, c='b', marker='o', label='Admitted')#s是标量或形如shape的数组,c显而易见是color,lable是标记、
  14. ax.scatter(nagative['Exam1'], nagative['Exam2'], s=30, c='r', marker='x', label='not Admitted')
  15. ax.legend()
  16. ax.set_xlabel('Exam 1 score')#设置图标
  17. ax.set_ylabel('Exam 2 score')
  18. plt.show() # 画图
  19. ##实现算法 the logistics regression 目标建立一个分类器 设置阈值来判断录取结果
  20. ##sigmoid 函数
  21. def sigmoid(z):
  22. return 1 / (1 + np.exp(-z)) #sigmoid 函数,公式
  23. # 画图
  24. nums = np.arange(-10, 10, step=1)
  25. fig, ax = plt.subplots(figsize=(12, 4))
  26. ax.plot(nums, sigmoid(nums), 'r') # 画图定义
  27. plt.show()
  28. # 按照理论实现预测函数
  29. def model(X, theta):
  30. return sigmoid(np.dot(X, theta.T)) #X矩阵和theta的转置矩阵相乘
  31. pdData.insert(0, 'ones', 1) # 插入一列
  32. orig_data = pdData.as_matrix()#将dataframe 转换成数组,
  33. cols = orig_data.shape[1] #shape【0】是行数,【1】是列数
  34. X = orig_data[:, 0:cols - 1]
  35. y = orig_data[:, cols - 1:cols]
  36. theta = np.zeros([1, 3]) #用0填充矩阵行数为1列数为3
  37. print(X[:5])
  38. print(X.shape, y.shape, theta.shape)
  39. ##损失函数
  40. def cost(X, y, theta):
  41. left = np.multiply(-y, np.log(model(X, theta))) #0的情况下
  42. right = np.multiply(1 - y, np.log(1 - model(X, theta)))#1的情况下
  43. return np.sum(left - right) / (len(X))
  44. print(cost(X, y, theta))
  45. # 计算梯度
  46. def gradient(X, y, theta):
  47. grad = np.zeros(theta.shape)#theta的维数进行填充0
  48. error = (model(X, theta) - y).ravel()#二维数组变一维数组
  49. for j in range(len(theta.ravel())): # for each parmeter
  50. term = np.multiply(error, X[:, j])
  51. grad[0, j] = np.sum(term) / len(X)
  52. return grad
  53. ##比较3种不同梯度下降方法
  54. STOP_ITER = 0
  55. STOP_COST = 1
  56. STOP_GRAD = 2
  57. def stopCriterion(type, value, threshold):
  58. if type == STOP_ITER:
  59. return value > threshold
  60. elif type == STOP_COST:
  61. return abs(value[-1] - value[-2]) < threshold
  62. elif type == STOP_GRAD:
  63. return np.linalg.norm(value) < threshold
  64. import numpy.random
  65. # 打乱数据洗牌
  66. def shuffledata(data):
  67. np.random.shuffle(data)
  68. cols = data.shape[1]
  69. X = data[:, 0:cols - 1]
  70. y = data[:, cols - 1:]
  71. return X, y
  72. import time
  73. def descent(data, theta, batchSize, stopType, thresh, alpha):
  74. # 梯度下降求解
  75. init_time = time.time()
  76. i = 0 # 迭代次数
  77. k = 0 # batch
  78. X, y = shuffledata(data)
  79. grad = np.zeros(theta.shape) # 计算的梯度
  80. costs = [cost(X, y, theta)] # 损失值
  81. while True:
  82. grad = gradient(X[k:k + batchSize], y[k:k + batchSize], theta)
  83. k += batchSize # 取batch数量个数据
  84. if k >= n:
  85. k = 0
  86. X, y = shuffledata(data) # 重新洗牌
  87. theta = theta - alpha * grad # 参数更新
  88. costs.append(cost(X, y, theta)) # 计算新的损失
  89. i += 1
  90. if stopType == STOP_ITER:
  91. value = i
  92. elif stopType == STOP_COST:
  93. value = costs
  94. elif stopType == STOP_GRAD:
  95. value = grad
  96. if stopCriterion(stopType, value, thresh): break
  97. return theta, i - 1, costs, grad, time.time() - init_time
  98. # 选择梯度下降
  99. def runExpe(data, theta, batchSize, stopType, thresh, alpha):
  100. # import pdb; pdb.set_trace();
  101. theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)
  102. name = "Original" if (data[:, 1] > 2).sum() > 1 else "Scaled"
  103. name += " data - learning rate: {} - ".format(alpha)
  104. if batchSize == n:
  105. strDescType = "Gradient"
  106. elif batchSize == 1:
  107. strDescType = "Stochastic"
  108. else:
  109. strDescType = "Mini-batch ({})".format(batchSize)
  110. name += strDescType + " descent - Stop: "
  111. if stopType == STOP_ITER:
  112. strStop = "{} iterations".format(thresh)
  113. elif stopType == STOP_COST:
  114. strStop = "costs change < {}".format(thresh)
  115. else:
  116. strStop = "gradient norm < {}".format(thresh)
  117. name += strStop
  118. print("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
  119. name, theta, iter, costs[-1], dur))
  120. fig, ax = plt.subplots(figsize=(12, 4))
  121. ax.plot(np.arange(len(costs)), costs, 'r')
  122. ax.set_xlabel('Iterations')
  123. ax.set_ylabel('Cost')
  124. ax.set_title(name.upper() + ' - Error vs. Iteration')
  125. return theta
  126. n = 100
  127. runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)
  128. plt.show()
  129. runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
  130. plt.show()
  131. runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
  132. plt.show()
  133. # 对比
  134. runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)
  135. plt.show()
  136. runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)
  137. plt.show()
  138. runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)
  139. plt.show()
  140. ##对数据进行标准化 将数据按其属性(按列进行)减去其均值,然后除以其方差。
  141. # 最后得到的结果是,对每个属性/每列来说所有数据都聚集在0附近,方差值为1
  142. from sklearn import preprocessing as pp
  143. scaled_data = orig_data.copy()
  144. scaled_data[:, 1:3] = pp.scale(orig_data[:, 1:3])
  145. runExpe(scaled_data, theta, n, STOP_ITER, thresh=5000, alpha=0.001)
  146. # 设定阈值
  147. def predict(X, theta):
  148. return [1 if x >= 0.5 else 0 for x in model(X, theta)]
  149. # if __name__=='__main__':
  150. scaled_X = scaled_data[:, :3]
  151. y = scaled_data[:, 3]
  152. predictions = predict(scaled_X, theta)
  153. correct = [1 if ((a == 1 and b == 1) or (a == 0 and b == 0)) else 0 for (a, b) in zip(predictions, y)]
  154. accuracy = (sum(map(int, correct)) % len(correct))
  155. print('accuracy = {0}%'.format(accuracy))

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/279293
推荐阅读
相关标签
  

闽ICP备14008679号