逻辑回归模型案例
我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理员,你想根据两次考试的结果来决定每个申请人的录取机会。你有以前的申请人的历史数据,你可以用它作为逻辑回归的训练集。对于每一个培训例子,你有两个考试的申请人的分数和录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。
# 数据分析三大件
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()
# 观察数据维度,第一维表示样本的个数,第二维表示当前每一个样本有三列值
pdData.shape
(100, 3)
# 画图观察第三列是什么样的
# 指定正列负列
positive = pdData[pdData["Admitted"] == 1]
negative = pdData[pdData["Admitted"] == 0]
# 指定画图域
fig,ax = plt.subplots(figsize=(10,5))
# 散点图;c定义的是颜色
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
目标:建立分类器(求解出三个参数 $\theta_0 \theta_1 \theta_2 $)
设定阈值,根据阈值判断录取结果
要完成的模块
sigmoid : 映射到概率的函数
model : 返回预测结果值
cost : 根据参数计算损失
gradient : 计算每个参数的梯度方向
descent : 进行参数更新
accuracy: 计算精度
sigmoid 函数
g ( z ) = 1 1 + e − z g(z) = \frac{1}{1+e^{-z}} g(z)=1+e−z1
def sigmoid(z):
return 1 / (1+np.exp(-z))
# 画图展示sigmoid 函数
nums = np.arange(-10, 10, step=1)
fig,ax = plt.subplots(figsize=(12,4))
ax.plot(nums, sigmoid(nums),"r")
Sigmoid
- g : R → [ 0 , 1 ] g:\mathbb{R} \to [0,1] g:R→[0,1]
- g ( 0 ) = 0.5 g(0)=0.5 g(0)=0.5
- g ( − ∞ ) = 0 g(- \infty)=0 g(−∞)=0
- g ( + ∞ ) = 1 g(+ \infty)=1 g(+∞)=1
# np.dot矩阵乘法
def model(X, theta):
return sigmoid(np.dot(X,theta.T))
( θ 0 θ 1 θ 2 )