用python写梯度下降算法实现逻辑斯蒂回归

1.logistic的理论基础

可参考网上一位大佬写的李航的《统计学习方法》笔记
pdf笔记文档链接:
链接:https://pan.baidu.com/s/1Gee9aOdNvemy5K6co1daZg
提取码:hlbb

具体算法步骤:
1
在这里插入图片描述

2.用python实现

数据使用iris数据集,iris数据集有三个类别,我们使用前两个类别作为因变量Y
iris数据集链接:
https://pan.baidu.com/s/17yA7n2so_EhxmXwn0RQXrQ
提取码:xboz

import numpy as np
import pandas as pd

# 1.加载数据;数据预处理
iris = pd.read_csv("iris.csv")
# iris数据集有三类, 这里将第三列删除,只使用第一类和第二类
iris = iris[~iris['Species'].isin(['virginica'])]
X = iris.iloc[:, 1:5]
Y = iris.iloc[:, 5]
# 将iris前两类的名称改为0和1
Y = Y.replace("setosa", 0)
Y = Y.replace("versicolor", 1)

# 将X转化成(x_1, x_2, ..., x_n, 1)的格式
X['one'] = 1
X = X.iloc[1:, :]
Y = Y.iloc[1:]
# 到这,数据预处理就完成了!

# 2.逻辑斯蒂回归算法
def g(w, X, Y):
    return np.sum(np.log(1 + np.exp(np.dot(X, w))) - np.multiply(np.dot(X, w), np.expand_dims(Y, axis=1)), axis=1)

class LOGISTIC(object):
    def __init__(self, X, Y, w=np.zeros(X.shape[1])):
        # w = (w1, w2, ..., wn, b)
        self.eta = 0.1
        self.epsilon = 0.001
        self.step = 0
        self.X = X
        self.w = w
        self.Y = Y

    def run(self):
        while True:
            P = np.exp(np.dot(self.X, self.w)) / (1 + np.exp(np.dot(self.X, self.w)))
            gradient_w = np.sum(np.multiply(self.X, np.expand_dims(P-self.Y, axis=1)), axis=0)
            gradient_w_norm = np.linalg.norm(gradient_w, ord=2)    # L2范数,等价于np.sqrt(np.sum(gradient_w**2))

            if gradient_w_norm < self.epsilon:
                return self.w, self.step
            else:
                w2 = self.w - self.eta*gradient_w
                if np.linalg.norm(g(w2, self.X, self.Y)-g(self.w, self.X, self.Y), ord=2) < self.epsilon or \
                        np.linalg.norm(w2-self.w, ord=2) < self.epsilon:
                    return self.w, self.step
                self.w = w2
            self.step += 1

# 测试
def test(w, x):
    p_0 = 1/(1+np.exp(np.dot(x, np.expand_dims(w, axis=1))))
    p_1 = 1 - p_0
    diff = p_0 - p_1
    diff[diff > 0] = 0
    diff[diff < 0] = 1
    return diff


log = LOGISTIC(X=X, Y=Y)
train_w, train_step = log.run()
# train_w即为训练得到的权重,train_step为训练的步数
print(train_w)
print("步数:", train_step)

test_cls = test(train_w, X)
# test_cls即为logistic的判断结果
# print(test_cls)

# 计算准确率
acc = np.sum(test_cls - np.expand_dims(Y, axis=1) == 0)/test_cls.shape[0]
print("准确率:%.3f%%" % (acc*100))

运行结果:
在这里插入图片描述

注:代码是参照上面的算法步骤自己写的,如有问题,欢迎批评指正。

  • 2
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是使用Python代码对梯度下降算法实现线性回归的示例: 首先,我们需要导入所需的包: ```python import numpy as np import matplotlib.pyplot as plt ``` 然后,我们定义一个函数来计算误差,即损失函数: ```python def compute_cost(X, y, theta): m = len(y) predictions = X.dot(theta) square_err = (predictions - y) ** 2 J = 1 / (2 * m) * np.sum(square_err) return J ``` 其中,X是一个m行n列的特征矩阵,y是一个m行1列的目标向量,theta是一个n行1列的参数向量,m是样本数量,n是特征数量。 接下来,我们定义一个函数来执行梯度下降算法: ```python def gradient_descent(X, y, theta, alpha, num_iters): m = len(y) J_history = np.zeros((num_iters, 1)) for i in range(num_iters): predictions = X.dot(theta) errors = np.subtract(predictions, y) delta = (alpha / m) * X.transpose().dot(errors) theta = theta - delta J_history[i] = compute_cost(X, y, theta) return theta, J_history ``` 其中,alpha是学习率,num_iters是迭代次数,J_history记录了每次迭代后的损失函数值。 最后,我们可以使用上述函数来拟合一个简单的线性模型: ```python # 生成随机数据 np.random.seed(0) X = 2 * np.random.rand(100, 1) y = 4 + 3 * X + np.random.randn(100, 1) # 对特征矩阵X添加一列全为1的向量,以便于计算截距 X_b = np.c_[np.ones((100, 1)), X] # 初始化参数向量theta theta = np.random.randn(2, 1) # 执行梯度下降算法 alpha = 0.1 num_iters = 1000 theta, J_history = gradient_descent(X_b, y, theta, alpha, num_iters) # 绘制拟合直线 plt.scatter(X, y) plt.plot(X, X_b.dot(theta), 'r') plt.show() ``` 这里我们生成了一个简单的一维数据集,然后对其进行线性回归拟合并绘制出拟合直线。 完整代码如下:
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值