python输出数组中随机的2个元素_如何通过随机选择2×2子数组中的元素来对2D数组进行下采样?...

博客介绍了在Python中从数组里随机采样元素的方法。将整个ndarray采样为4个单独的ndarray,这些子数组相同索引指向同一2×2正方形,再从这4个ndarray中随机采样,通过np.random.randint和choose函数实现随机选择,得到最终结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这可以通过采样完成.而不是对每个2×2正方形进行采样,我们将整个ndarray采样为4个单独的ndarray,这些子数组中的相同索引将指向同一2×2正方形.然后,我们从这4个单独的ndarray中随机采样:

# create test dataset

test = np.arange(36).reshape(6,6)

array([[ 0, 1, 2, 3, 4, 5],

[ 6, 7, 8, 9, 10, 11],

[12, 13, 14, 15, 16, 17],

[18, 19, 20, 21, 22, 23],

[24, 25, 26, 27, 28, 29],

[30, 31, 32, 33, 34, 35]])

# Create subsamples from ndarray

samples = np.array([test[::2, ::2], test[1::2, 1::2], test[::2, 1::2], test[1::2, ::2]])

>>> samples

array([[[ 0, 2, 4],

[12, 14, 16],

[24, 26, 28]],

[[ 7, 9, 11],

[19, 21, 23],

[31, 33, 35]],

[[ 1, 3, 5],

[13, 15, 17],

[25, 27, 29]],

[[ 6, 8, 10],

[18, 20, 22],

[30, 32, 34]]])

现在,这4个子样本中每个样本的相同索引指向原始ndarray上相同的2×2平方.我们只需要从相同的索引中随机选择:

# Random choice sampling between these 4 subsamples.

select = np.random.randint(4,size=(3,3))

>>> select

array([[2, 2, 1],

[3, 1, 1],

[3, 0, 0]])

result = select.choose(samples)

>>> result

array([[ 1, 3, 11],

[18, 21, 23],

[30, 26, 28]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值