Numpy提取子矩阵

8 篇文章 0 订阅
1 篇文章 0 订阅

结论

代码运行环境:ipython、jupyter、jupyterlab
想要从numpy的矩阵或者ndarray中提取子矩阵还是使用有序的坐标序列np.ix_函数最快。另外想不到ndarray速度比matrix要快一些, 实验不是很严谨,实验次数不够, 水平有限,多多斧正。

import numpy as np
import time
import random

# ndarray
mtx = np.random.random((3000, 1500))
# 矩阵
M = np.matrixlib.matrix(mtx)

print(u"有序坐标")
a_lis = random.sample(range(3000), 400)
order_a = sorted(a_lis)
b_lis = random.sample(range(1500), 200)
order_b = sorted(b_lis)

indices = np.ix_(order_a, order_b)

time.sleep(2)
%timeit c = mtx[indices]
time.sleep(2)
%timeit c = M[indices]
time.sleep(2)
%timeit c = mtx[:, order_b][order_a, :]
time.sleep(2)
%timeit c = mtx[order_a, :][:, order_b]
time.sleep(2)

print(u"无序坐标")
unordered_a = a_lis
unordered_b = b_lis
indices = np.ix_(unordered_a, unordered_b)

time.sleep(2)
%timeit c = mtx[indices]
time.sleep(2)
%timeit c = M[indices]
time.sleep(2)
%timeit c = mtx[:, unordered_b][unordered_a, :]
time.sleep(2)
%timeit c = mtx[unordered_a, :][:, unordered_b]
有序坐标
The slowest run took 6.45 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 559 µs per loop
The slowest run took 493.40 times longer than the fastest. This could mean that an intermediate result is being cached.
10 loops, best of 3: 749 µs per loop
10 loops, best of 3: 12.6 ms per loop
1000 loops, best of 3: 1.07 ms per loop
无序坐标
1000 loops, best of 3: 757 µs per loop
The slowest run took 6.65 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.32 ms per loop
100 loops, best of 3: 13.9 ms per loop
100 loops, best of 3: 1.35 ms per loop
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值