你可以使用seaborn数据可视化库中的regplot()函数来绘制Python中的逻辑回归曲线:
import seaborn as sns
sns.regplot(x=x, y=y, data=df, logistic=True, ci=None)
下面的例子展示了如何在实践中使用这种语法。
例子:在Python中绘制一个Logistic回归曲线
对于这个例子,我们将使用《统计学习入门》一书中的Default数据集。我们可以使用下面的代码来加载和查看数据集的摘要。
#import dataset from CSV file on Github
url = "https://raw.githubusercontent.com/Statology/Python-Guides/main/default.csv"
data = pd.read_csv(url)
#view first six rows of dataset
data[0:6]
default student balance income
0 0 0 729.526495 44361.625074
1 0 1 817.180407 12106.134700
2 0 0 1073.549164 31767.138947
3 0 0 529.250605 35704.493935
4 0 0 785.655883 38463.495879
5 0 1 919.588530 7491.558572
这个数据集包含10,000个个体的以下信息:
- default:表示一个人是否违约。
- 学生:表示一个人是否是学生。
- 余额:个人携带的平均余额。
- 收入:个人的收入。
假设我们想建立一个逻辑回归模型,用 "余额 "来预测某个人违约的概率。
我们可以使用下面的代码来绘制一条逻辑回归曲线:
#define the predictor variable and the response variable
x = data['balance']
y = data['default']
#plot logistic regression curve
sns.regplot(x=x, y=y, data=data, logistic=True, ci=None)
x轴显示预测变量 "余额 "的值,y轴显示预测的违约概率。
我们可以清楚地看到,余额的数值越高,个人违约的概率就越高。
注意,你也可以使用scatter_kws和line_kws来修改图中的点和曲线的颜色。
#define the predictor variable and the response variable
x = data['balance']
y = data['default']
#plot logistic regression curve with black points and red line
sns.regplot(x=x, y=y, data=data, logistic=True, ci=None),
scatter_kws={'color': 'black'}, line_kws={'color': 'red'})
请自由选择你想在图中使用的任何颜色。
其他资源
下面的教程提供了关于逻辑回归的额外信息: