gpt4 book ai didi

python - 三维数据集

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:06 25 4
gpt4 key购买 nike

我正在将数据写入三维数据集,我注意到一个非常令人不安的问题。我想将 20 个 2000x2000 的矩阵写入数据集。我注意到写入 2000x2000x20 的数据集比写入 20x2000x2000 的数据集慢得离谱。有谁知道为什么?

慢 - 时间:66.4123821259

import h5py
import numpy as np

file1 = h5py.File('/home/serra/Documents/Software/Store_testdata/TestDataset.h5')
a = file1.create_group('run')
b = a.create_dataset('seq_1',(2000,2000,20))

for i in range(20):
b[:,:,i] = np.random.rand(2000,2000)

file1.close()

快 - 时间:3.72713208199

import h5py
import numpy as np

file1 = h5py.File('/home/serra/Documents/Software/Store_testdata/TestDataset.h5')
a = file1.create_group('run')
b = a.create_dataset('seq_1',(20,2000,2000))

for i in range(20):
b[i,:,:] = np.random.rand(2000,2000)

file1.close()

最佳答案

性能差异与矩阵的大小无关,但与填充数据的顺序有关:

b[i,:,:] = np.random.rand(2000,2000)
b[:,:,i] = np.random.rand(2000,2000)

在第一种情况下,您正在填充内存中连续的单元格。在第二种情况下,细胞分散在内存中。

当项目在连续内存中时,所有相邻单元格可能会在第一个单元格被获取时被缓存。在另一种情况下,当一个被获取时,它的大部分将保存在缓存中的相邻单元将不会被使用。

为了便于说明,让我们考虑二维情况,并假设两个项目适合缓存。以下矩阵:

numpy.array('[[10, 20, 30], [40, 50, 60]]')

在内存中是这样存储的:

10 20 30 40 50 60

让我们看看按行顺序迭代它时会发生什么:

a[0][0] → fetch 10 from memory (cached: 10 20)
a[0][1] → read 20 from cache
a[0][2] → fetch 30 from memory (cached: 30 40)
a[1][0] → read 40 from cache
a[1][1] → fetch 50 from memory (cached: 50 60)
a[1][2] → read 60 from cache

现在,让我们按列顺序迭代:

a[0][0] → fetch 10 from memory (cached: 10 20)
a[1][0] → fetch 40 from memory (cached: 30 40)
a[2][1] → fetch 20 from memory (cached: 10 20)
a[0][1] → fetch 50 from memory (cached: 50 60)
a[1][2] → fetch 30 from memory (cached: 30 40)
a[1][2] → fetch 60 from memory (cached: 50 60)

因此,在第一种情况下,您可以仅使用三个内存访问来遍历整个矩阵,而在第二种情况下,您需要六次。根据经验,从内存中读取值比从缓存中读取值慢约 200 倍。

关于python - 三维数据集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com