目录

一、案例实战:Python实现逻辑回归任务概述

Logistic Regression

1、读取数据

2、看数据维度

3、 'Admitted'==1/'Admitted'==0图像

实现The logistic regression

二、案例实战:完成梯度下降模块

1、sigmoid 函数

表达式

sigmoid 函数画图展示

2、完成预测函数

3、构造数据

检查结果

4、数据组合

损失函数

计算梯度

三、案例实战:停止策略与梯度下降案例

1、比较3中不同梯度下降方法

2、将数据进行洗牌

3、时间对结果的影响

4、功能性函数

5、结果

四、案例实战:实验对比效果

1、对比不同停止策略

根据损失值停止

根据梯度变化停止

2、对比不同的梯度下降方法

Stochastic descent

Mini-batch descent

精度


一、案例实战:Python实现逻辑回归任务概述

Logistic Regression

我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理员,你想根据两次考试的结果来决定每个申请人的录取机会。你有以前的申请人的历史数据,你可以用它作为逻辑回归的训练集。对于每一个培训例子,你有两个考试的申请人的分数和录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。

#三大件
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

1、读取数据

import os
path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
pdData.head()

2、看数据维度

pdData.shape

3、 'Admitted'==1/'Admitted'==0图像

positive = pdData[pdData['Admitted'] == 1] # returns the subset of rows such Admitted = 1, i.e. the set of *positive* examples
negative = pdData[pdData['Admitted'] == 0] # returns the subset of rows such Admitted = 0, i.e. the set of *negative* examplesfig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=30, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')

实现The logistic regression

目标:建立分类器(求解出三个参数

设定阈值,根据阈值判断录取结果

二、案例实战:完成梯度下降模块

要完成的模块:

  • sigmoid : 映射到概率的函数

  • model : 返回预测结果值

  • cost : 根据参数计算损失

  • gradient : 计算每个参数的梯度方向

  • descent : 进行参数更新

  • accuracy: 计算精度

1、sigmoid 函数