对统计处理过的R2值python使用“groupby”

2024-09-29 06:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

对于我的研究,我有一个R2值的具体计算。它不是使用线性回归函数直接计算的R2值。在

我使用的代码是统计处理过的R2值(标记为“最佳R2”)。我得到了整个x轴和y轴的R2值。但是,数据中有多个“测试事件”。这意味着我需要单个“测试事件”的R2值

到目前为止,我用来计算R2值的代码(以及我需要的输出)如下:


import numpy, scipy,pandas as pd, matplotlib
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import scipy.stats
import copy
df=pd.read_excel("I:/Python/Excel.xlsx")
df.head()

xyDataPairs = df[['x', 'y']].values.tolist()

minDataPoints = len(xyDataPairs) - 1
# utility function
def UniqueCombinations(items, n):
    if n==0:
        yield []
    else:
        for i in range(len(items)):
            for cc in UniqueCombinations(items[i+1:],n-1):
                yield [items[i]]+cc

bestR2 = 0.0
bestDataPairCombination = []
bestParameters = []

for pairs in UniqueCombinations(xyDataPairs, minDataPoints):
    x = []
    y = []
    for pair in pairs:
        x.append(pair[0])
        y.append(pair[1])
    fittedParameters = numpy.polyfit(x, y, 1) # straight line
    modelPredictions = numpy.polyval(fittedParameters, x)
    absError = modelPredictions - y
    Rsquared = 1.0 - (numpy.var(absError) / numpy.var(y))
    if Rsquared > bestR2:
        bestR2 = Rsquared
        bestDataPairCombination = copy.deepcopy(pairs)
        bestParameters = copy.deepcopy(fittedParameters)
    print('best R2', bestR2)

以上最佳R2值适用于整个x和y列。 但是,假设我必须将整个数据集分成四个事件,每个事件都有自己的R2值。那我怎么弄到呢? 我需要得到上面的代码给我的'bestR2'值与'groupby'有关'测试事件。 它是一个R2值,经过高度处理以适合我的研究项目所需的结果。 因此,直接使用Linregress是没有帮助的,这就是我计算bestR2不同的原因。 简而言之:我需要用上述方法计算的多个测试事件的最佳R2值。在


结果如下:

^{pr2}$

谢谢你的阅读!!在


Tags: 代码inimportnumpydffor事件items
1条回答
网友
1楼 · 发布于 2024-09-29 06:22:35

您可以按“test_event”列分组,并应用自定义函数为每个组计算最佳的\u r2值。自定义函数只是您所需逻辑的包装器(这里称为compute_best_r2)。在

以下是一个可行的解决方案:

import numpy, pandas as pd
import copy

df=pd.read_excel("...")

def UniqueCombinations(items, n):
    if n==0:
        yield []
    else:
        for i in range(len(items)):
            for cc in UniqueCombinations(items[i+1:],n-1):
                yield [items[i]]+cc


def compute_best_r2(data):
    xyDataPairs = data[['x', 'y']].values.tolist()
    minDataPoints = len(xyDataPairs)
    bestR2 = 0.0
    bestDataPairCombination = []
    bestParameters = []

    for pairs in UniqueCombinations(xyDataPairs, minDataPoints):
        x = []
        y = []
        for pair in pairs:
            x.append(pair[0])
            y.append(pair[1])
        fittedParameters = numpy.polyfit(x, y, 1) # straight line
        modelPredictions = numpy.polyval(fittedParameters, x)
        absError = modelPredictions - y
        Rsquared = 1.0 - (numpy.var(absError) / numpy.var(y))
        if Rsquared > bestR2:
            bestR2 = Rsquared
            bestDataPairCombination = copy.deepcopy(pairs)
            bestParameters = copy.deepcopy(fittedParameters)
    data['best_r2'] = bestR2
    return data

df_with_best_r2 = df.groupby(['test_event']).apply(compute_best_r2)
result = df_with_best_r2[['test_event', 'best_r2']].groupby(['test_event']).agg(['first']).reset_index()[['test_event', 'best_r2']]
result.columns = result.columns.droplevel(-1)

请注意,我将minDataPoints改为len(xyDataPairs),而不是{},因为它看起来像一个bug,请确保这是您想要的。在

我用这个样本数据进行了测试:

^{pr2}$

其结果是:

   test_event   best_r2
0           1  0.705464
1           2  1.000000

相关问题 更多 >