逻辑回归疑惑y=-(w0+w1*x1)/w2

本文介绍了基于Logistic回归和sigmoid函数的分类方法,通过最优化方法确定最佳回归系数,包括梯度上升法和随机梯度上升算法。还给出从疝气病症预测病马死亡率的示例,介绍了处理数据缺失值的方法,最后总结了Logistic回归的优缺点及适用数据类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

https://blog.youkuaiyun.com/u010454729/article/details/48274955

5.1 基于Logistic回归和sigmoid函数的分类

实现Logistic回归分类器:在每个特征上都乘以一个回归系数,然后把所有的结果值相加,总和带入sigmoid函数,其结果大于0.5分为第0类,结果小于0.5分为第0类。

sigmoid函数公式:

Figure 5-1: sigmoid函数公式

 

Figure 5-2: sigmoid曲线

sigmoid函数具有很好的性质,如其导数可以用其本身表示等等。

5.2 基于最优化方法的最佳回归系数确定

sigmoid函数输入z:

其可以写成z=w.T*x,向量x为分类器的输入数据, w为训练器寻找的最佳参数。

梯度上升法:

思想:要找到某函数的最大值,最好的方法是沿着该函数的梯度方向探寻。

函数f(x,y)的梯度:

沿x的方向移动,沿y的方向移动,最后能够到达最优点,但是f(x,y)在待计算点需要有定义并且可微。

梯度算子总是指向函数值增长最快的方向。移动方向为梯度方向,移动量大小需要乘以一个参数,称之为步长。参数迭代公式为:

公式可一直执行,直到某个条件停止为止。如迭代次数或者算法达到某个可以允许的误差范围。

训练算法:使用梯度上升找到最佳参数

梯度上升法伪代码:

数据点:

算法:

 
  1. def loadDataSet():

  2. dataMat = []

  3. labelMat = []

  4. fr = open("testSet.txt")

  5. for line in fr.readlines():

  6. lineArr = line.strip().split("\t")

  7. dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) #对应三个参数,第一个对应着常熟

  8. labelMat.append(int(lineArr[2]))

  9. return dataMat, labelMat

  10.  
  11. def sigmoid(inX):

  12. return 1.0/(1+exp(-inX))

  13.  
  14. def gradAscent(dataMatIn, classLabels):

  15. '''Logistic回归梯度上升优化算法'''

  16. dataMatrix = mat(dataMatIn) #100行3列

  17. labelMat = mat(classLabels).transpose() #transpose()将1行100列的矩阵转为100行1列mat(classLabels).T也可破

  18. m,n = shape(dataMatrix) #m=100,n=3

  19. alpha = 0.001

  20. maxCycles = 500

  21. weights = ones((n,1)) #100行1列

  22. for k in range(maxCycles):

  23. h = sigmoid(dataMatrix*weights) #dataMatrix*weights,100×3和3×1的矩阵相乘,得到100×1的矩阵

  24. error = (labelMat - h)

  25. weights = weights + alpha*dataMatrix.transpose()*error

  26. return weights

  27. dataMat, labelMat = loadDataSet()

  28. weights = gradAscent(dataMat, labelMat)

  29. print weights

 

Figure5-4: 算法参数

分析数据:画出决策边界

上一步确定了回归系数,确定了不同类别数据之间的分割线。这一步画出分割线:

 
  1. def plotBestFit(weights):

  2. dataMat, labelMat = loadDataSet()

  3. dataArr = array(dataMat) #将每个数据点的x,y坐标存为矩阵的形式

  4. n = shape(dataArr)[0] #取其行数,也即数据点的个数

  5. #======画数据点

  6. xcord1 = []

  7. ycord1 = []

  8. xcord2 = []

  9. ycord2 = []

  10. for i in range(n):

  11. if int(labelMat[i]) == 1: #若是正例,存到(x1,y1)中

  12. xcord1.append(dataArr[i,1])

  13. ycord1.append(dataArr[i,2])

  14. else:

  15. xcord2.append(dataArr[i,1])

  16. ycord2.append(dataArr[i,2])

  17. fig = plt.figure()

  18. ax = fig.add_subplot(111)

  19. ax.scatter(xcord1,ycord1,s=30,c="red",marker = "s")

  20. ax.scatter(xcord2,ycord2,s=30,c="green")

  21. #============

  22. x = arange(-3.0,3.0,0.1) #x为numpy.arange格式,并且以0.1为步长从-3.0到3.0切分。

  23. #拟合曲线为0 = w0*x0+w1*x1+w2*x2, 故x2 = (-w0*x0-w1*x1)/w2, x0为1,x1为x, x2为y,故有

  24. y = (-weights[0] - weights[1]*x)/weights[2]

  25. #x为array格式,weights为matrix格式,故需要调用getA()方法,其将matrix()格式矩阵转为array()格式

  26. ax.plot(x,y)

  27. plt.xlabel("X1")

  28. plt.ylabel("X2")

  29. plt.show()

  30. dataMat, labelMat = loadDataSet()

  31. weights = gradAscent(dataMat, labelMat)

  32. #getA()方法,其将matrix()格式矩阵转为array()格式,type(weights),type(weights.getA())可观察到。

  33. plotBestFit(weights.getA())

 

Figure 5-5: 分割线

训练算法:随机梯度上升

梯度上升算法中,每次更新回归系数需要遍历整个数据集。数据量若是大了,计算复杂度较高。

改进方法:一次仅用一个样本点更新回归系数,这便是随机梯度上升算法。

伪代码:

代码:

 

 
  1. def stocGradAscent0(dataMatrix, classLabels):

  2. '''随机梯度上升算法'''

  3. m,n = shape(dataMatrix)

  4. alpha = 0.01

  5. weights = ones(n)

  6. for i in range(m):

  7. h = sigmoid(sum(dataMatrix[i]*weights)) #此处h为具体数值

  8. error = classLabels[i] - h #error也为具体数值

  9. weights = weights + alpha*error*dataMatrix[i] #每次对一个样本进行处理,更新权值

  10. return weights

  11. dataArr, labelMat = loadDataSet()

  12. weights = stocGradAscent0(array(dataArr), labelMat)

  13. plotBestFit(weights)

 

Figure 5-6: 随机梯度上升算法分割线

结果显示其效果还不如梯度上升算法,不过不一样,梯度上升算法,500次迭代每次都用上了所有数据,而随机梯度上升算法总共也只用了500次。需要对其进行改进:

 

 
  1. def stocGradAscent1(dataMatrix, classLabels, numIter=150):

  2. '''改进的随机梯度上升算法,收敛得更快'''

  3. m,n = shape(dataMatrix)

  4. weights = ones(n)

  5.  
  6. for j in range(numIter):

  7. dataIndex = range(m)

  8. for i in range(m):

  9. alpha = 4/(1.0+i+j)+0.0001 #alpha迭代次数不断变小,1.非严格下降,2.不会到0

  10. #随机选取样本更新系数weights,每次随机从列表中选取一个值,用过后删除它再进行下一次迭代

  11. randIndex = int(random.uniform(0, len(dataIndex)))#每次迭代改变dataIndex,而m是不变的,故不用unifor(0, m)

  12. h = sigmoid(sum(dataMatrix[randIndex]*weights))

  13. error = classLabels[randIndex] - h

  14. weights = weights + alpha*error*dataMatrix[randIndex]

  15. del(dataIndex[randIndex])

  16. return weights

  17.  
  18. dataArr, labelMat = loadDataSet()

  19. weights = stocGradAscent1(array(dataArr), labelMat)

  20. plotBestFit(weights)

Figure 5-7: 改进的随机梯度上升算法分割线

5.3 示例:从疝气病症预测病马的死亡率

准备数据:处理数据中的缺失值

可选做法:

 

  • 使用可用特征的均值来填补缺失值
  • 使用特殊值来填补缺失值,如-1
  • 忽略有缺失值的样本
  • 使用相似样本的均值添补缺失值
  • 使用另外的机器学习算法预测缺失值

 

数据挖掘软件clementine几乎可以做以上数据预处理的工作。可破有问题的数据。

数据:

 

Figure 5-8: train data

 

Figure 5-9: test data

测试算法:用Logistic回归进行分类

 

 
  1. def colicTest():

  2. frTrain = open("horseColicTraining.txt")

  3. frTest = open("horseColicTest.txt")

  4. #==========训练数据准备

  5. trainingSet = []

  6. trainingLabels = []

  7. for line in frTrain.readlines():

  8. currLine = line.strip().split("\t")

  9. lineArr = []

  10. for i in range(21):

  11. lineArr.append(float(currLine[i]))

  12. trainingSet.append(lineArr)

  13. trainingLabels.append(float(currLine[21]))

  14. #==========

  15. trainWeights = stocGradAscent1(array(trainingSet), trainingLabels, 500) #进行500次迭代,计算权重

  16. errorCount = 0

  17. numTestVec = 0.0

  18. #========准备测试集并进行测试计算错误率

  19. for line in frTest.readlines():

  20. numTestVec +=1.0

  21. currLine = line.strip().split("\t")

  22. lineArr = []

  23. for i in range(21):

  24. lineArr.append(float(currLine[i]))

  25. if int(classifyVector(array(lineArr), trainWeights)) != int(currLine[21]):

  26. errorCount +=1

  27. errorRate = (float(errorCount)/numTestVec)

  28. #=======

  29. print "the error rate of this test is: %f" % errorRate

  30. return errorRate

  31.  
  32. def multiTest(): #多次测试

  33. numTests = 10

  34. errorSum = 0.0

  35. for k in range(numTests):

  36. errorSum += colicTest()

  37. print "after %s iterations the average error rate is: %f " % (numTests, errorSum/float(numTests))

Figure 5-10: 测试结果

 

5.4 小结

Logistic回归:

优点: 计算代价不高,易于理解和实现。

缺点: 容易欠拟合,分类精度可能不高。

适用数据类型:数值型和标称型数据。

def bbox_ttdiou_v3(box1, box2, xywh=True, eps=1e-7, alpha=0.25, beta=1.2, gamma=0.3, delta=0.1): """ TTDIoU v3: 平衡高低IoU阈值性能 改进点: 1. 降低高IoU梯度增强强度 2. 优化形状惩罚应用条件 3. 引入边界框紧密度惩罚 4. 动态调整中心点权重策略 """ # 坐标转换(保持不变) if xywh: (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1) w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2 b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_ else: b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1) b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1) w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 # 计算交集和并集(保持不变) inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0) union = w1 * h1 + w2 * h2 - inter + eps iou = inter / union # 中心点计算(保持不变) b1_cx, b1_cy = (b1_x1 + b1_x2) / 2, (b1_y1 + b1_y2) / 2 b2_cx, b2_cy = (b2_x1 + b2_x2) / 2, (b2_y1 + b2_y2) / 2 # 最小外接矩形(保持不变) c_x1 = torch.min(b1_x1, b2_x1) c_y1 = torch.min(b1_y1, b2_y1) c_x2 = torch.max(b1_x2, b2_x2) c_y2 = torch.max(b1_y2, b2_y2) c_diag = (c_x2 - c_x1).pow(2) + (c_y2 - c_y1).pow(2) + eps # 中心点距离(保持不变) center_dist = (b1_cx - b2_cx).pow(2) + (b1_cy - b2_cy).pow(2) # ========== 关键改进 ========== # 1. 温和的高IoU梯度增强 # 降低gamma值,仅在IoU>0.7时增强 iou_gain = 1.0 + gamma * (iou.detach() - 0.7).clamp_min(0) # 2. 条件性形状惩罚 # 仅在IoU>0.5时应用形状惩罚 aspect_ratio1 = w1 / (h1 + eps) aspect_ratio2 = w2 / (h2 + eps) shape_penalty = torch.zeros_like(iou) shape_mask = iou.detach() > 0.5 if shape_mask.any(): # 使用更温和的log比例 ratio_diff = (aspect_ratio1 / aspect_ratio2).clamp(0.5, 2.0) shape_penalty[shape_mask] = torch.log(ratio_diff[shape_mask]).abs() # 降低形状惩罚权重 shape_weight = 0.05 * (iou.detach() / 0.7).clamp(0, 1) # 3. 动态中心点权重(改进) min_dim = torch.min(w1, h1) * torch.min(w2, h2) center_weight = 1.0 + beta * (1.0 - min_dim.sqrt() / 32.0).clamp(0, 1) # 仅在低IoU时衰减中心点权重 center_decay = 0.2 * (1.0 - iou.detach() / 0.5).clamp(0, 1) center_weight *= 1.0 - center_decay # 4. 新增边界框紧密度惩罚(修正括号问题) # 计算预测框与目标框的紧密度 compactness_w = torch.abs(w1 - w2) / (w1 + w2 + eps) compactness_h = torch.abs(h1 - h2) / (h1 + h2 + eps) compactness = compactness_w + compactness_h # 紧密度惩罚随IoU增加而增加 compactness_weight = delta * (iou.detach() / 0.7).clamp(0, 1) compactness_penalty = compactness * compactness_weight # 5. 自适应尺寸惩罚(保持不变) size_ratio = torch.min(w1/w2, h1/h2) + torch.min(w2/w1, h2/h1) size_penalty = alpha * (1 - size_ratio / 2) # 6. 小目标边界保护(保持不变) min_size = torch.min(w1 * h1, w2 * h2) boundary_factor = 1.0 / (1.0 + torch.exp(-0.1 * (min_size - 10))) # 组合TTDIoU_v3 ttdiou = iou - center_weight * (center_dist / c_diag) - boundary_factor * size_penalty ttdiou -= shape_weight * shape_penalty ttdiou -= compactness_penalty # 新增紧密度惩罚 # 5. 新增小目标补偿因子 #small_target_factor = (min_dim < 32**2).float() * 0.8 + 0.2 # [0.2,1.0] return iou_gain * ttdiou 调用: iou = bbox_ttdiou_v3(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=True, alpha=0.25, beta=1.2, gamma=0.5) loss_iou = (1.0 - iou).mean()
最新发布
07-01
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值