政策资讯

Policy Information


ML之LoR:LoR之二分类之线性决策算法实现根据两课成绩分数~预测期末通过率(合格还是不合格)

来源: 重庆市软件正版化服务中心    |    时间: 2022-09-19    |    浏览量: 48399    |   

ML之LoR:LoR之二分类之线性决策算法实现根据两课成绩分数~预测期末通过率(合格还是不合格)

目录

输出结果

代码设计


输出结果

LoR之二分类算法实现预测期末考试成绩合格还是不合格

LoR回归函数

代码设计

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib as mpl
  4. import matplotlib.pyplot as plt
  5. from scipy.optimize import minimize
  6. from sklearn.preprocessing import PolynomialFeatures
  7. pd.set_option('display.notebook_repr_html', False)
  8. pd.set_option('display.max_columns', None)
  9. pd.set_option('display.max_rows', 150)
  10. pd.set_option('display.max_seq_items', None)
  11. import seaborn as sns
  12. sns.set_context('notebook')
  13. sns.set_style('white')
  14. def loaddata(file, delimeter):
  15. data = np.loadtxt(file, delimiter=delimeter)
  16. print('Dimensions: ',data.shape)
  17. print(data[1:6,:])
  18. return(data)
  19. def plotData(data, label_x, label_y, label_pos, label_neg, axes=None):
  20. 获得正负样本的下标(即哪些是正样本,哪些是负样本)
  21. neg = data[:,2] == 0
  22. pos = data[:,2] == 1
  23. if axes == None:
  24. axes = plt.gca()
  25. axes.scatter(data[pos][:,0], data[pos][:,1], marker='^', c='b', s=60, linewidth=2, label=label_pos)
  26. axes.scatter(data[neg][:,0], data[neg][:,1], c='y', s=60, label=label_neg)
  27. axes.set_xlabel(label_x)
  28. axes.set_ylabel(label_y)
  29. axes.legend(frameon= True, fancybox = True);
  30. data = loaddata('data1.txt', ',')
  31. X = np.c_[np.ones((data.shape[0],1)), data[:,0:2]]
  32. y = np.c_[data[:,2]]
  33. plotData(data, 'Exam 1 score', 'Exam 2 score', 'Pass', 'Fail') 绘图
  34. 定义sigmoid函数
  35. def sigmoid(z):
  36. return(1 / (1 + np.exp(-z)))
  37. 定义损失函数
  38. def costFunction(theta, X, y):
  39. m = y.size
  40. h = sigmoid(X.dot(theta))
  41. J = -1*(1/m)*(np.log(h).T.dot(y)+np.log(1-h).T.dot(1-y))
  42. if np.isnan(J[0]):
  43. return(np.inf)
  44. return(J[0])
  45. 求解梯度
  46. def gradient(theta, X, y):
  47. m = y.size
  48. h = sigmoid(X.dot(theta.reshape(-1,1)))
  49. grad =(1/m)*X.T.dot(h-y)
  50. return(grad.flatten())
  51. initial_theta = np.zeros(X.shape[1])
  52. cost = costFunction(initial_theta, X, y)
  53. grad = gradient(initial_theta, X, y)
  54. print('Cost: \n', cost)
  55. print('Grad: \n', grad)
  56. 最小化损失函数(梯度下降),直接调用scipy里面的最小化损失函数的minimize函数
  57. res = minimize(costFunction, initial_theta, args=(X,y), method=None, jac=gradient, options={'maxiter':400})
  58. 进行预测
  59. def predict(theta, X, threshold=0.5):
  60. p = sigmoid(X.dot(theta.T)) >= threshold
  61. return(p.astype('int'))
  62. 第一门课45分,第二门课85分的同学,拿到通过考试的概率
  63. sigmoid(np.array([1, 45, 85]).dot(res.x.T))
  64. p = predict(res.x, X)
  65. print('Train accuracy {}%'.format(100*sum(p == y.ravel())/p.size))
  66. 绘制二分类决策边界
  67. plt.scatter(45, 85, s=60, c='r', marker='v', label='(45, 85)')
  68. plotData(data, 'Exam 1 score', 'Exam 2 score', 'Pass', 'Failed')
  69. x1_min, x1_max = X[:,1].min(), X[:,1].max(),
  70. x2_min, x2_max = X[:,2].min(), X[:,2].max(),
  71. xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
  72. h = sigmoid(np.c_[np.ones((xx1.ravel().shape[0],1)), xx1.ravel(), xx2.ravel()].dot(res.x))
  73. h = h.reshape(xx1.shape)
  74. plt.contour(xx1, xx2, h, [0.5], linewidths=1, colors='b');


 

评论

产品推荐

更多 >

QQ咨询 扫一扫加入群聊,了解更多平台咨询
微信咨询 扫一扫加入群聊,了解更多平台咨询
意见反馈
立即提交
QQ咨询
微信咨询
意见反馈