如何在使用 Pandas 滚动相关时处理不一致的结果? 为什么会这样

如何解决如何在使用 Pandas 滚动相关时处理不一致的结果? 为什么会这样

让我先说一下,为了重现这个问题,我需要一个大数据,这是问题的一部分,我无法预测什么时候会出现这种特殊性。无论如何,数据太大(~13k 行,2 列)无法粘贴到问题中,我在帖子末尾添加了一个 pastebin 链接


过去几天我在使用 pandas.core.window.rolling.Rolling.corr 时遇到了一个奇怪的问题。我有一个数据集,我试图在其中计算滚动相关性。这就是问题:

在计算两列(window_size=100a)之间的滚动 (b) 相关性时:一些指数(一个这样的指数是 12981)给出接近 { {1}} 个值(顺序为 0),但理想情况下它应该返回 1e-10nan,(因为一列中的所有值都是常量)。但是,如果我只是计算与该索引有关的独立相关性(ie 包括所述索引的最后 100 行数据),或者对较少数量的行(例如 300 或 1000 行)执行滚动计算到 13k),我得到正确的结果(ie infnan。)

期望:

inf

现在,现实:

>>> df = pd.read_csv('sample_corr_data.csv') # link at the end,## columns = ['a','b']
>>> df.a.tail(100).value_counts()

 0.000000    86
-0.000029     3
 0.000029     3
-0.000029     2
 0.000029     2
-0.000029     2
 0.000029     2
Name: a,dtype: int64

>>> df.b.tail(100).value_counts()     # all 100 values are same
 
6.0    100
Name: b,dtype: int64

>>> df.a.tail(100).corr(df.b.tail(100))
nan                                      # expected,because column 'b' has same value throughout

# Made sure of this using,# 1. np.corrcoef,because pandas uses this internally to calculate pearson moments
>>> np.corrcoef(df.a.tail(100),df.b.tail(100))[0,1]
nan

# 2. using custom function
>>> def pearson(a,b):
        n = a.size
        num = n*np.nansum(a*b) - np.nansum(a)*np.nansum(b)
        den = (n*np.nansum((a**2)) - np.nansum(a)**2)*(n*np.nansum(b**2) - np.nansum(b)**2)
        return num/np.sqrt(den) if den * np.isfinite(den*num) else np.nan

>>> pearson(df.a.tail(100),df.b.tail(100))
nan

这一直持续到 >>> df.a.rolling(100).corr(df.b).tail(3) 12979 7.761921e-07 12980 5.460717e-07 12981 2.755881e-10 # This should have been NaN/inf !! ## Furthermore!! >>> debug = df.tail(300) >>> debug.a.rolling(100).corr(debug.b).tail(3) 12979 7.761921e-07 12980 5.460717e-07 12981 -inf # Got -inf,fine dtype: float64 >>> debug = df.tail(3000) >>> debug.a.rolling(100).corr(debug.b).tail(3) 12979 7.761921e-07 12980 5.460717e-07 12981 inf # Got +inf,still acceptable dtype: float64 行:

9369

当前的解决方法

>>> debug = df.tail(9369)
>>> debug.a.rolling(100).corr(debug.b).tail(3)

12979    7.761921e-07
12980    5.460717e-07
12981             inf
dtype: float64

# then
>>> debug = df.tail(9370)
>>> debug.a.rolling(100).corr(debug.b).tail(3)

12979    7.761921e-07
12980    5.460717e-07
12981    4.719615e-10                    # SPOOKY ACTION IN DISTANCE!!!
dtype: float64

>>> debug = df.tail(10000)
>>> debug.a.rolling(100).corr(debug.b).tail(3)
 
12979    7.761921e-07
12980    5.460717e-07
12981    1.198994e-10                    # SPOOKY ACTION IN DISTANCE!!!    
dtype: float64

据我所知,>>> df.a.rolling(100).apply(lambda x: x.corr(df.b.reindex(x.index))).tail(3) # PREDICTABLY,VERY SLOW! 12979 7.761921e-07 12980 5.460717e-07 12981 NaN Name: a,dtype: float64 # again this checks out using other methods,>>> df.a.rolling(100).apply(lambda x: np.corrcoef(x,df.b.reindex(x.index))[0,1]).tail(3) 12979 7.761921e-07 12980 5.460717e-07 12981 NaN Name: a,dtype: float64 >>> df.a.rolling(100).apply(lambda x: pearson(x,df.b.reindex(x.index))).tail(3) 12979 7.761921e-07 12980 5.460717e-07 12981 NaN Name: a,dtype: float64 的结果应该与以下内容匹配:

series.rolling(n).corr(other_series)

起初我认为这是一个 >>> def rolling_corr(series,other_series,n=100): return pd.Series( [np.nan]*(n-1) + [series[i-n: i].corr(other_series[i-n:i]) for i in range (n,series.size+1)] ) >>> rolling_corr(df.a,df.b).tail(3) 12979 7.761921e-07 12980 5.460717e-07 12981 NaN 问题(因为最初,在某些情况下,我可以通过将列“a”四舍五入到小数点后 5 位或强制转换为 floating-point arithmetic 来解决此问题),但在在这种情况下,无论使用的样本数量如何,它都会存在。因此,float32 肯定存在一些问题,或者至少 rolling 会引起 rolling 问题,具体取决于数据的大小。我检查了 floating-point 的源代码,但找不到可以解释这种不一致的任何内容。现在我很担心,有多少过去的代码受到这个问题的困扰。

这背后的原因是什么?以及如何解决这个问题?如果发生这种情况是因为熊猫更喜欢速度而不是准确性(如建议的 here),这是否意味着我永远无法对大样本可靠地使用 rolling.corr 操作?我如何知道这种不一致会出现的大小?


sample_corr_data.csv:https://pastebin.com/jXXHSv3r

已测试

  • Windows 10、python 3.9.1、pandas 1.2.2、(IPython 7.20)
  • Windows 10、python 3.8.2、pandas 1.0.5、(IPython 7.19)
  • Ubuntu 20.04、python 3.7.7、pandas 1.0.5、(GCC 7.3.0、标准 REPL)
  • CentOS Linux 7(核心)、Python 2.7.5、pandas 0.23.4、(IPython 5.8.0)

注意:不同的操作系统在上述索引处返回不同的值,但都是有限的并且接近 pandas.rolling

解决方法

如果你用滚动总和替换皮尔逊公式中的总和怎么办


def rolling_pearson(a,b,n):
    a_sum = a.rolling(n).sum()
    b_sum = b.rolling(n).sum()
    ab_sum = (a*b).rolling(n).sum()
    aa_sum = (a**2).rolling(n).sum()
    bb_sum = (b**2).rolling(n).sum();
    
    num = n * ab_sum - a_sum * b_sum;
    den = (n*aa_sum - a_sum**2) * (n * bb_sum - b_sum**2)
    return num / den**(0.5)

rolling_pearson(df.a,df.b,100)

             ...     
12977    1.109077e-06
12978    9.555249e-07
12979    7.761921e-07
12980    5.460717e-07
12981             inf
Length: 12982,dtype: float64

为什么会这样

为了回答这个问题,我需要检查实现。因为确实 b 的最后 100 个样本的方差为零,并且滚动相关性计算为 a.cov(b) / (a.var() * b.var())**0.5

经过一番搜索,我找到了滚动方差实现 here,他们使用的方法是 Welford's online algorithm。这个算法很好,因为您可以只使用一次乘法来添加一个样本(与累积和的方法相同),并且您可以使用单个整数除法进行计算。这里用python重写。

def welford_add(existingAggregate,newValue):
    if pd.isna(newValue):
        return s
    (count,mean,M2) = existingAggregate
    count += 1
    delta = newValue - mean
    mean += delta / count
    delta2 = newValue - mean
    M2 += delta * delta2
    return (count,M2)
def welford_remove(existingAggregate,M2) = existingAggregate
    count -= 1
    delta = newValue - mean
    mean -= delta / count
    delta2 = newValue - mean
    M2 -= delta * delta2
    return (count,M2)
def finalize(existingAggregate):
    (count,M2) = existingAggregate
    (mean,variance,sampleVariance) = (mean,M2 / count if count > 0 else None,M2 / (count - 1) if count > 1 else None)
    return (mean,sampleVariance)

在pandas实现中,他们提到了Kahan's summation,这对于获得更好的加法精度很重要,但结果并没有因此得到改善(我没有检查它是否正确实现) .

通过 n=100 应用 Welford 算法

s = (0,0)
for i in range(len(df.b)):
    if i >= n:
        s = welford_remove(s,df.b[i-n])
    s = welford_add(s,df.b[i])
finalize(s)

它给了

(6.000000000000152,4.7853099260919405e-12,4.8336463899918594e-12)

df.b.rolling(100).var() 给出

0                 NaN
1                 NaN
2                 NaN
3                 NaN
4                 NaN
             ...     
12977    6.206061e-01
12978    4.703030e-01
12979    3.167677e-01
12980    1.600000e-01
12981    6.487273e-12
Name: b,Length: 12982,dtype: float64

误差 6.4e-12 略高于直接应用韦尔福德方法给出的 4.83e-12

另一方面,(df.b**2).rolling(n).sum()-df.b.rolling(n).sum()**2/n 为最后一个条目提供 0.0。

0          NaN
1          NaN
2          NaN
3          NaN
4          NaN
         ...  
12977    61.44
12978    46.56
12979    31.36
12980    15.84
12981     0.00
Name: b,dtype: float64

我希望这个解释是令人满意的:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res