根据两个预先计算的直方图报告两个样本的 K-S 统计量

2024-05-13

Problem:

在这里,我绘制了存储在文本文件中的 2 个数据集(在列表中)dataset)每个包含 218 亿个数据点。这使得数据太大而无法作为数组保存在内存中。我仍然能够将它们绘制为直方图,但我不确定如何通过2 样本KS测试 http://docs.scipy.org/doc/scipy-0.15.1/reference/generated/scipy.stats.ks_2samp.html。这是因为我无法弄清楚如何访问 plt 对象中的每个直方图。

Example:

这是一些生成虚拟数据的代码:

mu = [100, 120]
sigma = 30
dataset = ['gsl_test_1.txt', 'gsl_test_2.txt']
for idx, file in enumerate(dataset):
    dist = np.random.normal(mu[idx], sigma, 10000)
    with open(file, 'w') as g:
        for s in dist:
            g.write('{}\t{}\t{}\n'.format('stuff', 'stuff', str(s)))

这会生成我的两个直方图(使here https://stackoverflow.com/questions/37082402/how-to-build-or-precompute-a-histogram-from-a-file-too-large-for-memory):

chunksize = 1000
dataset = ['gsl_test_1.txt', 'gsl_test_2.txt']
for fh in dataset:
    # find the min, max, line qty, for bins
    low = np.inf
    high = -np.inf

    loop = 0
    for chunk in pd.read_table(fh, header=None, chunksize=chunksize, delimiter='\t'):
        low = np.minimum(chunk.iloc[:, 2].min(), low)
        high = np.maximum(chunk.iloc[:, 2].max(), high)
        loop += 1
    lines = loop*chunksize

    nbins = math.ceil(math.sqrt(lines))   

    bin_edges = np.linspace(low, high, nbins + 1)
    total = np.zeros(nbins, np.int64)  # np.ndarray filled with np.uint32 zeros, CHANGED TO int64

    for chunk in pd.read_table(fh, header=None, chunksize=chunksize, delimiter='\t'):

        # compute bin counts over the 3rd column
        subtotal, e = np.histogram(chunk.iloc[:, 2], bins=bin_edges)  # np.ndarray filled with np.int64

        # accumulate bin counts over chunks
        total += subtotal


    plt.hist(bin_edges[:-1], bins=bin_edges, weights=total)
    plt.savefig('gsl_test_hist.svg')

问题:

Most KS 统计的示例 https://stackoverflow.com/questions/10884668/two-sample-kolmogorov-smirnov-test-in-python-scipy使用两个原始数据/观察/点/等数组,但我没有足够的内存来使用这种方法。根据上面的示例,我如何访问这些预先计算的垃圾箱(从'gsl_test_1.txt' and 'gsl_test_2.txt'计算两个分布之间的 KS 统计量?

奖励业力:在图表上记录 KS 统计量和 p 值!


我稍微清理了一下你的代码。写信给StringIO所以它比写入文件更精简。设置默认氛围 w/seaborn代替matplotlib使其看起来更现代。这bins如果您希望统计测试保持一致,则两个样本的阈值应该相同。我认为如果你迭代并以这种方式制作垃圾箱,整个事情可能会比需要的时间更长。Counter可能很有用,因为您只需循环一次...而且您将能够制作相同的垃圾箱大小。将浮点数转换为整数,因为您将它们合并在一起。from collections import Counter then C = Counter() and C[value] += 1。你会有一个dict最后你可以从那里制作垃圾箱list(C.keys())。这会很好,因为你的数据是如此粗糙。另外,你应该看看是否有办法做chunksize with numpy代替pandas b/c numpy索引速度更快。尝试一个%timeit for DF.iloc[i,j] and ARRAY[i,j]你就会明白我的意思了。我将其中大部分内容编写为一个函数,以尝试使其更加模块化。

import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
from io import StringIO
from scipy.stats import ks_2samp
import seaborn as sns; sns.set()

%matplotlib inline

#Added seaborn b/c it looks mo betta

mu = [100, 120]
sigma = 30

def write_random(file,mu,sigma=30):
    dist = np.random.normal(mu, sigma, 10000)
    for i,s in enumerate(dist):
        file.write('{}\t{}\t{}\n'.format("label_A-%d" % i, "label_B-%d" % i, str(s)))
    return(file)

#Writing to StringIO instead of an actual file
gs1_test_1 = write_random(StringIO(),mu=100)
gs1_test_2 = write_random(StringIO(),mu=120)

chunksize = 1000

def make_hist(fh,ax):
    # find the min, max, line qty, for bins
    low = np.inf
    high = -np.inf

    loop = 0

    fh.seek(0)
    for chunk in pd.read_table(fh, header=None, chunksize=chunksize, sep='\t'):
        low = np.minimum(chunk.iloc[:, 2].min(), low) #btw, iloc is way slower than numpy array indexing
        high = np.maximum(chunk.iloc[:, 2].max(), high) #you might wanna import and do the chunks with numpy
        loop += 1
    lines = loop*chunksize

    nbins = math.ceil(math.sqrt(lines))   

    bin_edges = np.linspace(low, high, nbins + 1)
    total = np.zeros(nbins, np.int64)  # np.ndarray filled with np.uint32 zeros, CHANGED TO int64

    fh.seek(0)
    for chunk in pd.read_table(fh, header=None, chunksize=chunksize, delimiter='\t'):

        # compute bin counts over the 3rd column
        subtotal, e = np.histogram(chunk.iloc[:, 2], bins=bin_edges)  # np.ndarray filled with np.int64

        # accumulate bin counts over chunks
        total += subtotal

    plt.hist(bin_edges[:-1], bins=bin_edges, weights=total,axes=ax,alpha=0.5)

    return(ax,bin_edges,total)

#Make the plot canvas to write on to give it to the function
fig,ax = plt.subplots()

test_1_data = make_hist(gs1_test_1,ax)
test_2_data = make_hist(gs1_test_2,ax)

#test_1_data[1] == test_2_data[1] The bins should be the same if you're going try and compare them...
ax.set_title("ks: %f, p_in_the_v: %f" % ks_2samp(test_1_data[2], test_2_data[2]))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据两个预先计算的直方图报告两个样本的 K-S 统计量 的相关文章

随机推荐

  • ORDER BY id 或 date_created 显示最新结果?

    我有一个表 实际上有几个 我想首先从中获取最新条目的结果 这是我的ORDER BY条款选项 date created INT 从不改变值 id 当然是INT AUTO INCRMENT 两列应同等地代表记录插入的顺序 我自然会使用date
  • 为单个方法引用大 DLL

    我想在 C 中使用大型类库 dll 中的单个方法 是否有性能或其他方面的缺点 我应该使用反射工具 读取 方法代码并将其复制粘贴到我的项目中吗 更新 硬盘空间不是问题 我的应用程序是网络应用程序 是否有性能或其他方面的缺点 唯一真正重要的是可
  • 如何在WPF中使用一次性视图模型?

    如果视图模型引用非托管资源或具有事件处理程序 例如调度程序计时器上的处理已过去 如何确保视图模型得到正确处理 在第一种情况下 终结器是一种选择 虽然并不理想 但在后者中 它永远不会被调用 我们如何判断何时不再有视图附加到视图模型 我通过执行
  • 如何在控制器内部使用 auto_link

    在我的控制器中 我需要构建一个 JSON 对象 如何在控制器内使用 auto link 现在它错误 NoMethodError undefined method mail to for
  • Apollo 更新查询未调用?

    我正在 GitHunt React 和 GitHunt API 中研究 Apollo pub sub 当我运行这些应用程序并输入新评论时 评论将通过调用提交来保存 然后 updateQueries 代码块在此处运行 const Commen
  • 具有自签名证书的 Alamofire / ServerTrustPolicy

    我想使用 Alamofire 通过带有自签名证书的 https 连接与我的服务器进行通信 我的环境在本地主机上运行 我尝试连接 但响应始终如下所示 Success false Response String nil 我用下面的代码完成了它
  • 如何在 Linq where 子句中指定动态字段名称?

    如果您创建一个包含 Linq 条件的 Filter 对象 该对象通常位于如下的 where 子句中 var myFilterObject FilterFactory GetBlank myFilterObject AddCondition
  • 如何使用 QuerySelector 获得第二个匹配项?

    以下语句给出了该类的第一个元素titanic element document querySelector titanic 我如何检索具有相同类的第二个元素 Use document querySelectorAll https devel
  • 我想使用对话框显示两个数字选择器

    我试图仅使用 java 在对话框上显示两个数字选择器 代码正在工作 但我无法将其排列为相等的宽度 这是我的代码 RelativeLayout relative new RelativeLayout mContext final Number
  • Fiddler 会话对象文档

    在哪里可以找到有关 Fiddler Session 对象的属性和方法的文档 我正在 Fiddler 中创建一些自定义规则 js 以进行故障排除 安装脚本编辑器并单击 视图 gt 类资源管理器 http www telerik com dow
  • 如何在模型更改时停止ListView“跳跃”

    我需要做什么 我需要创建一个聊天窗口用一个ListView在 QML 中存储聊天消息 我设置listView positionViewAtEnd 以便跟踪最后的消息 我禁用positionViewAtEnd当我向上滚动时 我可以阅读过去的消
  • 使用 Python-AppKit-Objective C 转换为预组合 Unicode 字符串

    苹果公司的这份文件技术问答 QA1235 http developer apple com qa qa2001 qa1235 html描述了一种将 unicode 字符串从组合版本转换为分解版本的方法 由于我对包含某些字符 例如重音符号 的
  • 如何在编译时生成嵌套循环

    我有一个整数N我在编译时就知道了 我也有一个标准 数组保存描述形状的整数N维数组 我想在编译时使用元编程技术生成嵌套循环 如下所述 constexpr int N 4 constexpr std array
  • 如何在 Ruby 中列出局部变量?

    def method a 3 b 4 some method that gives a b end 局部变量 http ruby doc org core Kernel html method i local variables 它输出符号
  • 在 TinyMCE 中插入换行符而不是

    我已按如下方式初始化 TinyMCE 我想在用户按 Enter 键而不是段落时强制换行 我正在尝试关注 但没有成功 我正在使用 TinyMCE 版本 3 3 8 tinyMCE init mode exact theme advanced
  • Travis CI 与 Clang 3.4 和 C++11

    Travis CI 是否可以与支持 C 11 的 Clang 一起使用 我想要 Clang 而不是 GCC 我已经在 Travis CI 中使用了 GCC 4 8 看来预安装的版本不支持 C 11 我安装任何新版本的所有尝试都结束了因为这个
  • Express.js - 监听关闭

    我有一个使用 Express 的 Node js 应用程序 在该应用程序中 我有一个如下所示的块 const app require app const port process env PORT 8080 const server app
  • T-SQL 按最旧日期和唯一类别选择行

    我正在使用 Microsoft SQL 我有一个表 其中包含按两个不同类别存储的信息和一个日期 例如 ID Cat1 Cat2 Date Time Data 1 1 A 11 00 456 2 1 B 11 01 789 3 1 A 11
  • 如何在 Visual Studio Code 中缩进/格式化所选代码?

    我想缩进 Visual Studio Code 中的特定代码部分 I read 如何在 Visual Studio Code 中设置代码格式 https stackoverflow com questions 29973357 它提供了缩进
  • 根据两个预先计算的直方图报告两个样本的 K-S 统计量

    Problem 在这里 我绘制了存储在文本文件中的 2 个数据集 在列表中 dataset 每个包含 218 亿个数据点 这使得数据太大而无法作为数组保存在内存中 我仍然能够将它们绘制为直方图 但我不确定如何通过2 样本KS测试 http