案例实战:Python实现逻辑回归(Logistic Regression)与梯度下降策略

0. 案例背景

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

1. 导入pythony库

#导入机器学习三大件:Numpy, Pandas, Matplotlib
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

for i in [np, pd, matplotlib]:
    print(i.__version__)

输出:

1.17.4
0.25.3
3.1.2

2. 导入数据集

import os

path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv(path, header=None, names=['Exam1', 'Exam2', 'Admitted'])
print(pdData.head(8))
print("Data shape:",pdData.shape)

输出:

       Exam1      Exam2  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
5  45.083277  56.316372         0
6  61.106665  96.511426         1
7  75.024746  46.554014         1
Data shape: (100, 3)

3. 数据可视化

positive = pdData[pdData['Admitted'] == 1] # 返回Admitted列值为1的样本
negative = pdData[pdData['Admitted'] == 0] # 返回Admitted列值为1的样本

fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam1'], positive['Exam2'], s=30, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam1'], negative['Exam2'], s=30, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam1 Score')
ax.set_ylabel('Exam2 Score')

输出:

从上图可以看出:数据具有一定的可区分性。红色点(负样本)总体位于左下方,而蓝色点(正样本)总体位于右上方。

4. 数据处理

在模型构建中为了方便书写和计算,将偏置项用W0表示,因此在数据所有样本的第一列插入1,即b=W0*1

try:
    pdData.insert(0, 'Ones', 1) # 写到try...except结构中以防第二次执行时报错
except:
    pass

orig_data = pdData.as_matrix() # 将Pandas的DataFrame转换成矩阵形成
print(type(orig_data))
print(orig_data.shape)
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]

print("X shape:",X.shape)
print("y shape:",y.shape)

#X = np.matrix(X.values)
#y = np.matrix(data.iloc[:,3:4].values) #np.array(y.values)
W = np.zeros([3, 1])
print("W shape:",W.shape)

输出:

<class 'numpy.ndarray'>
(100, 4)
X shape: (100, 3)
y shape: (100, 1)
W shape: (3, 1)

根据X, y, W的shape以及矩阵乘法相关知识可得:XW=y

5. 用Python手动实现逻辑回归

目标:建立逻辑回归模型,即求解出参数𝑊W。由于数据共有3列:Exam1,Exam2,Admitted,其中Admitted作为标签使用。因此𝑊可以表示为3*1的向量(这里偏置项用𝑊0代替,方便书写和矩阵计算&#

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值