python - 使用 pd.DataFrame 以高斯分布重新分配数据
问题描述
我有一个 pandas DataFrame,其中包含属于每个类(列)的每个样本的概率。碰巧的是,几乎 99% 的类都有< 0.01
概率,而很少有> 0.5
概率。出于某种原因,我希望概率分布在 和 之间的高斯分布0
中1
。我想平均值应该0.5
在这种情况下,但如果可能的话,我也希望能够修改这种分布的平均值。我希望对每一行分别进行此操作,如何使用 pandas 数据框来执行此操作?
解决方案
如果你想重现一个更像高斯的分布,你正在谈论单点的加权(连续的班级分数)。
所以我建议使用高斯分布权重来放大分数。
这里有一个例子:
import numpy as np
import pandas as pd
#Preparation of the data
nclasses = 10
nsamples = 5
df_c = []
for nc in range( nsamples ):
a = np.random.rand(nclasses)
a = [n/np.sum(a) for n in a]
df_c.append( a )
df = pd.DataFrame(df_c)
# Now let's weight
for nr in range( df[0].count() ): #iterate over rows
a = df.iloc[nr] #capture the nth row
#generate Gaussian weights
gw = np.random.normal( np.mean(a), np.std(a), len(a) )
#sort gw and a in order to assign one to the other
gw = np.sort(gw)
b_ind = np.argsort(a) #indexes to sort a
b = a[b_ind] #sorted version of a
# now weight the row
aw_r = a*b # you can reduce the entity adding anotherfactor, like 0.8 for instance
# back from sort
aw = [ aw_r[n] for n in b_ind ]
#update the dataframe
df.iloc[nr] = aw
# there you go!
希望它会有所帮助
更新__
如果要将每行的平均值调整为相同的值,例如 0.5,则只需减去行平均值和目标平均值之间的差值(在本例中为 0.5)。
a=np.array([1,2,3,47,2,6])
print( a.mean() ) # 10.1666
target_mean = 0.5
a_adj = a-(np.mean(a) - target_mean)
print( np.mean( a_adj ) ) # 0.5
这意味着在上面的主要示例中,在将 aw 替换为 df.iloc[nr] 之前,您应该这样做
aw = aw-(np.mean(aw) - 0.5)
推荐阅读
- python - 我的位加法器的总和只在某些时候工作
- python - 检查值是否在区间内
- haskell - 如何根据列表的后半部分简洁匹配列表,并相应地绑定它的前半部分?
- javascript - 通过单击按钮更改部分
- docker - Traefik 中间件不适用于 docker compose
- scala - 具有 spark 依赖项的 Scalatra 应用程序返回 java.lang.NoSuchFieldError: INSTANCE 由于多个 httpclient 版本
- javascript - 在Javascript中获取像素RGB
- python - 在特征重要性和特征选择之后重建和训练新的深度学习 Python 模型以减少特征量?
- arduino - STM32 bluepill 板中使用的引导加载程序是什么?
- amazon-web-services - Grails Amazon Web Services Plugin route53 Error On Using Route53 ChangeResourceRecordSets