当前位置:   article > 正文

logit模型应用实例_逻辑斯谛回归模型

logit模型应用综述

8367e8ef2d4821b52fb70fd1f8f0835a.png

逻辑斯谛回归是统计学习中的经典分类方法,属于对数线性模型。

一、逻辑斯谛分布

是连续的随机变量,X服从逻辑斯谛分布是指X具有以下分布函数和概率密度函数:

分布函数:

密度函数:

其中

为位置参数,
为形状参数。逻辑斯谛函数是一个S型函数,当
的值越小,曲线在中心附近增长的越快。

二、逻辑斯谛回归模型

二项逻辑斯谛回归模型是一种分类模型,由条件概率

表示,随机变量
取值为实数,随机变量
取值为1或者0。模型由如下的条件概率分布表示:

其中,

为参数。

假设

,取值范围为
的取值范围为
。可以通过logit函数将
的范围映射到
,为

反求

当线性函数的值越接近正无穷,概率值就越接近1;线性函数的值越接近负无穷,概率值就接近0。这样的模型就是逻辑斯谛回归模型,也就是常说的逻辑回归模型。

三、参数估计

训练数据集

。使用极大似然函数估计模型的参数

似然函数为:

取对数:

求最大值,得到
的估计值。

四、代码实现

自编程实现:

  1. import numpy as np
  2. import time
  3. import matplotlib.pyplot as plt
  4. from mpl_toolkits.mplot3d import Axes3D
  5. plt.rcParams['font.sans-serif'] = ['SimHei'] # 正常显示中文标签
  6. plt.rcParams['axes.unicode_minus'] = False # 显示正负号
  7. class LogisticRegression:
  8. def __init__(self, learn_rate=0.1, max_iter=10000, tol=1e-2):
  9. self.learn_rate = learn_rate # 学习率
  10. self.max_iter = max_iter # 迭代次数
  11. self.tol = tol # 迭代停止阈值
  12. self.w = None # 权重
  13. def preprocessing(self, X):
  14. """ 将原始X末尾加上一列,该列数值全部为1 """
  15. row = X.shape[0]
  16. y = np.ones(row).reshape(row, 1)
  17. X_prepro = np.hstack((X, y))
  18. return X_prepro
  19. def sigmoid(self, x):
  20. return 1 / (1 + np.exp(-x))
  21. def fit(self, X_train, y_train):
  22. """ 训练模型 """
  23. # 处理数据
  24. X = self.preprocessing(X_train)
  25. y = y_train.T
  26. # 初始化权重
  27. self.w = np.array([[0] * X.shape[1]], dtype=np.float)
  28. k = 0
  29. for loop in range(self.max_iter):
  30. # 计算梯度
  31. z = np.dot(X, self.w.T)
  32. grad = X * (y - self.sigmoid(z))
  33. grad = grad.sum(axis=0)
  34. # 利用梯度的绝对值作为迭代中止的条件
  35. if (np.abs(grad) <= self.tol).all():
  36. break
  37. else:
  38. # 更新权重w,梯度上升求极大值
  39. self.w += self.learn_rate * grad
  40. k += 1
  41. print("迭代次数: {}次".format(k))
  42. print("最终梯度: {}".format(grad))
  43. print("最终权重: {}".format(self.w[0]))
  44. def predict(self, x):
  45. p = self.sigmoid(np.dot(self.preprocessing(x), self.w.T))
  46. #print("Y=1的概率估计为: {:.2%}".format(p[0][0]))
  47. p[np.where(p > 0.5)] = 1
  48. p[np.where(p < 0.5)] = 0
  49. return p
  50. def score(self, X, y):
  51. y_c = self.predict(X)
  52. # 错误率
  53. error_rate = np.sum(np.abs(y_c - y.T)) / y_c.shape[0]
  54. return 1 - error_rate
  55. def draw(self, X, y):
  56. # 分离正负实例点
  57. y = y[0]
  58. X_po = X[np.where(y == 1)]
  59. X_ne = X[np.where(y == 0)]
  60. # 绘制数据集散点图
  61. ax = plt.axes(projection='3d')
  62. x_1 = X_po[0, :]
  63. y_1 = X_po[1, :]
  64. z_1 = X_po[2, :]
  65. x_2 = X_ne[0, :]
  66. y_2 = X_ne[1, :]
  67. z_2 = X_ne[2, :]
  68. # 画图
  69. ax.scatter(x_1, y_1, z_1, c='r', label="正实例")
  70. ax.scatter(x_2, y_2, z_2, c='b', label="负实例")
  71. ax.legend(loc='best')
  72. # 绘制p=0.5的区分平面
  73. x = np.linspace(-3, 3, 3)
  74. y = np.linspace(-3, 3, 3)
  75. x_3, y_3 = np.meshgrid(x, y)
  76. a, b, c, d = self.w[0]
  77. z_3 = -(a*x_3+b*y_3+d) / c
  78. ax.plot_surface(x_3, y_3, z_3, alpha=0.5) # 调节透明度
  79. plt.show()
  80. def main():
  81. # 训练数据集
  82. X_train = np.array([
  83. [3, 3, 3],
  84. [4, 3, 2],
  85. [2, 1, 2],
  86. [1, 1, 1],
  87. [-1, 0, 1],
  88. [2, -2, 1],
  89. ])
  90. y_train = np.array([[1, 1, 1, 0, 0, 0]])
  91. # 实例化模型,进行训练
  92. clf = LogisticRegression()
  93. clf.fit(X_train, y_train)
  94. # 预测新数据
  95. X_new = np.array([[1, 2, -2]])
  96. y_predict = clf.predict(X_new)
  97. print("{}被分类为: {}".format(X_new[0], y_predict[0]))
  98. # 展示数据
  99. clf.draw(X_train, y_train)
  100. # 评价模型
  101. X_test = X_train
  102. y_test = y_train
  103. correct_rate = clf.score(X_test, y_test)
  104. print("共测试{}组数据,正确率: {:.2%}".format(X_test.shape[0], correct_rate))
  105. if __name__ == '__main__':
  106. main()

sklearn实现:

  1. from sklearn.linear_model import LogisticRegression
  2. import numpy as np
  3. # 训练数据集
  4. X_train = np.array([
  5. [3, 3, 3],
  6. [4, 3, 2],
  7. [2, 1, 2],
  8. [1, 1, 1],
  9. [-1, 0, 1],
  10. [2, -2, 1],
  11. ])
  12. y_train = np.array([1, 1, 1, 0, 0, 0])
  13. # 选择不同的求解器,实例化模型,进行训练和测试
  14. methods = ['liblinear', 'newton-cg', 'lbfgs', 'sag', 'saga']
  15. res = []
  16. X_new = np.array([[1, 2, -2]])
  17. for method in methods:
  18. # 实例化模型
  19. clf = LogisticRegression(solver=method, intercept_scaling=2, max_iter=1000)
  20. # 训练
  21. clf.fit(X_train, y_train)
  22. # 预测
  23. y_predict = clf.predict(X_new)
  24. # 利用训练数据,评价模型
  25. X_test = X_train
  26. y_test = y_train
  27. correct_rate = clf.score(X_test, y_test)
  28. # 保存结果
  29. res.append((y_predict, correct_rate))
  30. # 格式化输出
  31. methodes = ["liblinear", "newton-cg", "lbfgs ", "sag ", "saga "]
  32. print("solver选择: {}".format(" ".join(method for method in methodes)))
  33. print("{}被分类为: {}".format(X_new[0], " ".join(str(re[0]) for re in res)))
  34. print("测试{}组数据,正确率: {}".format(X_train.shape[0], " ".join(str(round(re[1], 1)) for re in res)))
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/989232
推荐阅读
相关标签
  

闽ICP备14008679号