python - 对矩阵 python 进行二次采样

标签 python random

例如,我有一个列出对的文本文件

10,1
2,7
3,1
10,1

然后将其转换为对称矩阵,因此 (1,10) 条目是 (1,10) 对出现在列表中的次数。我现在想对这个矩阵进行二次采样。我所说的子样本是指 - 我想制作一个矩阵,该矩阵是仅使用原始文本文件中随机 30% 的行的结果。因此,在本例中,如果我删除了文本文件的 70%,则 (1,10) 对可能只显示一次而不是两次,因此矩阵中的 (1,10) 条目将为 1 而不是 2。

如果我确实有原始文本文件,只需使用 random.sample 挑选出文件中 30% 的行,就可以轻松完成此操作。但如果我只有矩阵,我怎样才能随机抽取 70% 的数据呢?

最佳答案

我想最好的方法取决于你的数据在哪里:

  • 您是否有一个巨大的矩阵,其中大部分都是小计数?或
  • 您是否有一个中等大小的矩阵,其中包含大量计数?

这是一个适合第二种情况的解决方案,尽管它也可以工作 第一种情况没问题。

基本上,计数恰好位于二维矩阵中的事实并非如此 重要的是:这基本上是从具有以下特征的总体中进行抽样的问题: 已被扔进垃圾桶。所以我们能做的就是直接提取垃圾箱,而忘记 矩阵一点:

import numpy as np
import random

# Input counts matrix
mat = np.array([
    [5, 5, 2],
    [1, 1, 3],
    [6, 0, 4]
], dtype=np.int64)

# Build a list of (row,col) pairs, and a list of counts
keys, counts = zip(*[
    ((i,j), mat[i,j])
        for i in range(mat.shape[0])
        for j in range(mat.shape[1])
        if mat[i,j] > 0
])

然后使用累积计数数组从这些容器中进行采样:

# Make the cumulative counts array
counts = np.array(counts, dtype=np.int64)
sum_counts = np.cumsum(counts)

# Decide how many counts to include in the sample
frac_select = 0.30
count_select = int(sum_counts[-1] * frac_select)

# Choose unique counts
ind_select = sorted(random.sample(xrange(sum_counts[-1]), count_select))

# A vector to hold the new counts
out_counts = np.zeros(counts.shape, dtype=np.int64)

# Perform basically the merge step of merge-sort, finding where
# the counts land in the cumulative array
i = 0
j = 0
while i<len(sum_counts) and j<len(ind_select):
    if ind_select[j] < sum_counts[i]:
        j += 1
        out_counts[i] += 1
    else:
        i += 1

# Rebuild the matrix using the `keys` list from before
out_mat = np.zeros(mat.shape, dtype=np.int64)
for i in range(len(out_counts)):
    out_mat[keys[i]] = out_counts[i]

现在您将在 out_mat 中获得采样矩阵。

关于python - 对矩阵 python 进行二次采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11818215/

相关文章:

python - 在Python中计算总和的最有效方法

使用随机数 rand() 计数

perl - List::Util 'shuffle' 实际上是如何工作的?

python - 按正确的顺序将字典写入 csv 文件

python - 尝试从 python 脚本执行 golang 程序时出错

python - 有哪些进行机器间锁定的好方法?

python - 如何让 selenium 在 scraperwiki 上工作

c# - 这些随机数是 'safe'

php - 生成可预测的随机数组

java - 数组中 int 元素的随机整数