Kev*_*vin 5 python numpy vectorization scipy
是否可以使用费舍尔精确检验的矢量化来优化此计算?num_cases>〜1000000 时,运行时很麻烦。
import numpy as np
from scipy.stats import fisher_exact
num_cases = 100
randCounts = np.random.random_integers(100,size=(num_cases,4))
def testFisher(randCounts):
return [fisher_exact([[r[0],r[1]],[r[2], r[3]]])[0] for r in randCounts]
In [6]: %timeit testFisher(randCounts)
1 loops, best of 3: 524 ms per loop
Run Code Online (Sandbox Code Playgroud)
这是使用Fisher中实现的 Fisher 的答案。我在 numpy 中手动计算 OR。
安装:
# pip install fisher
# or
# conda install -c bioconda fisher
Run Code Online (Sandbox Code Playgroud)
设置:
import numpy as np
np.random.seed(0)
num_cases = 100
c = np.random.randint(100,size=(num_cases,4), dtype=np.uint)
# head, i.e.
c[:5]
# array([[44, 47, 64, 67],
# [67, 9, 83, 21],
# [36, 87, 70, 88],
# [88, 12, 58, 65],
# [39, 87, 46, 88]], dtype=uint64)
Run Code Online (Sandbox Code Playgroud)
执行:
from fisher import pvalue_npy
_, _, twosided = pvalue_npy(c[:, 0], c[:, 1], c[:, 2], c[:, 3])
odds = (c[:, 0] * c[:, 3]) / (c[:, 1] * c[:, 2])
print("result fast p and odds", odds[0], twosided[0])
# result fast p and odds 0.9800531914893617 1.0
print("result slow", fisher_exact([[c[0][0], c[0][1]], [c[0][2], c[0][3]]]))
# result slow (0.9800531914893617, 1.0)
Run Code Online (Sandbox Code Playgroud)
请注意,对于一百万行只需要两秒钟:)
另外,要计算近似的 OR,您可能需要在查找优势比之前向表中添加伪计数。这通常比 inf 更有趣,因为您可以比较近似值:):
c2 = c + 1
odds = (c2[:, 0] * c2[:, 3]) / (c2[:, 1] * c2[:, 2])
Run Code Online (Sandbox Code Playgroud)
编辑:
从 0.0.61>= 此方法作为 包含在pyranges中pr.stats.fisher_exact。
| 归档时间: |
|
| 查看次数: |
627 次 |
| 最近记录: |