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


zuomeng
你来替我做个梦 2022-09-19 16:59:51 48819
分类专栏: 资讯

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');


 

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=3733
赞同 0
评论 0 条
你来替我做个梦L0
粉丝 0 发表 9 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2950
【软件正版化】软件正版化工作要点  2872
统信UOS试玩黑神话:悟空  2833
信刻光盘安全隔离与信息交换系统  2728
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1261
grub引导程序无法找到指定设备和分区  1226
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  165
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  163
点击报名 | 京东2025校招进校行程预告  163
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  159
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
如何玩转信创开放社区—从小白进阶到专家 15
信创开放社区邀请他人注册的具体步骤如下 15
方德桌面操作系统 14
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
我有15积分有什么用? 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!