机器学习_学习笔记:逻辑回归(Logistic Regression)的Python实现

 逻辑回归(Logistic Regression)

逻辑回归模型的假设是:h_{\theta}(x)=g(\theta^{T}x),其中x代表特征向量,θ代表参数向量

一个常用的逻辑函数为S形函数(sigmoid function),公式为:g(z)=\frac{1}{1+e^{-z}}

逻辑回归模型的代价函数为J(\theta)=\frac{1}{m}\sum_{i=1}^{m}Cost(h_{\theta}(x^{(i)},y^{(i)})),其中m为样本个数

Cost(h_{\theta}(x),y)=\left\{\begin{matrix} -log(h_{\theta}(x)) &if y=1 \\ -log(1-h_{\theta}(x))&if y=0 \end{matrix}\right.

简化后为:J(\theta)=-\frac{1}{m}\sum_{i=1}^{m}[y^{(i)}log(h_{\theta}(x^{(i)}))+(1-y^{(i)})log(1-h_{\theta}(x^{(i)}))]

Python代码实现如下:

import numpy as np
import matplotlib.pyplot as plt


def sigmoid_z(z):
    """
    计算逻辑函数 S形函数
    对于给定的x,通过已经确定的参数(θ)计算得出h_θ(x)= 0.7,则表示y有70%的概率y为正向类,相应的y为负向类的概率为1-0.7=0.3
    :param z:预测的输出变量的值,即θ^TX的值
    :return: g(z)的值:输出变量y=z时,为正向类的几率
    """
    return 1 / (1 + np.exp(-z))  # np.exp(k) 求e的幂次方 e^k


def sigmoid(theta, X):
    """
    计算逻辑函数 S形函数
    :param theta:参数向量
    :param X:特征矩阵
    :return:
    """
    theta = np.mat(theta)
    X = np.mat(X)

    z = X * theta.T  # θ和X^(i)的维度是相同的,θ是向量,θj是标量,它与每一个x(i)样本的第j个维度相乘,即:θj*x(i,j);输入时注意
    return 1 / (1 + np.exp(-z))  # np.exp(k) 求e的幂次方 e^k


def cost(theta, X, y):
    """
    逻辑回归算法的代价函数
    :param theta:参数向量
    :param X:特征矩阵
    :param y:结果为正向类/负向类
    :return:
    """
    theta = np.mat(theta)
    X = np.mat(X)  # 创建矩阵;若输入X本身为矩阵,则不会创建副本,只是创建一个引用;等价于np.matrix(X,copy=False)和np.asmatrix(X)
    y = np.mat(y)  # np.matrix(X)默认为np.matrix(X,copy=True)

    # X:m*(n+1) theta:1*(n+1)
    first = np.multiply(-y, np.log(sigmoid(theta, X)))  # np.multiply()数组和矩阵对应位置相乘,输出与相乘数组/矩阵的大小一致
    second = np.multiply((1 - y), np.log(1 - sigmoid(theta, X)))

    return np.sum(first - second)


if __name__ == "__main__":
    # 逻辑函数 S 形函数 test
    n = 2  # θ^T@X的值为2
    re = sigmoid_z(n)  # 计算g(2),即输出变量为1时(即输出变量为正向类)的可能性
    print("test:" + str(re))

    X_m = np.array([[1, 2, 3, 4], [1, 1, 2, 0]])  # X为特征矩阵是m*(n+1)
    y_m = np.array([1, 0])  # y为实际的结果变量(正向类/负向类),y的数量对应的是样本的数量,即m
    theta_m = np.array([1, 0, 2, 1])  # theta是参数向量:1*(n+1)
    # 逻辑函数S形函数
    re_sig = sigmoid(theta_m, X_m)
    print("逻辑函数:" + str(re_sig))
    # 逻辑函数的代价函数
    re_cost = cost(theta_m, X_m, y_m)
    print("逻辑函数代价函数:" + str(re_cost))

    # 画出S形函数的图像 用函数sigmoid_z(z)
    xx = np.arange(-10, 10, 1)
    yy = sigmoid_z(xx)
    plt.plot(xx, yy)
    plt.show()

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是使用牛顿法实现逻辑回归Python 代码: ```python import numpy as np # 定义 sigmoid 函数 def sigmoid(x): return 1 / (1 + np.exp(-x)) # 定义牛顿法求解函数 def newton_method(X, y, max_iter=100, tol=1e-6): m, n = X.shape theta = np.zeros(n) J_history = [] for i in range(max_iter): # 计算 Hessian 矩阵和梯度向量 grad = np.dot(X.T, (sigmoid(np.dot(X, theta)) - y)) H = np.dot(X.T, np.dot(np.diag(sigmoid(np.dot(X, theta))) * np.diag(1 - sigmoid(np.dot(X, theta))), X)) # 计算参数更新量 delta delta = np.dot(np.linalg.inv(H), grad) # 更新参数 theta -= delta # 计算代价函数值 J = -np.mean(y * np.log(sigmoid(np.dot(X, theta))) + (1 - y) * np.log(1 - sigmoid(np.dot(X, theta)))) # 将代价函数值记录下来 J_history.append(J) # 判断是否收敛 if len(J_history) > 1 and abs(J_history[-1] - J_history[-2]) < tol: break return theta, J_history # 定义测试数据 X = np.array([[1, 0.5], [1, 2], [1, 3], [1, 4]]) y = np.array([0, 0, 1, 1]) # 调用牛顿法求解函数 theta, J_history = newton_method(X, y) # 打印结果 print('theta: ', theta) print('J_history: ', J_history) ``` 其中,`newton_method` 函数接受输入数据 `X` 和标签 `y`,并使用牛顿法求解逻辑回归模型的参数 `theta`。`max_iter` 参数指定最大迭代次数,`tol` 参数指定收敛阈值。函数返回参数 `theta` 和每次迭代后的代价函数值 `J_history`。在测试数据上运行该代码,输出结果如下: ``` theta: [-3.00893325 2.14741959] J_history: [0.6931471805599453, 0.2669544726698027, 0.13705632045316542, 0.09203771660369033, 0.07079664830787625, 0.059139332628238676, 0.05136488481787413, 0.04591477587635569, 0.04178301932068173, 0.038465174470379574, 0.03570243695117117, 0.03334670150049713, 0.0312990589127205, 0.029490324581943943, 0.02786979302712522, 0.026400129691429624, 0.025051062015345358, 0.023798996720792114, 0.02262586870468139, 0.021517088652593512, 0.02046103027062017, 0.019448619792075086, 0.018472020748139423, 0.01752453231759679, 0.01660029613296208, 0.015695041620655392, 0.014805935235905013, 0.013930518327382414, 0.01306656813688889, 0.01221208258656761, 0.011365262917829082, 0.010524438955291958, 0.00968706726059816, 0.00885167884217652, 0.008016873155744753, 0.007181305839098925, 0.006343669870503022, 0.005502707619564358, 0.004657204459673163, 0.003805990133353994, 0.0029479384747786106, 0.002081959646526758, 0.0012069968423602312, 0.0003214669941350246] ``` 可以看到,经过 42 次迭代后,模型的参数 `theta` 收敛,并且代价函数值也随之收敛。最终得到的参数 `theta` 为 `[-3.00893325, 2.14741959]`,可以用于预测新的样本标签。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值