逻辑回归实战

简介

  Logistic回归是一种机器学习分类算法,用于预测分类因变量的概率。 在逻辑回归中,因变量是一个二进制变量,包含编码为1(是,成功等)或0(不,失败等)的数据。 换句话说,逻辑回归模型预测P(Y = 1)是X的函数。

  数据

  该数据集来自UCI机器学习库,它与葡萄牙银行机构的直接营销活动(电话)有关。 分类目标是预测客户是否将购买定期存款(变量y)。 数据集可以从这里下载或者here

import pandas as pd
import numpy as np
from sklearn import preprocessing
import matplotlib.pyplot as plt 
plt.rc("font", size=14)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
import seaborn as sns
sns.set(style="white")
sns.set(style="whitegrid", color_codes=True)
data = pd.read_csv('bank.csv', header=0)
data = data.dropna()
print(data.shape)
print(list(data.columns))
数据集提供银行客户的信息。 它包括41,188条记录和21个字段。

变量

  • age (numeric)
  • job : type of job (categorical: “admin”, “blue-collar”, “entrepreneur”, “housemaid”, “management”, “retired”, “self-employed”, “services”, “student”, “technician”, “unemployed”, “unknown”)
  • marital : marital status (categorical: “divorced”, “married”, “single”, “unknown”)
  • education (categorical: “basic.4y”, “basic.6y”, “basic.9y”, “high.school”, “illiterate”, “professional.course”, “university.degree”, “unknown”)
  • default: has credit in default? (categorical: “no”, “yes”, “unknown”)
  • housing: has housing loan? (categorical: “no”, “yes”, “unknown”)
  • loan: has personal loan? (categorical: “no”, “yes”, “unknown”)
  • contact: contact communication type (categorical: “cellular”, “telephone”)
  • month: last contact month of year (categorical: “jan”, “feb”, “mar”, …, “nov”, “dec”)
  • day_of_week: last contact day of the week (categorical: “mon”, “tue”, “wed”, “thu”, “fri”)
  • duration: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y=’no’). The duration is not known before a call is performed, also, after the end of the call, y is obviously known. Thus, this input should only be included for benchmark purposes and should be discarded if the intention is to have a realistic predictive model
  • campaign: number of contacts performed during this campaign and for this client (numeric, includes last contact)
  • pdays: number of days that passed by after the client was last contacted from a previous campaign (numeric; 999 means client was not previously contacted)
  • previous: number of contacts performed before this campaign and for this client (numeric)
  • poutcome: outcome of the previous marketing campaign (categorical: “failure”, “nonexistent”, “success”)
  • emp.var.rate: employment variation rate — (numeric)
  • cons.price.idx: consumer price index — (numeric)
  • cons.conf.idx: consumer confidence index — (numeric)
  • euribor3m: euribor 3 month rate — (numeric)
  • nr.employed: number of employees — (numeric)

  预测变量

  y - 客户是否订购了定期存款? (二进制:“1”表示“是”,“0”表示“否”)

  数据集的教育列有许多类别,我们需要减少类别以获得更好的建模。 教育专栏有以下几类: 
(41188, 21) ['age', 'job', 'marital', 'education', 'default', 'housing', 'loan', 'contact', 'month', 'day_of_week', 'duration', 'campaign', 'pdays', 'previous', 'poutcome', 'emp_var_rate', 'cons_price_idx', 'cons_conf_idx', 'euribor3m', 'nr_employed', 'y']

data['education'].unique()

array(['basic.4y', 'unknown', 'university.degree', 'high.school',
       'basic.9y', 'professional.course', 'basic.6y', 'illiterate'],
      dtype=object)

Let us group "basic.4y", "basic.9y" and "basic.6y" together and call them "basic".

data['education']=np.where(data['education'] =='basic.9y', 'Basic', data['education'])
data['education']=np.where(data['education'] =='basic.6y', 'Basic', data['education'])
data['education']=np.where(data['education'] =='basic.4y', 'Basic', data['education'])

如果不懂np.where函数,可以看这里

After grouping, this is the columns

data['education'].unique()
array(['Basic', 'unknown', 'university.degree', 'high.school',
       'professional.course', 'illiterate'], dtype=object)

1.1  Data exploration

1.1  Data exploration¶
0    36548
1     4640
Name: y, dtype: int64

来源:1.https://towardsdatascience.com/building-a-logistic-regression-in-python-step-by-step-becd4d56c9c8

             2.http://www.cnblogs.com/jin-liang/p/9534801.html

             3.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你在学习Python数据分析的时候,是否遇到过在这些问题? 别慌!这些都是数据科学入门常见问题。从入门到上手再到解决实际问题,数据科学看似复杂,但如果你掌握了正确的学习方法,完全可以极速入门。 【职场人进阶必备  数据分析/挖掘一点通】 如今的职场上,90%以上的岗位都会涉及数据问题。 以产品文案岗位为例,在一个新产品推向市场之前,文案需要考虑: 此时,可以关注一下市场上已有的相关产品推广数据,如:哪些文案打开率更高?哪些文案转化更好?目标用户的购买习惯如何? 以此作为下一步工作开展的依据,对产品文案工作者来说,可以少走很多弯路。 学会数据分析/挖掘,等于站巨人的肩膀上工作,轻松且高效。 【爬虫、数据分析、数据挖掘知识点三合一】数据问题一网打尽 本课程将知识点悉数融入实战项目,不空谈语法,帮助学员在实践中获取知识,目标是:让学员能自主完成数据采集、数据分析与数据挖掘。 学习完本课程,你可以熟练掌握: 【实战案例超实用,轻松拥有“睡后收入”!】 本课程以股票案例为主线,串联爬虫、数据分析以及数据挖掘多个知识点。 通过实战案例演练,你可以全面掌握股票收益的分析和预判方法,在收获新技能的同时,也有机会获得“睡后收入”! 四大优势: 三重权益:
本次逻辑回归实战练习我们将使用一个经典的数据集——“学生录取数据集”。 该数据集包含三个特征变量:考试1成绩、考试2成绩、录取结果(0表示未被录取,1表示被录取)。 我们的目标是构建一个逻辑回归模型,根据学生的两次考试成绩预测学生是否会被录取。 步骤1:导入必要的库和数据集 我们需要导入以下库: - pandas:用于数据加载和处理 - numpy:用于矩阵计算 - matplotlib:用于绘制数据可视化图表 - sklearn:用于构建逻辑回归模型和评估模型性能 ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.metrics import classification_report ``` 接着,我们加载数据集: ``` data = pd.read_csv('https://raw.githubusercontent.com/cryad/Logistic_Regression/master/exam_scores.csv') ``` 步骤2:数据探索和可视化 我们将使用pandas和matplotlib库对数据集进行探索和可视化,以便更好地理解数据和评估建模可行性。 首先,我们可以使用head()方法查看数据集中的前几行: ``` data.head() ``` 输出结果: ``` exam1 score exam2 score 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 ``` 接着,我们绘制一个散点图,将考试1成绩和考试2成绩作为横纵坐标,录取结果用颜色进行区分: ``` plt.scatter(data['exam1 score'], data['exam2 score'], c=data['admitted']) plt.xlabel('Exam 1 Score') plt.ylabel('Exam 2 Score') plt.show() ``` 输出结果: ![img](https://cdn.jsdelivr.net/gh/cryad/Logistic_Regression/images/exam_scores.png) 可以看到,蓝色点表示未被录取的学生,而绿色点表示被录取的学生。我们可以发现,在考试1和考试2成绩都高于一定水平的情况下,学生被录取的概率较大,这也与我们的人生经验相符。 步骤3:数据预处理 在建模之前,我们需要将数据集分为训练集和测试集,并将特征变量和目标变量分开,并进行一些必要的数据处理。 我们将使用train_test_split()方法将数据集分为70%的训练集和30%的测试集: ``` X_train, X_test, y_train, y_test = train_test_split(data[['exam1 score', 'exam2 score']], data['admitted'], test_size=0.3, random_state=42) ``` 接着,我们需要对特征变量进行标准化处理,以确保每个特征变量的重要性对模型一样,避免因为某个特征值过大而导致模型过于关注这个特征变量。我们可以使用sklearn的StandardScaler()方法对数据进行标准化处理: ``` from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) ``` 步骤4:建立并训练模型 有了标准化的特征变量和目标变量,我们可以开始建立逻辑回归模型了。 在scikit-learn中,建立逻辑回归模型非常简单,只需要在构造函数中指定参数即可: ``` model = LogisticRegression() ``` 接着,我们使用fit()方法训练模型: ``` model.fit(X_train_scaled, y_train) ``` 步骤5:模型评估和预测 模型训练完成后,我们需要对模型进行评估,以了解模型在不同情况下的预测性能。 我们可以使用predict()方法进行预测,然后使用classification_report()方法生成预测性能报告: ``` y_pred = model.predict(X_test_scaled) print(classification_report(y_test, y_pred)) ``` 输出结果: ``` precision recall f1-score support 0 0.82 0.94 0.88 18 1 0.93 0.78 0.85 17 micro avg 0.87 0.87 0.87 35 macro avg 0.87 0.86 0.87 35 weighted avg 0.87 0.87 0.87 35 ``` 我们可以看到,在测试集中,模型的整体准确率为0.87,这是一个很不错的性能。 最后,我们可以使用前面绘制散点图的方法,绘制模型在训练集和测试集上的预测结果: ``` plt.scatter(X_train['exam1 score'], X_train['exam2 score'], c=y_train) plt.xlabel('Exam 1 Score') plt.ylabel('Exam 2 Score') plt.title('Training Set') plt.show() plt.scatter(X_test['exam1 score'], X_test['exam2 score'], c=y_pred) plt.xlabel('Exam 1 Score') plt.ylabel('Exam 2 Score') plt.title('Test Set') plt.show() ``` 输出结果: ![img](https://cdn.jsdelivr.net/gh/cryad/Logistic_Regression/images/training_set.png) ![img](https://cdn.jsdelivr.net/gh/cryad/Logistic_Regression/images/test_set.png) 我们可以看到,模型正确地识别了训练集和测试集中的大多数数据点,但是在测试集中仍然有一些点被错误地标记。这表明模型还有进一步的优化空间,可以通过调整模型超参数和特征选择等方法来提高模型性能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值