改进Cronbach Alpha代码python numpy的性能

u3r8eeie  于 2022-10-30  发布在  Python
关注(0)|答案(3)|浏览(201)

我做了一些计算Cronbach Alpha的代码,但我不太擅长使用lambda函数。有没有办法通过使用lambda函数代替svar()函数,并通过使用numpy数组来摆脱一些for循环,从而减少代码并提高效率?

import numpy as np

def svar(X):
    n = float(len(X))
    svar=(sum([(x-np.mean(X))**2 for x in X]) / n)* n/(n-1.)
    return svar

def CronbachAlpha(itemscores):
    itemvars = [svar(item) for item in itemscores]
    tscores = [0] * len(itemscores[0])
    for item in itemscores:
       for i in range(len(item)):
          tscores[i]+= item[i]
    nitems = len(itemscores)
    #print "total scores=", tscores, 'number of items=', nitems

    Calpha=nitems/(nitems-1.) * (1-sum(itemvars)/ svar(tscores))

    return Calpha

########### Test################

itemscores = [[ 4,14,3,3,23,4,52,3,33,3],
              [ 5,14,4,3,24,5,55,4,15,3]]
print "Cronbach alpha = ", CronbachAlpha(itemscores)
y1aodyip

y1aodyip1#

def CronbachAlpha(itemscores):
    itemscores = numpy.asarray(itemscores)
    itemvars = itemscores.var(axis=1, ddof=1)
    tscores = itemscores.sum(axis=0)
    nitems = len(itemscores)

    return nitems / (nitems-1.) * (1 - itemvars.sum() / tscores.var(ddof=1))

NumPy有一个内置的方差函数。指定ddof=1使用分母N-1,给出样本方差。还有一个内置的sum

ejk8hzay

ejk8hzay2#

正如Julien Marrec提到的,我建议对CronbachAlpha进行以下重构:

def CronbachAlpha(itemscores):
    # cols are items, rows are observations
    itemscores = np.asarray(itemscores)
    itemvars = itemscores.var(axis=0, ddof=1)
    tscores = itemscores.sum(axis=1)
    nitems = len(itemscores.columns)

    return (nitems / (nitems-1)) * (1 - (itemvars.sum() / tscores.var(ddof=1)))
cclgggtu

cclgggtu3#

和其他答案一样,只是有点像Python。X是一个数据矩阵--也就是说,行是样本,列是项。X可以是一个numpy数组或PandasDataFrame。

def cronbach_alpha(X):
    num_items = X.shape[1]
    sum_of_item_variances = X.var(axis=0).sum()
    variance_of_sum_of_items = X.sum(axis=1).var()
    return num_items/(num_items - 1)*(1 - sum_of_item_variances/variance_of_sum_of_items)

(It不需要指定ddof,因为该项出现在分母和分子中,并被取消。)

相关问题