使用重复条目绘制置信区间和预测区间

2024-01-30

I have a correlation plot for two variables, the predictor variable (temperature) on the x-axis, and the response variable (density) on the y-axis. My best fit least squares regression line is a 2nd order polynomial. I would like to also plot confidence and prediction intervals. The method described in this https://stackoverflow.com/questions/17559408/confidence-and-prediction-intervals-with-statsmodels answer seems perfect. However, my dataset (n=2340) has repeated entries for many (x,y) pairs. My resulting plot looks like this: enter image description here

这是我的相关代码(对上面链接的答案稍作修改):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.sandbox.regression.predstd import wls_prediction_std
import statsmodels.formula.api as smf    
from statsmodels.stats.outliers_influence import summary_table

d = {'temp': x, 'dens': y}
df = pd.DataFrame(data=d)

x = df.temp
y = df.dens

plt.figure(figsize=(6 * 1.618, 6))
plt.scatter(x,y, s=10, alpha=0.3)
plt.xlabel('temp')
plt.ylabel('density')

# points linearly spaced for predictor variable
x1 = pd.DataFrame({'temp': np.linspace(df.temp.min(), df.temp.max(), 100)})

# 2nd order polynomial
poly_2 = smf.ols(formula='dens ~ 1 + temp + I(temp ** 2.0)',   data=df).fit()

# this correctly plots my single 2nd-order poly best-fit line:
plt.plot(x1.temp, poly_2.predict(x1), 'g-', label='Poly n=2  $R^2$=%.2f' % poly_2.rsquared, 
     alpha=0.9)

prstd, iv_l, iv_u = wls_prediction_std(poly_2)

st, data, ss2 = summary_table(poly_2, alpha=0.05)

fittedvalues = data[:,2]
predict_mean_se  = data[:,3]
predict_mean_ci_low, predict_mean_ci_upp = data[:,4:6].T
predict_ci_low, predict_ci_upp = data[:,6:8].T

# check we got the right things
print np.max(np.abs(poly_2.fittedvalues - fittedvalues))
print np.max(np.abs(iv_l - predict_ci_low))
print np.max(np.abs(iv_u - predict_ci_upp))

plt.plot(x, y, 'o')
plt.plot(x, fittedvalues, '-', lw=2)
plt.plot(x, predict_ci_low, 'r--', lw=2)
plt.plot(x, predict_ci_upp, 'r--', lw=2)
plt.plot(x, predict_mean_ci_low, 'r--', lw=2)
plt.plot(x, predict_mean_ci_upp, 'r--', lw=2)

正如预期的那样,打印语句的计算结果为 0.0。 然而,我需要single多项式最佳拟合线以及置信度和预测区间的线(而不是我当前绘图中的多条线)。有任何想法吗?

Update:以下第一个答案来自@kpie,我根据温度订购了置信度和预测区间数组:

data_intervals = {'temp': x, 'predict_low': predict_ci_low, 'predict_upp': predict_ci_upp, 'conf_low': predict_mean_ci_low, 'conf_high': predict_mean_ci_upp}

df_intervals = pd.DataFrame(data=data_intervals)

df_intervals_sort = df_intervals.sort(columns='temp')

This achieved desired results: enter image description here


您需要根据温度对预测值进行排序。我认为*

因此,要获得漂亮的曲线,您必须使用numpy.多项式.多项式.polyfit http://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.polynomial.polynomial.polyfit.html这将返回系数列表。您必须将 x 和 y 数据拆分为 2 个列表,以便它适合该函数。

然后您可以使用以下函数绘制该函数:

def strPolynomialFromArray(coeffs):
    return("".join([str(k)+"*x**"+str(n)+"+" for n,k in enumerate(coeffs)])[0:-1])

from numpy import *
from matplotlib.pyplot import *
x = linespace(-15,45,300) # your smooth line will be made of 300 smooth pieces
y = exec(strPolynomialFromArray(numpy.polynomial.polynomial.polyfit(xs,ys,degree)))
plt.plot(x , y)

您可以更多地研究绘制平滑线here http://matplotlib.org/api/pyplot_api.html只需记住所有直线都是线性样条线,因为连续曲率是无理的。

我相信多项式拟合是通过最小二乘拟合完成的(过程此处描述 http://mathworld.wolfram.com/LeastSquaresFitting.html)

祝你好运!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用重复条目绘制置信区间和预测区间 的相关文章

随机推荐

  • org.hibernate.PersistentObjectException:分离的实体传递给持久异常

    我正在创建一个简单的应用程序 只需使用以下命令将一行插入表中 如果表不存在 则创建它 Java JPA 我附加了一些可运行示例的代码 这是我得到的异常和堆栈跟踪 EXCEPTION gt org hibernate PersistentOb
  • 任意颜色条

    我有使用 imshow 显示的 70 0 范围内的数据 并且希望使用非线性颜色条来表示数据 因为我的模式都在 70 60 范围和 70 范围内 0 范围 我想要使 用任意函数 参见示例 重新缩放 重新规范化颜色条的最简单方法 以便所有模式都
  • 函数返回接口意味着什么?

    我刚刚看到这样的成员函数 public Cat nextCat GameState state 但 Cat 的接口是这样的 public interface Cat void makeCat GameState state 所以我很困惑如何
  • 如何从 java.sql.Timestamp 转换为 java.util.Date?

    i e 这段代码 startDate new Date timestampValue getTime 给我 2012 16 02 05 16 17 when System out println timestampValue return
  • 全日历日双击回调

    我需要实现在 dblclick 上工作的功能 例如 dayClick 回调 我尝试了所有找到的解决方案 但对我来说没有任何作用 例如米歇尔的回答 https stackoverflow com questions 8124460 handl
  • 单击菜单时如何隐藏默认键盘?

    我已经通过在该网站中插入代码尝试了多种方法onCreateOptionsMenu Menu menu 没有成功 我想在单击菜单按钮时隐藏键盘 我有三个 EditText 我可以在其中写入一些数据 并且菜单上有插入 删除 修改数据库的选项 但
  • 带动态标题的管道 ggplot2

    我可以获取数据并在 ggplot 中使用管道制作标题吗 假设我有这样的数据 x lt c 5 17 31 9 17 10 30 28 16 29 14 34 y lt c 1 2 3 4 5 6 7 8 9 10 11 12 day lt
  • 显示高级自定义字段的 JSON API - WordPress

    I am developing a magazine WordPress site that will have a json feed for a Mobile App I set the backend up using Advance
  • 我应该在 Swift Playgrounds 的 .gitignore 文件中包含什么?

    我想使用 Git 对我的 Playground 进行版本控制 但我不确定哪些文件应该被忽略以及哪些文件应该提交 目前我使用以下 gitignore游乐场文件 Xcode user data xcuserdata 还应该有什么 来自官方Swi
  • 使用环境调用 popen

    在我的 Lua 程序中 我必须捕获外部程序的输出 该外部程序需要某些环境变量 所以我这样做 e e e A 100 e e B Hi e e C Test file io popen e bin aprogr 显然 如果环境很大 popen
  • 如何使用Python获取两个PDF文件的差异?

    我需要找出两个 PDF 文件之间的差异 有谁知道任何与Python相关的工具具有直接给出两个PDF的差异的功能吗 你所说的 差异 是什么意思 PDF 文本存在差异或某些布局发生变化 例如 调整了嵌入图形的大小 第一个很容易检测 第二个几乎不
  • SQLITE 数据库在 java 中被锁定(IDE NetBeans)

    当我执行任何操作时 它在数据库中工作 但突然显示数据库已锁定错误 假设这是在一个按钮上执行的操作 private void jButton6ActionPerformed java awt event ActionEvent evt Sah
  • 是否可以在 webpack 中创建自定义解析器?

    当需要模块时我有自己的约定 例如 require components SettingsPanel 应解决require components SettingsPanel SettingsPanel js 有什么方法可以创建这样的解析器吗
  • 在谷歌闭包库中创建自定义事件调度程序时出现问题

    我正在尝试在 google Closure js 库中创建自定义事件调度程序 我将此代码基于 fx 文件夹中的动画类 但我不断收到此错误 goog events 未定义 但我将事件包放在顶部 这是我的代码 goog provide test
  • 如何自动重新连接 Rails 6 PostgreSQL 连接?

    我有一个带有一些工作进程的 Rails 6 应用程序 该应用程序使用 PostgreSQL 作为数据库 有时数据库会重新启动 例如次要版本升级 并且工作人员会失去连接 我希望他们能够自动重新连接 但它没有发生 我尝试使用reconnect
  • GWT 中的字符串格式化程序

    如何在 GWT 中格式化字符串 我做了一个方法 Formatter format new Formatter int matches 0 Formatter formattedString format format d numbers s
  • opencv中的HoughCircles函数可以检测圆内的圆吗?

    我在 OpenCV 中遇到了用于圆检测的 HoughCircles 但它有一个参数指定检测到的圆之间的最小距离 我担心的是 如果两个圆同心 即一个圆在另一个圆内 这是否有效 谢谢 沙尚克 如果两个圆的中心相距足够远 霍夫变换将仅返回 2 个
  • 将当前应用程序作为单实例运行并显示前一个实例

    我刚刚实现了这段保护应用程序单个实例的代码 以免应用程序运行两次 现在我想知道如何显示已经运行的原始应用程序进程 这是我在程序类中的代码 static class Program STAThread static void Main con
  • 合并两个已排序的链表

    这是微软笔试时提出的编程问题之一 我给出了我提出的问题和答案 事情是我的答案 虽然看起来很全面 至少对我来说 但我觉得行数可以减少 这是用 C 语言问的 我是一个 Java 人 但我设法编写了它 我的答案可能包含太多类似 Java 的语法
  • 使用重复条目绘制置信区间和预测区间

    I have a correlation plot for two variables the predictor variable temperature on the x axis and the response variable d