我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理员,你想根据两次考试的结果来决定每个申请人的录取机会。你有以前的申请人的历史数据,你可以用它作为逻辑回归的训练集。对于每一个培训例子,你有两个考试的申请人的分数和录取决定。为了做到这一点,我们将建立一个分类模型,根据考试成绩估计入学概率。
#三大件
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# 数据的维数
# positive和negative都是很多数
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* examples
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')
下面开始逻辑回归
目标:建立分类器(求解出三个参数 θ 0 , θ 1 , θ 2 \theta_{0},\theta_{1},\theta_{2} θ0,θ1,θ2)
设定阈值,根据阈值判断录取结果
要完成的模块
- sigmoid : 映射到概率的函数
- model : 返回预测结果值
- cost : 根据参数计算损失
- gradient : 计算每个参数的梯度方向
- descent : 进行参数更新
- accuracy: 计算精度
sigmod函数
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))
def model(X, theta):
return sigmoid(np.dot(X, theta.T))
构造数据
#添加一列值为1
pdData.insert(0, 'Ones', 1) # in a try / except structure so as not to return an error if the b