Python - 如何在大数据集上计算多项式概率密度函数?

9 投票
1 回答
4201 浏览
提问于 2025-04-15 23:56

我最开始打算用MATLAB来解决这个问题,但它自带的功能有一些限制,不太适合我的需求。NumPy也有同样的问题。

我有两个用制表符分隔的文件。第一个文件显示了氨基酸残基、频率和计数,数据来自一个内部的蛋白质结构数据库,也就是:

A    0.25    1
S    0.25    1
T    0.25    1
P    0.25    1

第二个文件包含了氨基酸的四元组以及它们出现的次数,也就是:

ASTP    1

注意,这里有超过8000个这样的四元组。

根据每种氨基酸的背景出现频率和四元组的计数,我想计算每个四元组的多项式概率密度函数,然后将其作为最大似然计算中的期望值。

多项式分布的公式如下:

f(x|n, p) = n!/(x1!*x2!*...*xk!)*((p1^x1)*(p2^x2)*...*(pk^xk))

其中x是n次试验中每个k种结果的数量,p是固定的概率。在我的计算中,n始终是4。

我已经创建了四个函数来计算这个分布。

# functions for multinomial distribution


def expected_quadruplets(x, y):
    expected = x*y
    return expected

# calculates the probabilities of occurence raised to the number of occurrences

def prod_prob(p1, a, p2, b, p3, c, p4, d):
    prob_prod = (pow(p1, a))*(pow(p2, b))*(pow(p3, c))*(pow(p4, d))
    return prob_prod 


# factorial() and multinomial_coefficient() work in tandem to calculate C, the multinomial coefficient

def factorial(n):
    if n <= 1:
        return 1
    return n*factorial(n-1)


def multinomial_coefficient(a, b, c, d):
    n = 24.0
    multi_coeff =  (n/(factorial(a) * factorial(b) * factorial(c) * factorial(d)))
    return multi_coeff

问题在于如何更好地组织数据,以便高效地进行计算,同时我能看懂(你们写的代码有点难懂 :-)),并且不会出现溢出或运行时错误。

到目前为止,我的数据是用嵌套列表表示的。

amino_acids = [['A', '0.25', '1'], ['S', '0.25', '1'], ['T', '0.25', '1'], ['P', '0.25', '1']]

quadruplets = [['ASTP', '1']]

我最开始打算在一个嵌套的for循环中调用这些函数,但这导致了运行时错误或溢出错误。我知道可以重置递归限制,但我希望能有更优雅的解决方案。

我有以下代码:

for i in quadruplets:
    quad = i[0].split(' ')
    for j in amino_acids:
        for k in quadruplets:
            for v in k:
                if j[0] == v:
                    multinomial_coefficient(int(j[2]), int(j[2]), int(j[2]), int(j[2]))

我还没有真正想好如何将其他函数结合进来。我觉得我现在的嵌套列表安排不是最优的。

我想将字符串'ASTP'中的每个字母与amino_acids中每个子列表的第一个元素进行比较。如果有匹配,我希望通过索引将相应的数值传递给函数。

有没有更好的方法?我能否在循环中将每个氨基酸和四元组的相应数字添加到一个临时数据结构中,然后传递给函数,并在下一次迭代前清空它?

谢谢,S :-)

1 个回答

9

这可能和你最开始的问题有点偏离,但我强烈建议不要直接计算阶乘,因为这样容易导致溢出。相反,你可以利用一个事实:factorial(n) 等于 gamma(n+1)。你可以使用伽马函数的对数,并用加法代替乘法,用减法代替除法。scipy.special 里有一个叫 gammaln 的函数,可以给你伽马函数的对数。

from itertools import izip
from numpy import array, log, exp
from scipy.special import gammaln

def log_factorial(x):
    """Returns the logarithm of x!
    Also accepts lists and NumPy arrays in place of x."""
    return gammaln(array(x)+1)

def multinomial(xs, ps):
    n = sum(xs)
    xs, ps = array(xs), array(ps)
    result = log_factorial(n) - sum(log_factorial(xs)) + sum(xs * log(ps))
    return exp(result)

如果你不想为了 gammaln 而安装 SciPy,这里有一个纯 Python 的替代方案(当然,这个速度会慢一些,而且没有 SciPy 的那种向量化处理):

def gammaln(n):
    """Logarithm of Euler's gamma function for discrete values."""
    if n < 1:
        return float('inf')
    if n < 3:
        return 0.0
    c = [76.18009172947146, -86.50532032941677, \
         24.01409824083091, -1.231739572450155, \
         0.001208650973866179, -0.5395239384953 * 0.00001]
    x, y = float(n), float(n)
    tm = x + 5.5
    tm -= (x + 0.5) * log(tm)
    se = 1.0000000000000190015
    for j in range(6):
        y += 1.0
        se += c[j] / y
    return -tm + log(2.5066282746310005 * se / x)

另一个简单的方法是使用一个 dict 来存储 amino_acids,用氨基酸本身作为索引。根据你原来的 amino_acids 结构,你可以这样做:

amino_acid_dict = dict((amino_acid[0], amino_acid) for amino_acid in amino_acids)
print amino_acid_dict
{"A": ["A", 0.25, 1], "S": ["S", 0.25, 1], "T": ["T", 0.25, 1], "P": ["P", 0.25, 1]}

这样你就可以更方便地通过氨基酸查找频率或计数:

freq_A = amino_acid_dict["A"][1]
count_A = amino_acid_dict["A"][2]

这可以在主循环中为你节省一些时间:

for quadruplet in quadruplets:
    probs = [amino_acid_dict[aa][1] for aa in quadruplet]
    counts = [amino_acid_dict[aa][2] for aa in quadruplet]
    print quadruplet, multinomial(counts, probs)

撰写回答