机器学习2-Logistic回归

本文详细介绍了Logistic回归,包括其形式化定义、求解过程、代码实现、正则化的理论和实践,以及如何用它进行多分类任务。通过sklearn库实现Logistic回归,并通过鸢尾花分类和手写数字识别两个案例进行实战演示。
摘要由CSDN通过智能技术生成

1.形式化定义

解决的是分类问题,类别分别是0和1
在这里插入图片描述

2.逻辑回归求解

在这里插入图片描述

举例说明

在这里插入图片描述

3.逻辑回归代码实现

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import accuracy_score


# 定义加载数据的函数
def loaddata():
    data = np.loadtxt('data2.txt', delimiter=',')
    # 特征数
    n = data.shape[1] - 1
    X = data[:, 0:n]
    y = data[:, -1].reshape(-1, 1)
    return X, y


# 定义散点图函数
def scatter(X, y):
    # 分别寻找y==1和y==0时,索引值的位置
    pos = np.where(y == 1)
    neg = np.where(y == 0)
    plt.scatter(X[pos[0], 0], X[pos[0], 1], marker='x')
    plt.scatter(X[neg[0], 0], X[neg[0], 1], marker='o')
    plt.xlabel('Exam 1 score')
    plt.xlabel('Exam 2 score')
    plt.show()


# 实现sigmoid函数
def sigmoid(z):
    r = 1 / (1 + np.exp(-z))
    return r


# 实现假设函数
def hypothesis(X, theta):
    z = np.dot(X, theta)
    return sigmoid(z)


# 实现代价函数,先实现损失
def computeCost(X, y, theta):
    m = X.shape[0]
    l = -y * np.log(hypothesis(X, theta)) - (1 - y) * np.log(1 - hypothesis(X, theta))
    return np.sum(l) / m


# 梯度下降法求解
def gradientDescent(X, y, theta, iterations, alpha):
    # 数据量
    m = X.shape[0]
    # 在x最前面插入全为1的列
    # np.vstack():在竖直方向上堆叠
    # np.hstack表示在水平方向上平铺
    X = np.hstack((np.ones((m, 1)), X))

    for i in range(iterations):
        for j in range(len(theta)):
            theta[j] = theta[j] - (alpha / m) * np.sum((hypothesis(X, theta) - y) * X[:, j].reshape(-1, 1))
        if (i % 10000 == 0):
            # 每迭代10000次,输出一次损失值
            print('第', i, '次迭代,当前损失为:', computeCost(X, y, theta), 'theta =', theta)
    return theta


# 画决策边界
def plotDescionBoundary(X, y, theta):
    # 样本点颜色
    cm_dark = mpl.colors.ListedColormap(['g', 'r'])
    plt.xlabel('Exam 1 score')
    plt.ylabel('Exam 2 score')
    # 根据y的结果自动的在cmap中选择颜色,c参数代表颜色
    plt.scatter(X[:, 0], X[:, 1], c=np.array(y).squeeze(), cmap=cm_dark, s=30)

    # 画分类决策面
    x1 = np.arange(min(X[:, 0]), max(X[:, 0]), 0.1)
    x2 = -(theta[0] + theta[1] * x1) / theta[2]
    plt.plot(x1, x2)
    plt.show()


# 定义预测函数
def predict(X):
    m = X.shape[0]
    # 在x最前面插入全为1的列
    X = np.hstack((np.ones((m, 1)), X))
    # 求解假设函数的值(预测值)
    h = hypothesis(X, theta)
    # 根据概率值决定最终的分类,>=0.5为1类,<0.5为0类
    h[h >= 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值