用python做逻辑回归_用Python来实现逻辑回归

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)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我为您介绍一下如何用Python实现逻辑回归。 我们可以使用Python中的sklearn库来实现逻辑回归。具体步骤如下: 1. 导入库和数据集 首先,需要导入必要的库,例如numpy、pandas、matplotlib和sklearn。然后,可以使用pandas库的read_csv()函数来读取数据集。 ```python import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, classification_report # 读取数据集 data = pd.read_csv('data.csv') ``` 2. 数据预处理 在进行逻辑回归之前,需要对数据进行一些预处理,例如处理缺失值、去除异常值和进行特征工程等。 ```python # 处理缺失值 data = data.dropna() # 特征选择 X = data[['feature1', 'feature2', ...]] y = data['label'] ``` 3. 划分训练集和测试集 为了评估模型的性能,需要将数据集划分为训练集和测试集。可以使用sklearn库的train_test_split()函数来实现。 ```python # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0) ``` 4. 模型训练和预测 使用sklearn库的LogisticRegression()函数来创建逻辑回归模型,并使用训练集进行训练。然后,使用测试集进行预测,并计算模型的准确率、精确率、召回率和F1得分等指标。 ```python # 创建逻辑回归模型 lr = LogisticRegression() # 训练模型 lr.fit(X_train, y_train) # 预测测试集 y_pred = lr.predict(X_test) # 计算模型指标 print('Accuracy:', lr.score(X_test, y_test)) print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred)) ``` 5. 可视化结果 最后,可以使用matplotlib库将结果可视化,例如绘制ROC曲线和混淆矩阵等。 ```python # 绘制ROC曲线 from sklearn.metrics import roc_curve, auc fpr, tpr, thresholds = roc_curve(y_test, y_pred) roc_auc = auc(fpr, tpr) plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() # 绘制混淆矩阵 import seaborn as sns cm = confusion_matrix(y_test, y_pred) sns.heatmap(cm, annot=True, cmap='Blues') plt.xlabel('Predicted') plt.ylabel('True') plt.show() ``` 以上就是用Python实现逻辑回归的步骤。希望对您有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值