改变分解分布以匹配更多的聚合水平分布

Shifting disaggregate distribution to match more aggregate level distribution

我遇到的本质上是分配问题。

我有: 我对小的地理区域有观察,比如人口普查区。对于每个人,我都有四个不同年龄组的人数。每个区域都属于一个分区。

现在,我知道小区域分布并不完全正确,因为我知道正确的分布——在更高的聚合层次,分区层次,更细道级数据在求和时显示不同的组总数。

我想要的: 我想调整我的 tract-level,分解分布在四个组中,因此它与已知正确的这四个组中的汇总级分布一致,但保留 tract-level 分布的信号——即根据更粗略的数据进行调整,但不要将其丢弃 window.

然后,我想做的是改变边缘地区的人口数量,满足以下标准,前两个是最重要的(我意识到在满足所有这些):

  1. 汇总后,它应该与次区域总数相匹配。
  2. 调整不应改变道级人口。
  3. 现有的空间分布不应发生实质性变化,但我只是根据新的次区域总数进行了微调
  4. 理想情况下,调整应该是相等的table——即调整不应该只针对几条记录,而应该更多地分布在每个地区。

下面是模拟数据和占位符代码:

一、小面积数据:

n=1000
np.random.seed(123)
df_small_area_scale = pd.DataFrame(data={
        'grp1':np.random.randint(10,250,n),
        'grp2':np.random.randint(10,250,n),
        'grp3':np.random.randint(10,250,n),
        'grp4':np.random.randint(10,250,n),
        'subregion': np.random.choice(['A', 'B', 'C', 'D', 'E'],n),
        'tract_id':range(1000)}).set_index(['subregion','tract_id'])


df_small_area_scale.head()
                    grp1  grp2  grp3  grp4
subregion tract_id                        
B         0          119    85    11    19
D         1          136   100    46   239
A         2           76    26   198   109
B         3          230   180    84   222
A         4          108   101   222   244

并且,通过 subregion 进行汇总,我们得到:

df_small_area_scale.groupby(level=0).sum()
            grp1   grp2   grp3   grp4
subregion                            
A          27241  27050  27471  26215
B          26507  24696  23315  24857
C          27474  28871  28882  28743
D          26671  26163  25077  27612
E          22739  23077  23797  24473

(让我们得到每个组中每个次区域的目标份额)

summary_area_scale_shares = summary_area_scale.stack().groupby(level=0).apply(lambda x: x/float(x.sum()))
summary_area_scale_shares.head()

subregion      
A          grp1    0.244444
           grp2    0.266667
           grp3    0.244444
           grp4    0.244444
B          grp1    0.255319
dtype: float64

其次,小区域数据应该加起来,在次区域层面

这些是次区域 "known" 分布。我希望将区域级数据调整到这些,以便在聚合区域时,它们大致匹配每个组中的这些区域总数。具体来说,subregion A 中的 grp4 总计为 26,215,但根据目标,应该是 22,000,因此次区域 A 的区域应该看到从 grp4 给其他一些团体。

summary_area_scale = pd.DataFrame(data={'grp1':[22000,24000,21000,25000,28000],
                                        'grp2':[24000,22000,26000,20000,28000],
                                        'grp3':[22000,24000,21000,25000,28000],
                                        'grp4':[22000,24000,21000,25000,28000],
                                        'subregion':list('ABCDE')}).set_index('subregion')
summary_area_scale
            grp1   grp2   grp3   grp4
subregion                            
A          22000  24000  22000  22000
B          24000  22000  24000  24000
C          21000  26000  21000  21000
D          25000  20000  25000  25000
E          28000  28000  28000  28000

一个想法是在每个次区域内抽样,然后按照需要从一个垃圾箱转移到另一个垃圾箱的总人数的一定比例转移人员,尽管我不确定是否有聪明的做法它符合上述标准。

导致我出现问题的主要是确定了一种跨组重新分配人员以匹配次区域总数的方法,同时保持记录级别的总数,而不是完全丢弃我想保留的先前存在的空间分布作为信号(但已调整为现在已知的不同总体分布)。

一般而言,关于如何使细节分布更符合总体分布的任何想法,而不仅仅是抽样和从 grp4 -> grp3grp2 -> grp1 移动 x 人以及无论有什么区别介于现有分布和目标分布之间?

占位符代码

此函数主要是在 table 中查找每个组中的区域份额,将该分布推送到每个区域,因此它除了设置数据绑定外什么都不做。

def some_redistribution_algorithm(df):
    """
    how many persons need to be moved across groups in each subregion?
    minimal solution is to just take those shifts and apply uniformly
    tracts keep the same counts, but the *distribution* across bins will change slightly
    Quality criteria for algorithm:
    - switch population at tract level such that 
    - tract-level population counts maintained
    - Pre- and post-adjustment spatial distribution be largely unchanged
    - change is not disproportional / dramatically impacting some tracts over others 
      (i.e. a tract with 10 grp4 population losing 8 would lose 80%, while a tract with 100 q4 hhs would lose 8%)

    """

    adjustments = summary_area_scale.xs(df.name)

    size = (adjustments).apply(lambda x: abs(x)).loc['grp4'].astype(np.int64)/df.shape[0]
    print "Processing %s (%s tracts), beg. pop: %s, avg pop to move (here q4) %s" %(df.name,df.shape[0],
                                                                                   df.sum().loc['grp4'].astype(np.int64),size)
    print 'Average pop per tract:'
    print df.sum()/df.shape[0]


    ## tract-level distribution, if all tracts had the same distribution within each subregion (placeholder)

    return df_small_area_scale.xs(df.name).mul(summary_area_scale_shares.unstack().xs(df.name),axis=1)

    #samplerows= np.random.choice(a=df.index, size=size)
    #df.loc[samplerows,:] = df.loc[samplerows,:]#, p=df.totalshare.tolist()),:]
df_small_area_scale.groupby(level=0).apply(some_redistribution_algorithm)

如果我对你的问题理解正确,我认为迭代比例拟合可能就是你要找的。如果可以的话,我会陈述我最近遇到的类似问题。这是我试图解决的问题:

我知道大都市级别的年龄分布,我知道每个区域的总人数,但由于人口普查的工作方式,我想我知道每个区域的年龄分布,但我不确定。

我知道我想满足区域内的总人口(行边缘),我知道我想满足大都市级别的年龄分布(列边缘),我想 "seed" ipf每个区域的分布是我对答案的最佳猜测。当然它不起作用(我的意思是数字不会加起来),所以你立即偏离那个猜测以满足边缘。这就是迭代比例拟合的目的。

也许不是防弹的,但我使用的代码(在 Python / numpy 中)是这样的:

# this should be fairly self explanitory if you know ipf
# seed_matrix is your best bet at the totals, col_marginals are
# observed column marginals and row_marginals is the same for rows

def simple_ipf(seed_matrix, col_marginals, row_marginals, tolerance=1, cnt=0):
    assert np.absolute(row_marginals.sum() - col_marginals.sum()) < 5.0

    # first normalize on columns
    ratios = col_marginals / seed_matrix.sum(axis=0)
    seed_matrix *= ratios
    closeness = np.absolute(row_marginals - seed_matrix.sum(axis=1)).sum()
    assert np.absolute(col_marginals - seed_matrix.sum(axis=0)).sum() < .01
    # print "row closeness", closeness
    if closeness < tolerance:
        return seed_matrix

    # first normalize on rows
    ratios = row_marginals / seed_matrix.sum(axis=1)
    ratios[row_marginals == 0] = 0
    seed_matrix = seed_matrix * ratios.reshape((ratios.size, 1))
    assert np.absolute(row_marginals - seed_matrix.sum(axis=1)).sum() < .01
    closeness = np.absolute(col_marginals - seed_matrix.sum(axis=0)).sum()
    # print "col closeness", closeness
    if closeness < tolerance:
        return seed_matrix

    if cnt >= 50:
        return seed_matrix

    return simple_ipf(seed_matrix, col_marginals, row_marginals,
                      tolerance, cnt+1)