0

我在理解numpy.memmap工作方式时遇到问题。背景是我需要numpy通过删除条目来减少磁盘上保存的大型数组。读取数组并通过复制所需的部分来建立一个新的部分是行不通的——它只是不适合内存。所以这个想法是使用numpy.memmap- 即在光盘上工作。她是我的代码(带有一个小文件):

import numpy

in_file = './in.npy'
in_len = 10
out_file = './out.npy'
out_len = 5

# Set up input dummy-file
dummy_in = numpy.zeros(shape=(in_len,1),dtype=numpy.dtype('uint32'))
for i in range(in_len):
    dummy_in[i] = i + i
numpy.save(in_file, dummy_in)

# get dtype and shape from the in_file
in_npy = numpy.load(in_file)

in_dtype = in_npy.dtype
in_shape = (in_npy.shape[0],1)
del(in_npy)

# generate an 'empty' out_file with the desired dtype and shape
out_shape = (out_len,1)
out_npy = numpy.zeros(shape=out_shape, dtype=in_dtype)
numpy.save(out_file, out_npy)
del(out_npy)

# memmap both files
in_memmap = numpy.memmap( in_file,  mode='r',  shape=in_shape, dtype=in_dtype)
out_memmap = numpy.memmap(out_file, mode='r+', shape=out_shape, dtype=in_dtype)
print "in_memmap"
print in_memmap, "\n"
print "out_memmap before in_memmap copy"
print out_memmap, "\n"

# copy some parts
for i in range(out_len):
    out_memmap[i] = in_memmap[i]

print "out_memmap after in_memmap copy"
print out_memmap, "\n"
out_memmap.flush()

# test
in_data = numpy.load(in_file)
print "in.npy"
print in_data
print in_data.dtype, "\n"

out_data = numpy.load(out_file)
print "out.npy"
print out_data
print out_data.dtype, "\n"

运行此代码,我得到:

in_memmap
[[1297436307]
 [     88400]
 [ 662372422]
 [1668506980]
 [ 540682098]
 [ 880098343]
 [ 656419879]
 [1953656678]
 [1601069426]
 [1701081711]]

out_memmap before in_memmap copy
[[1297436307]
 [     88400]
 [ 662372422]
 [1668506980]
 [ 540682098]]

out_memmap after in_memmap copy
[[1297436307]
 [     88400]
 [ 662372422]
 [1668506980]
 [ 540682098]]

in.npy
[[ 0]
 [ 2]
 [ 4]
 [ 6]
 [ 8]
 [10]
 [12]
 [14]
 [16]
 [18]]
uint32

out.npy
[[0]
 [0]
 [0]
 [0]
 [0]]
uint32

形成输出很明显我做错了什么:

1) memmaps 不包含数组中设置的值,in_memmap并且out_memmap包含相同的值。

2)不清楚复制命令是否将任何内容复制in_memmapout_memmap(由于相同的值)。在调试模式下检查in_memmap[i]out_memmap[i]我得到的值:memmap([1297436307], dtype=uint32)。那么我可以像在代码中那样分配它们还是必须使用:out_memmap[i][0] = in_memmap[i][0]

3)out.npy不会被操作更新为out_memmapflush()

谁能帮我理解我在这里做错了什么。

非常感谢

4

1 回答 1

0

np.memmap替换withnp.lib.format.open_memmap和 get的每个实例:

in_memmap 
[[ 0]
 [ 2]
 [ 4]
 [ 6]
 [ 8]
 [10]
 [12]
 [14]
 [16]
 [18]] 

out_memmap before in_memmap copy 
[[0]
 [0]
 [0]
 [0]
 [0]] 

out_memmap after in_memmap copy 
[[0]
 [2]
 [4]
 [6]
 [8]] 

in.npy 
[[ 0]
 [ 2]
 [ 4]
 [ 6]
 [ 8]
 [10]
 [12]
 [14]
 [16]
 [18]] 
 uint32 

out.npy 
[[0]
 [2]
 [4]
 [6]
 [8]] 
 uint32 

np.save添加一个np.memmap正在读取的标题,这就是为什么两者中的数据看起来相同(因为它是相同的标题)。这也是为什么当您将数据从一个复制到另一个时它没有效果(因为它只是复制标题,而不是数据)np.lib.format.open_memmap会自动跳过标题,以便您可以处理数据。

于 2017-08-08T13:02:29.097 回答