原创文章,如需转载请保留出处
本博客为唐宇迪老师python数据分析与机器学习实战课程学习笔记
一. Python实现逻辑回归任务概述
1.1 问题描述
我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理员,你想根据两次考试的结果来决定每个申请人的历史数据,你可以用它作为逻辑回归的训练集。对于每一个培训例子,你可以有两个考试申请人的分数和录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。
1.2 代码实现
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import os
path = 'data'+os.sep+'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam 1','Exam 2','Admitted'])
pdData.head()
Exam 1 Exam 2 Admitted
0 34.623660 78.024693 0
1 30.286711 43.894998 0
2 35.847409 72.902198 0
3 60.182599 86.308552 1
4 79.032736 75.344376 1
pdData.shape
(100, 3)
#fig, ax = plt.subplots(1,3,figsize=(15,7)),这样就会有1行3个15x7大小的子图。
positive = pdData[pdData['Admitted']==1]
negative = pdData[pdData['Admitted']==0]
fig,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')
1.3 The logistic regression
- 目标:建立分类器(求解出三个参数θ0θ1θ2)
- 设定阈值,根据阈值判断录取结果
要完成的模块
- sigmoid:映射到概率的函数
- model:返回预测结果值
- cost:根据参数计算损失
- gradient:计算每个参数的梯度方向
- descent:进行参数更新
- accuracy:计算精度
Sigmoid函数