在 Python 中的散点图上计算并绘制 95% 范围的数据

Calculate and plot 95% range of data on scatter plot in Python

我想知道,对于以分钟为单位的给定预测通勤行程持续时间,我可能期望的实际通勤时间范围。例如,如果 Google 地图预测我的通勤时间为 20 分钟,我应该期望的最短和最长通勤时间是多少(可能是 95% 的范围)?

让我们将我的数据导入 pandas:

%matplotlib inline
import pandas as pd

commutes = pd.read_csv('https://raw.githubusercontent.com/blokeley/commutes/master/commutes.csv')
commutes.tail()

这给出:

我们可以轻松地创建一个图表,显示原始数据的散点、回归曲线和该曲线上的 95% 置信区间:

import seaborn as sns

# Create a linear model plot
sns.lmplot('prediction', 'duration', commutes);

我现在如何计算和绘制实际通勤时间与预测时间的 95% 范围?

换句话说,如果 Google 地图预测我的通勤时间为 20 分钟,那么看起来实际时间可能在 14 到 28 分钟之间。计算或绘制此范围会很棒。

在此先感谢您的帮助。

您的数据应该符合 3 sigma std dev 以内的高斯分布,这将代表您结果的 96% 左右。

关注正态分布。

实际通勤时间与预测之间的关系应该是线性的,所以我可以使用 quantile regression:

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf

# Import data and print the last few rows
commutes = pd.read_csv('https://raw.githubusercontent.com/blokeley/commutes/master/commutes.csv')

# Create the quantile regression model
model = smf.quantreg('duration ~ prediction', commutes)

# Create a list of quantiles to calculate
quantiles = [0.05, 0.25, 0.50, 0.75, 0.95]

# Create a list of fits
fits = [model.fit(q=q) for q in quantiles]

# Create a new figure and axes
figure, axes = plt.subplots()

# Plot the scatter of data points
x = commutes['prediction']
axes.scatter(x, commutes['duration'], alpha=0.4)

# Create an array of predictions from the minimum to maximum to create the regression line
_x = np.linspace(x.min(), x.max())

for index, quantile in enumerate(quantiles):
    # Plot the quantile lines
    _y = fits[index].params['prediction'] * _x + fits[index].params['Intercept']
    axes.plot(_x, _y, label=quantile)

# Plot the line of perfect prediction
axes.plot(_x, _x, 'g--', label='Perfect prediction')
axes.legend()
axes.set_xlabel('Predicted duration (minutes)')
axes.set_ylabel('Actual duration (minutes)');

这给出:

非常感谢我的同事 Philip 提供的分位数回归提示。