• 逻辑回归Logistic


    回归 概念

    假设现在有一些数据点,我们用一条直线对这些点进行拟合(这条直线称为最佳拟合直线),这个拟合的过程就叫做回归。进而可以得到对这些点的拟合直线方程。

    最后结果用sigmoid函数输出\sigma (z)=\frac{1}{1+e^{-z}}

    因此,为了实现 Logistic 回归分类器,我们可以在每个特征上都乘以一个回归系数(如下公式所示),然后把所有结果值相加,将这个总和代入 Sigmoid 函数中,进而得到一个范围在 0~1 之间的数值。任何大于 0.5 的数据被分入 1 类,小于 0.5 即被归入 0 类。所以,Logistic 回归也是一种概率估计,比如这里Sigmoid 函数得出的值为0.5,可以理解为给定数据和参数,数据被分入 1 类的概率为0.5

    逻辑回归实际上就是一层神经网络

    sigmoid函数的输入

    z=w_{0}x_{0}+w_{1}x_{1}+w_{2}x_{2}+.....+w_{n}x_{n}

    梯度上升

    梯度=梯度值+梯度方向

    要找到某函数的最大值,最好的方法是沿着该函数的梯度方向探寻。如果梯度记为 ▽ ,则函数 f(x, y) 的梯度由下式表示:

    \triangledown f(x,y)=\begin{cases} \frac{\partial f(x,y)}{\partial x} & \text{ } \\ \frac{\partial f(x,y)}{\partial y} & \text{ } \end{cases}

    上式表示要沿x的方向移动\frac{\partial f(x,y)}{\partial x},沿y方向移动\frac{\partial f(x,y)}{\partial y}。其中,函数f(x,y)必须要在待计算的点上有定义并且可微。

    w=w+\alpha \bigtriangledown _{x}f(w)

    梯度下降和梯度上升:

    其实这个两个方法在此情况下本质上是相同的。关键在于代价函数(cost function)或者叫目标函数(objective function)。如果目标函数是损失函数,那就是最小化损失函数来求函数的最小值,就用梯度下降。 如果目标函数是似然函数(Likelihood function),就是要最大化似然函数来求函数的最大值,那就用梯度上升。在逻辑回归中, 损失函数和似然函数无非就是互为正负关系。

    只需要在迭代公式中的加法变成减法。因此,对应的公式可以写成w=w-\alpha \bigtriangledown _{x}f(w)

    1. from __future__ import print_function
    2. from numpy import *
    3. import matplotlib.pyplot as plt
    4. # ---------------------------------------------------------------------------
    5. # 使用 Logistic 回归在简单数据集上的分类
    6. # 解析数据
    7. def loadDataSet(file_name):
    8. '''
    9. Desc:
    10. 加载并解析数据
    11. Args:
    12. file_name -- 文件名称,要解析的文件所在磁盘位置
    13. Returns:
    14. dataMat -- 原始数据的特征
    15. labelMat -- 原始数据的标签,也就是每条样本对应的类别
    16. '''
    17. # dataMat为原始数据, labelMat为原始数据的标签
    18. dataMat = []
    19. labelMat = []
    20. fr = open(file_name)
    21. for line in fr.readlines():
    22. lineArr = line.strip().split()
    23. if len(lineArr) == 1:
    24. continue # 这里如果就一个空的元素,则跳过本次循环
    25. # 为了方便计算,我们将 X0 的值设为 1.0 ,也就是在每一行的开头添加一个 1.0 作为 X0
    26. dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
    27. labelMat.append(int(lineArr[2]))
    28. return dataMat, labelMat
    29. # sigmoid跳跃函数
    30. def sigmoid(inX):
    31. # return 1.0 / (1 + exp(-inX))
    32. # Tanh是Sigmoid的变形,与 sigmoid 不同的是,tanh 是0均值的。因此,实际应用中,tanh 会比 sigmoid 更好。
    33. return 2 * 1.0/(1+exp(-2*inX)) - 1
    34. # 正常的处理方案
    35. # 两个参数: 第一个参数==> dataMatIn 是一个2维NumPy数组,每列分别代表每个不同的特征,每行则代表每个训练样本。
    36. # 第二个参数==> classLabels 是类别标签,它是一个 1*100 的行向量。为了便于矩阵计算,需要将该行向量转换为列向量,做法是将原向量转置,再将它赋值给labelMat。
    37. def gradAscent(dataMatIn, classLabels):
    38. '''
    39. Desc:
    40. 正常的梯度上升法
    41. Args:
    42. dataMatIn -- 输入的 数据的特征 List
    43. classLabels -- 输入的数据的类别标签
    44. Returns:
    45. array(weights) -- 得到的最佳回归系数
    46. '''
    47. # 转化为矩阵[[1,1,2],[1,1,2]....]
    48. dataMatrix = mat(dataMatIn) # 转换为 NumPy 矩阵
    49. # 转化为矩阵[[0,1,0,1,0,1.....]],并转制[[0],[1],[0].....]
    50. # transpose() 行列转置函数
    51. # 将行向量转化为列向量 => 矩阵的转置
    52. labelMat = mat(classLabels).transpose() # 首先将数组转换为 NumPy 矩阵,然后再将行向量转置为列向量
    53. # m->数据量,样本数 n->特征数
    54. m, n = shape(dataMatrix)
    55. # print m, n, '__'*10, shape(dataMatrix.transpose()), '__'*100
    56. # alpha代表向目标移动的步长
    57. alpha = 0.001
    58. # 迭代次数
    59. maxCycles = 500
    60. # 生成一个长度和特征数相同的矩阵,此处n为3 -> [[1],[1],[1]]
    61. # weights 代表回归系数, 此处的 ones((n,1)) 创建一个长度和特征数相同的矩阵,其中的数全部都是 1
    62. weights = ones((n, 1))
    63. for k in range(maxCycles): # heavy on matrix operations
    64. # m*3 的矩阵 * 3*1 的单位矩阵 = m*1的矩阵
    65. # 那么乘上单位矩阵的意义,就代表: 通过公式得到的理论值
    66. # 参考地址: 矩阵乘法的本质是什么? https://www.zhihu.com/question/21351965/answer/31050145
    67. # print 'dataMatrix====', dataMatrix
    68. # print 'weights====', weights
    69. # n*3 * 3*1 = n*1
    70. h = sigmoid(dataMatrix * weights) # 矩阵乘法
    71. # print 'hhhhhhh====', h
    72. # labelMat是实际值
    73. error = (labelMat - h) # 向量相减
    74. # 0.001* (3*m)*(m*1) 表示在每一个列上的一个误差情况,最后得出 x1,x2,xn的系数的偏移量
    75. weights = weights + alpha * dataMatrix.transpose() * error # 矩阵乘法,最后得到回归系数
    76. return array(weights)
    77. # 随机梯度下降
    78. # 梯度下降优化算法在每次更新数据集时都需要遍历整个数据集,计算复杂都较高
    79. # 随机梯度下降一次只用一个样本点来更新回归系数
    80. def stocGradAscent0(dataMatrix, classLabels):
    81. '''
    82. Desc:
    83. 随机梯度下降,只使用一个样本点来更新回归系数
    84. Args:
    85. dataMatrix -- 输入数据的数据特征(除去最后一列)
    86. classLabels -- 输入数据的类别标签(最后一列数据)
    87. Returns:
    88. weights -- 得到的最佳回归系数
    89. '''
    90. m, n = shape(dataMatrix)
    91. alpha = 0.01
    92. # n*1的矩阵
    93. # 函数ones创建一个全1的数组
    94. weights = ones(n) # 初始化长度为n的数组,元素全部为 1
    95. for i in range(m):
    96. # sum(dataMatrix[i]*weights)为了求 f(x)的值, f(x)=a1*x1+b2*x2+..+nn*xn,此处求出的 h 是一个具体的数值,而不是一个矩阵
    97. h = sigmoid(sum(dataMatrix[i] * weights))
    98. # print 'dataMatrix[i]===', dataMatrix[i]
    99. # 计算真实类别与预测类别之间的差值,然后按照该差值调整回归系数
    100. error = classLabels[i] - h
    101. # 0.01*(1*1)*(1*n)
    102. # print weights, "*" * 10, dataMatrix[i], "*" * 10, error
    103. weights = weights + alpha * error * dataMatrix[i]
    104. return weights
    105. # 随机梯度下降算法(随机化)
    106. def stocGradAscent1(dataMatrix, classLabels, numIter=150):
    107. '''
    108. Desc:
    109. 改进版的随机梯度下降,使用随机的一个样本来更新回归系数
    110. Args:
    111. dataMatrix -- 输入数据的数据特征(除去最后一列数据)
    112. classLabels -- 输入数据的类别标签(最后一列数据)
    113. numIter=150 -- 迭代次数
    114. Returns:
    115. weights -- 得到的最佳回归系数
    116. '''
    117. m, n = shape(dataMatrix)
    118. weights = ones(n) # 创建与列数相同的矩阵的系数矩阵,所有的元素都是1
    119. # 随机梯度, 循环150,观察是否收敛
    120. for j in range(numIter):
    121. # [0, 1, 2 .. m-1]
    122. dataIndex = range(m)
    123. for i in range(m):
    124. # i和j的不断增大,导致alpha的值不断减少,但是不为0
    125. alpha = 4 / (
    126. 1.0 + j + i
    127. ) + 0.0001 # alpha 会随着迭代不断减小,但永远不会减小到0,因为后边还有一个常数项0.0001
    128. # 随机产生一个 0~len()之间的一个值
    129. # random.uniform(x, y) 方法将随机生成下一个实数,它在[x,y]范围内,x是这个范围内的最小值,y是这个范围内的最大值。
    130. randIndex = int(random.uniform(0, len(dataIndex)))
    131. # sum(dataMatrix[i]*weights)为了求 f(x)的值, f(x)=a1*x1+b2*x2+..+nn*xn
    132. h = sigmoid(sum(dataMatrix[dataIndex[randIndex]] * weights))
    133. error = classLabels[dataIndex[randIndex]] - h
    134. # print weights, '__h=%s' % h, '__'*20, alpha, '__'*20, error, '__'*20, dataMatrix[randIndex]
    135. weights = weights + alpha * error * dataMatrix[dataIndex[randIndex]]
    136. del (dataIndex[randIndex])
    137. return weights
    138. # 可视化展示
    139. def plotBestFit(dataArr, labelMat, weights):
    140. '''
    141. Desc:
    142. 将我们得到的数据可视化展示出来
    143. Args:
    144. dataArr:样本数据的特征
    145. labelMat:样本数据的类别标签,即目标变量
    146. weights:回归系数
    147. Returns:
    148. None
    149. '''
    150. n = shape(dataArr)[0]
    151. xcord1 = []
    152. ycord1 = []
    153. xcord2 = []
    154. ycord2 = []
    155. for i in range(n):
    156. if int(labelMat[i]) == 1:
    157. xcord1.append(dataArr[i, 1])
    158. ycord1.append(dataArr[i, 2])
    159. else:
    160. xcord2.append(dataArr[i, 1])
    161. ycord2.append(dataArr[i, 2])
    162. fig = plt.figure()
    163. ax = fig.add_subplot(111)
    164. ax.scatter(xcord1, ycord1, s=30, c='red', marker='s')
    165. ax.scatter(xcord2, ycord2, s=30, c='green')
    166. x = arange(-3.0, 3.0, 0.1)
    167. """
    168. y的由来,卧槽,是不是没看懂?
    169. 首先理论上是这个样子的。
    170. dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])])
    171. w0*x0+w1*x1+w2*x2=f(x)
    172. x0最开始就设置为1叻, x2就是我们画图的y值,而f(x)被我们磨合误差给算到w0,w1,w2身上去了
    173. 所以: w0+w1*x+w2*y=0 => y = (-w0-w1*x)/w2
    174. """
    175. y = (-weights[0] - weights[1] * x) / weights[2]
    176. ax.plot(x, y)
    177. plt.xlabel('X')
    178. plt.ylabel('Y')
    179. plt.show()
    180. def simpleTest():
    181. # 1.收集并准备数据
    182. dataMat, labelMat = loadDataSet("data/5.Logistic/TestSet.txt")
    183. # print dataMat, '---\n', labelMat
    184. # 2.训练模型, f(x)=a1*x1+b2*x2+..+nn*xn中 (a1,b2, .., nn).T的矩阵值
    185. # 因为数组没有是复制n份, array的乘法就是乘法
    186. dataArr = array(dataMat)
    187. # print dataArr
    188. # weights = gradAscent(dataArr, labelMat)
    189. # weights = stocGradAscent0(dataArr, labelMat)
    190. weights = stocGradAscent1(dataArr, labelMat)
    191. # print '*'*30, weights
    192. # 数据可视化
    193. plotBestFit(dataArr, labelMat, weights)
    1. # --------------------------------------------------------------------------------
    2. # 从疝气病症预测病马的死亡率
    3. # 分类函数,根据回归系数和特征向量来计算 Sigmoid的值
    4. def classifyVector(inX, weights):
    5. '''
    6. Desc:
    7. 最终的分类函数,根据回归系数和特征向量来计算 Sigmoid 的值,大于0.5函数返回1,否则返回0
    8. Args:
    9. inX -- 特征向量,features
    10. weights -- 根据梯度下降/随机梯度下降 计算得到的回归系数
    11. Returns:
    12. 如果 prob 计算大于 0.5 函数返回 1
    13. 否则返回 0
    14. '''
    15. prob = sigmoid(sum(inX * weights))
    16. if prob > 0.5: return 1.0
    17. else: return 0.0
    18. # 打开测试集和训练集,并对数据进行格式化处理
    19. def colicTest():
    20. '''
    21. Desc:
    22. 打开测试集和训练集,并对数据进行格式化处理
    23. Args:
    24. None
    25. Returns:
    26. errorRate -- 分类错误率
    27. '''
    28. frTrain = open('data/5.Logistic/horseColicTraining.txt')
    29. frTest = open('data/5.Logistic/horseColicTest.txt')
    30. trainingSet = []
    31. trainingLabels = []
    32. # 解析训练数据集中的数据特征和Labels
    33. # trainingSet 中存储训练数据集的特征,trainingLabels 存储训练数据集的样本对应的分类标签
    34. for line in frTrain.readlines():
    35. currLine = line.strip().split('\t')
    36. lineArr = []
    37. for i in range(21):
    38. lineArr.append(float(currLine[i]))
    39. trainingSet.append(lineArr)
    40. trainingLabels.append(float(currLine[21]))
    41. # 使用 改进后的 随机梯度下降算法 求得在此数据集上的最佳回归系数 trainWeights
    42. trainWeights = stocGradAscent1(array(trainingSet), trainingLabels, 500)
    43. # trainWeights = stocGradAscent0(array(trainingSet), trainingLabels)
    44. errorCount = 0
    45. numTestVec = 0.0
    46. # 读取 测试数据集 进行测试,计算分类错误的样本条数和最终的错误率
    47. for line in frTest.readlines():
    48. numTestVec += 1.0
    49. currLine = line.strip().split('\t')
    50. lineArr = []
    51. for i in range(21):
    52. lineArr.append(float(currLine[i]))
    53. if int(classifyVector(array(lineArr), trainWeights)) != int(
    54. currLine[21]):
    55. errorCount += 1
    56. errorRate = (float(errorCount) / numTestVec)
    57. print("the error rate of this test is: %f" % errorRate)
    58. return errorRate
    59. # 调用 colicTest() 10次并求结果的平均值
    60. def multiTest():
    61. numTests = 10
    62. errorSum = 0.0
    63. for k in range(numTests):
    64. errorSum += colicTest()
    65. print("after %d iterations the average error rate is: %f" % (numTests, errorSum / float(numTests)))
    66. simpleTest()
    67. # multiTest()

     

    1. # 逻辑回归中的 L1 惩罚和稀缺性 L1 Penalty and Sparsity in Logistic Regression
    2. print(__doc__)
    3. import numpy as np
    4. import matplotlib.pyplot as plt
    5. from sklearn.linear_model import LogisticRegression
    6. from sklearn import datasets
    7. from sklearn.preprocessing import StandardScaler
    8. digits = datasets.load_digits()
    9. X, y = digits.data, digits.target
    10. X = StandardScaler().fit_transform(X)
    11. # 将大小数字分类为小
    12. y = (y > 4).astype(np.int)
    13. # 设置正则化参数
    14. for i, C in enumerate((100, 1, 0.01)):
    15. # 减少训练时间短的容忍度
    16. clf_l1_LR = LogisticRegression(C=C, penalty='l1', tol=0.01)
    17. clf_l2_LR = LogisticRegression(C=C, penalty='l2', tol=0.01)
    18. clf_l1_LR.fit(X, y)
    19. clf_l2_LR.fit(X, y)
    20. coef_l1_LR = clf_l1_LR.coef_.ravel()
    21. coef_l2_LR = clf_l2_LR.coef_.ravel()
    22. # coef_l1_LR contains zeros due to the
    23. # L1 sparsity inducing norm
    24. # 由于 L1 稀疏诱导规范,coef_l1_LR 包含零
    25. sparsity_l1_LR = np.mean(coef_l1_LR == 0) * 100
    26. sparsity_l2_LR = np.mean(coef_l2_LR == 0) * 100
    27. print("C=%.2f" % C)
    28. print("Sparsity with L1 penalty: %.2f%%" % sparsity_l1_LR)
    29. print("score with L1 penalty: %.4f" % clf_l1_LR.score(X, y))
    30. print("Sparsity with L2 penalty: %.2f%%" % sparsity_l2_LR)
    31. print("score with L2 penalty: %.4f" % clf_l2_LR.score(X, y))
    32. l1_plot = plt.subplot(3, 2, 2 * i + 1)
    33. l2_plot = plt.subplot(3, 2, 2 * (i + 1))
    34. if i == 0:
    35. l1_plot.set_title("L1 penalty")
    36. l2_plot.set_title("L2 penalty")
    37. l1_plot.imshow(np.abs(coef_l1_LR.reshape(8, 8)), interpolation='nearest',
    38. cmap='binary', vmax=1, vmin=0)
    39. l2_plot.imshow(np.abs(coef_l2_LR.reshape(8, 8)), interpolation='nearest',
    40. cmap='binary', vmax=1, vmin=0)
    41. plt.text(-8, 3, "C = %.2f" % C)
    42. l1_plot.set_xticks(())
    43. l1_plot.set_yticks(())
    44. l2_plot.set_xticks(())
    45. l2_plot.set_yticks(())
    46. plt.show()
    47. # 具有 L1-逻辑回归的路径
    48. from datetime import datetime
    49. import numpy as np
    50. import matplotlib.pyplot as plt
    51. from sklearn import linear_model
    52. from sklearn import datasets
    53. from sklearn.svm import l1_min_c
    54. iris = datasets.load_iris()
    55. X = iris.data
    56. y = iris.target
    57. X = X[y != 2]
    58. y = y[y != 2]
    59. X -= np.mean(X, 0)
    60. cs = l1_min_c(X, y, loss='log') * np.logspace(0, 3)
    61. print("Computing regularization path ...")
    62. start = datetime.now()
    63. clf = linear_model.LogisticRegression(C=1.0, penalty='l1', tol=1e-6)
    64. coefs_ = []
    65. for c in cs:
    66. clf.set_params(C=c)
    67. clf.fit(X, y)
    68. coefs_.append(clf.coef_.ravel().copy())
    69. print("This took ", datetime.now() - start)
    70. coefs_ = np.array(coefs_)
    71. plt.plot(np.log10(cs), coefs_)
    72. ymin, ymax = plt.ylim()
    73. plt.xlabel('log(C)')
    74. plt.ylabel('Coefficients')
    75. plt.title('Logistic Regression Path')
    76. plt.axis('tight')
    77. plt.show()
    78. # 绘制多项式和一对二的逻辑回归 Plot multinomial and One-vs-Rest Logistic Regression
    79. print(__doc__)
    80. import numpy as np
    81. import matplotlib.pyplot as plt
    82. from sklearn.datasets import make_blobs
    83. from sklearn.linear_model import LogisticRegression
    84. # 制作 3 类数据集进行分类
    85. centers = [[-5, 0], [0, 1.5], [5, -1]]
    86. X, y = make_blobs(n_samples=1000, centers=centers, random_state=40)
    87. transformation = [[0.4, 0.2], [-0.4, 1.2]]
    88. X = np.dot(X, transformation)
    89. for multi_class in ('multinomial', 'ovr'):
    90. clf = LogisticRegression(solver='sag', max_iter=100, random_state=42,
    91. multi_class=multi_class).fit(X, y)
    92. # 打印训练分数
    93. print("training score : %.3f (%s)" % (clf.score(X, y), multi_class))
    94. # 创建一个网格来绘制
    95. h = .02 # 网格中的步长
    96. x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    97. y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    98. xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
    99. np.arange(y_min, y_max, h))
    100. # 绘制决策边界。为此,我们将为网格 [x_min, x_max]x[y_min, y_max]中的每个点分配一个颜色。
    101. Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
    102. # 将结果放入彩色图
    103. Z = Z.reshape(xx.shape)
    104. plt.figure()
    105. plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
    106. plt.title("Decision surface of LogisticRegression (%s)" % multi_class)
    107. plt.axis('tight')
    108. # 将训练点也绘制进入
    109. colors = "bry"
    110. for i, color in zip(clf.classes_, colors):
    111. idx = np.where(y == i)
    112. plt.scatter(X[idx, 0], X[idx, 1], c=color, cmap=plt.cm.Paired)
    113. # 绘制三个一对数分类器
    114. xmin, xmax = plt.xlim()
    115. ymin, ymax = plt.ylim()
    116. coef = clf.coef_
    117. intercept = clf.intercept_
    118. def plot_hyperplane(c, color):
    119. def line(x0):
    120. return (-(x0 * coef[c, 0]) - intercept[c]) / coef[c, 1]
    121. plt.plot([xmin, xmax], [line(xmin), line(xmax)],
    122. ls="--", color=color)
    123. for i, color in zip(clf.classes_, colors):
    124. plot_hyperplane(i, color)
    125. plt.show()
    126. from __future__ import print_function
    127. # Logistic Regression 3-class Classifier 逻辑回归 3-类 分类器
    128. print(__doc__)
    129. import numpy as np
    130. import matplotlib.pyplot as plt
    131. from sklearn import linear_model, datasets
    132. # 引入一些数据来玩
    133. iris = datasets.load_iris()
    134. # 我们只采用样本数据的前两个feature
    135. X = iris.data[:, :2]
    136. Y = iris.target
    137. h = .02 # 网格中的步长
    138. logreg = linear_model.LogisticRegression(C=1e5)
    139. # 我们创建了一个 Neighbours Classifier 的实例,并拟合数据。
    140. logreg.fit(X, Y)
    141. # 绘制决策边界。为此我们将为网格 [x_min, x_max]x[y_min, y_max] 中的每个点分配一个颜色。
    142. x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    143. y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    144. xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    145. Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])
    146. # 将结果放入彩色图中
    147. Z = Z.reshape(xx.shape)
    148. plt.figure(1, figsize=(4, 3))
    149. plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
    150. # 将训练点也同样放入彩色图中
    151. plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
    152. plt.xlabel('Sepal length')
    153. plt.ylabel('Sepal width')
    154. plt.xlim(xx.min(), xx.max())
    155. plt.ylim(yy.min(), yy.max())
    156. plt.xticks(())
    157. plt.yticks(())
    158. plt.show()
    159. # Logistic function 逻辑回归函数
    160. # 这个类似于咱们之前讲解 logistic 回归的 Sigmoid 函数,模拟的阶跃函数
    161. print(__doc__)
    162. import numpy as np
    163. import matplotlib.pyplot as plt
    164. from sklearn import linear_model
    165. # 这是我们的测试集,它只是一条直线,带有一些高斯噪声。
    166. xmin, xmax = -5, 5
    167. n_samples = 100
    168. np.random.seed(0)
    169. X = np.random.normal(size=n_samples)
    170. y = (X > 0).astype(np.float)
    171. X[X > 0] *= 4
    172. X += .3 * np.random.normal(size=n_samples)
    173. X = X[:, np.newaxis]
    174. # 运行分类器
    175. clf = linear_model.LogisticRegression(C=1e5)
    176. clf.fit(X, y)
    177. # 并且画出我们的结果
    178. plt.figure(1, figsize=(4, 3))
    179. plt.clf()
    180. plt.scatter(X.ravel(), y, color='black', zorder=20)
    181. X_test = np.linspace(-5, 10, 300)
    182. def model(x):
    183. return 1 / (1 + np.exp(-x))
    184. loss = model(X_test * clf.coef_ + clf.intercept_).ravel()
    185. plt.plot(X_test, loss, color='red', linewidth=3)
    186. ols = linear_model.LinearRegression()
    187. ols.fit(X, y)
    188. plt.plot(X_test, ols.coef_ * X_test + ols.intercept_, linewidth=1)
    189. plt.axhline(.5, color='.5')
    190. plt.ylabel('y')
    191. plt.xlabel('X')
    192. plt.xticks(range(-5, 10))
    193. plt.yticks([0, 0.5, 1])
    194. plt.ylim(-.25, 1.25)
    195. plt.xlim(-4, 10)
    196. plt.legend(('Logistic Regression Model', 'Linear Regression Model'),
    197. loc="lower right", fontsize='small')
    198. plt.show()

  • 相关阅读:
    悲观模式下分库分表合并迁移
    网络工程师的关键任务:构建可靠的出海网络架构
    nginx几个常见的配置项
    【Oracle】Oracle系列之八--SQL查询
    CEC2018:动态多目标测试函数DF6~DF9的PS及PF
    【SSM框架 三】SpringMVC
    Windows11安装SQL Server2019操作手册
    Python编程 列表的操作(上)
    【无标题】
    ES6-解构赋值
  • 原文地址:https://blog.csdn.net/qq_36973725/article/details/132627315