逻辑回归-梯度下降法 python实现

机器学习的基本框架:

模型(model)、目标(cost function)、优化算法

Step1:对于一个问题,需要首先建立一个模型,如回归或分类模型;

step2:通过最小分类误差、最大似然或最大后验概率建立模型的代价函数;

step3:最优化问题求解

a.如果优化函数存在解析解,则可以通过一般的求值方法-对代价函数求导,找到倒数为0的点,即是最大值或者最小孩子;

b.如果上述方法求优化函数导数比较复杂,可利用迭代算法也求解。


对于回归问题:

(1)模型

可选择的模型有线性回归和LR回归。

(2)目标-cost function

线性回归模型:

 (最小二乘)

LR回归模型:

(极大似然)


线性回归的假设前提是y服从正态分布,LR回归的假设前提是y服从二项分布(y非零即1)。

(3)算法-最优化算法

梯度下降法、牛顿法等;


Python代码:

LRgradAscent.py

from numpy import *

def loadData(filepath):
    dataMat= []
    labels = []
    fr = open(filepath)
    for line in fr.readlines():
        str = line.strip().split('\t')
        dataMat.append([1.0,float(str[0]),float(str[1])])
        labels.append(int(str[2]))
    return mat(dataMat), mat(labels).transpose()

def sigmoid(inX):
    return 1.0/(1+exp(-inX))

def gradAscent(dataMatrix,labelsMatrix):
    n,m = shape(dataMatrix)
    weights = ones((m,1))
    step = 0.001
    iter = 500
    for k in range(iter):
        value = sigmoid(dataMatrix*weights)
        chazhi = labelsMatrix - value
        grad = dataMatrix.transpose()*chazhi
        weights = weights + step * grad
    return weights
    
def plotBestFit(weights,filepath):
    import matplotlib.pyplot as plt
    # illustrate the samples
    dataMatrix,labelsMatrix = loadData(filepath)
    n,m = shape(dataMatrix)
    xcord1 = []; ycord1 = []  #store the coordination of sample having label 1
    xcord2 = []; ycord2 = []
    for i in range(n):
        if int(labelsMatrix[i]) == 1:
            xcord1.append(dataMatrix[i,1])
            ycord1.append(dataMatrix[i,2])
        else:
            xcord2.append(dataMatrix[i,1])
            ycord2.append(dataMatrix[i,2])
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.scatter(xcord1,ycord1,s = 30,c = 'red',marker = 's')
    ax.scatter(xcord2,ycord2,s = 30,c = 'green')
    
    #illustrate the classifying line
    min_x = min(dataMatrix[:,1])[0,0]
    max_x = max(dataMatrix[:,2])[0,0]
    y_min_x = (-weights[0] - weights[1] * min_x) / weights[2]
    y_max_x = (-weights[0] - weights[1] * max_x) / weights[2]  #here, sigmoid(wx = 0) so wo + w1*x1 + w2*x2 = 0
    plt.plot([min_x,max_x],[y_min_x[0,0],y_max_x[0,0]],'-g') 
    plt.show()

测试程序:

import LRgradAscent
import pdb

filename = 'testSet.txt'
dataMat, labelsMat = LRgradAscent.loadData(filename)
weights = LRgradAscent.gradAscent(dataMat,labelsMat)
LRgradAscent.plotBestFit(weights,filename)



参考:http://blog.csdn.net/zouxy09/article/details/20319673


  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
小批量梯度下降是一种常用的优化算,用于训练逻辑回归模型。下面是它的实现逻辑和Python代码示例: 1. 初始化参数:首先,我们需要初始化逻辑回归模型的参数,包括权重和偏置项。 2. 定义损失函数:逻辑回归模型通常使用交叉熵损失函数来衡量预测结果与真实标签之间的差异。 3. 获取数据:从训练集中获取一小批量的样本和对应的标签。 4. 前向传播:使用当前的参数进行前向传播,计算预测结果。 5. 计算损失:将预测结果与真实标签进行比较,计算损失值。 6. 反向传播:根据损失值计算梯度,并更新参数。 7. 重复步骤3-6:重复执行上述步骤,直到达到指定的迭代次数或收敛条件。 下面是一个简单的Python代码示例: ```python import numpy as np # 初始化参数 def initialize_parameters(dim): w = np.zeros((dim, 1)) b = 0 return w, b # 定义sigmoid函数 def sigmoid(z): return 1 / (1 + np.exp(-z)) # 前向传播 def forward_propagation(X, w, b): Z = np.dot(X, w) + b A = sigmoid(Z) return A # 计算损失函数 def compute_loss(A, Y): m = Y.shape loss = -np.sum(Y * np.log(A) + (1 - Y) * np.log(1 - A)) / m return loss # 反向传播 def backward_propagation(X, A, Y): m = Y.shape dw = np.dot(X.T, (A - Y)) / m db = np.sum(A - Y) / m return dw, db # 更新参数 def update_parameters(w, b, dw, db, learning_rate): w -= learning_rate * dw b -= learning_rate * db return w, b # 小批量梯度下降训练逻辑回归模型 def train(X, Y, num_iterations, batch_size, learning_rate): m, dim = X.shape w, b = initialize_parameters(dim) for i in range(num_iterations): # 获取小批量样本和标签 indices = np.random.choice(m, batch_size) X_batch = X[indices] Y_batch = Y[indices] # 前向传播 A = forward_propagation(X_batch, w, b) # 计算损失函数 loss = compute_loss(A, Y_batch) # 反向传播 dw, db = backward_propagation(X_batch, A, Y_batch) # 更新参数 w, b = update_parameters(w, b, dw, db, learning_rate) if i % 100 == 0: print("Loss after iteration {}: {}".format(i, loss)) return w, b ``` 使用上述代码,你可以通过调用`train`函数来训练逻辑回归模型。其中,`X`是输入特征矩阵,`Y`是对应的标签向量,`num_iterations`是迭代次数,`batch_size`是每次迭代中使用的样本数量,`learning_rate`是学习率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值