1,什么是逻辑回归(Logistic Regression)
逻辑回归用于二分分类问题,二分分类问题的标签值只有两个,比如 对于一首歌喜欢或者不喜欢;对于一件商品,喜欢或者不喜欢;对于某个考生,考试成绩 及格或者不及格。
其思想也是基于线性回归(Logistic Regression属于广义线性回归模型),分类算法用到了逻辑函数 ,因为逻辑函数的参数又用到了线性回归函数,所以才被称为逻辑回归。
逻辑函数的数值是介于0到1之间,中间值为0.5,通过一个函数可以把y的值控制在0到1之间。
分类问题的本质是决策面,如果逻辑函数得到的概率值y>=0.5 标签=1 ,如果y< 0.5 ,标签=0
逻辑回归模型准确率 ,用正确率来衡量
【准确率】 = 正确分类个数 / 数据总数
2,分类和回归的区别
3,用Python实现逻辑回归
3.1 收集数据
# 通过有序字典创建一个有序数据集
from collections import OrderedDict
import pandas as pd
examDict={
'学习时间':[0.50,0.75,1.00,1.25,1.50,1.75,1.75,2.00,2.25,2.50,
2.75,3.00,3.25,3.50,4.00,4.25,4.50,4.75,5.00,5.50],
'通过考试':[0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1]
}
examOrderDict=OrderedDict(examDict)
examDf=pd.DataFrame(examOrderDict)
examDf.head()
3.2 特征提取
特征提取
# 特征X 与标签y提取
exam_X = examDf.loc[:,'学习时间']
exam_y = examDf.loc[:,'通过考试']
绘制散点图对数据有个直观的认识
# 通过绘制散点图来对数据有个直观的认识,从散点图来看明显不适合用最佳拟合线来
import matplotlib.pyplot as plt
plt.scatter(exam_X,exam_y,color='b',label='exam data')
plt.xlabel('Hours')
plt.ylabel("Pass")
plt.show()
3.3 建立训练、测试数据集
#建立训练、测试数据集;一般把原始数据8/2 开
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test = train_test_split(exam_X,exam_y,train_size=.8)
print('原始数据特征:',exam_X.shape ,
',训练数据特征:', X_train.shape ,
',测试数据特征:',X_test.shape )
print('原始数据标签',exam_y.shape,
'训练数据标签',y_train.shape,
'测试数据标签',y_test.shape)
返回结果:
原始数据特征: (20,) ,训练数据特征: (16,) ,测试数据特征: (4,)
原始数据标签 (20,) 训练数据标签 (16,) 测试数据标签 (4,)
# 绘制散点图,更形象展示训练数据集、测试数据集
# 蓝色为训练数据集,红色为测试数据集
import matplotlib.pyplot as plt
plt.scatter(X_train,y_train,color='blue',label='train data')
plt.scatter(X_test,y_test,color='red',label='test data')
plt.legend(loc=2)
plt.xlabel('Hours')
plt.ylabel('Pass')
plt.show()
3.4 构建模型
#第0步:输入的数据只有1个特征,需要用array.reshape(-1, 1)来改变数组的形状
X_train = X_train.values.reshape(-1,1)
X_test = X_test.values.reshape(-1,1)
#第1步:导入逻辑回归
from sklearn.linear_model import LogisticRegression
# 第2步:创建模型:逻辑回归
model = LogisticRegression()
#第3步:训练模型
model.fit(X_train,y_train)
返回结果:
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)
3.5 模型评估
#模型评估(使用测试数据)
model.score(X_test,y_test)
返回结果:
0.75
正确率0.75,模型还不错。
#获取概率值
#第1个值是标签为0的概率值,第2个值是标签为1的概率值
model.predict_proba(3)
返回结果:
array([[0.44701593, 0.55298407]])
理解逻辑回归函数
'''
理解逻辑回归函数
斜率slope
截距intercept
'''
import numpy as np
a=model.intercept_
b=model.coef_
x=3
z=a+b*x
y_pred=1/(1+np.exp(-z))
print('预测的概率值:',y_pred)
返回结果:
预测的概率值: [[0.55298407]]
概率值大于0.5,表示学生花费3小时,通过考试
4,实践收获
1)通过通过train_test_split 随机把数据集分为训练数据集和测试数据集
#建立训练、测试数据集;一般把原始数据8/2 开
from sklearn.cross_validation import train_test_split
X_train,X_test,y_train,y_test = train_test_split(exam_X,exam_y,train_size=.8)
print('原始数据特征:',exam_X.shape ,
',训练数据特征:', X_train.shape ,
',测试数据特征:',X_test.shape )
print('原始数据标签',exam_y.shape,
'训练数据标签',y_train.shape,
'测试数据标签',y_test.shape)
2)构建逻辑回归模型,只需要3行代码
#第1步:导入逻辑回归
from sklearn.linear_model import LogisticRegression
# 第2步:创建模型:逻辑回归
model = LogisticRegression()
#第3步:训练模型
model.fit(X_train,y_train)
3)用array.reshape()来改变数组的形状,第一个参数代表行数,第二个参数代表列数;假如对一个3*2的数组使用reshape(-1,1),则得到一个6*1的数组;对一个3*2的数组使用reshape(1,-1),则得到一个1*6的数组。
#第0步:输入的数据只有1个特征,需要用array.reshape(-1, 1)来改变数组的形状
X_train = X_train.values.reshape(-1,1)
X_test = X_test.values.reshape(-1,1)