我生成一个 npz 文件如下:
import numpy as np
import os
# Generate npz file
dataset_text_filepath = 'test_np_load.npz'
texts = []
for text_number in range(30000):
texts.append(np.random.random_integers(0, 20000,
size = np.random.random_integers(0, 100)))
texts = np.array(texts)
np.savez(dataset_text_filepath, texts=texts)
Run Code Online (Sandbox Code Playgroud)
这给了我这个 ~7MiB npz 文件(基本上只有 1 个变量texts,它是一个 Numpy 数组的 NumPy 数组):
我加载了numpy.load():
# Load data
dataset = np.load(dataset_text_filepath)
Run Code Online (Sandbox Code Playgroud)
如果我按如下方式查询,则需要几分钟:
# Querying data: the slow way
for i in range(20):
print('Run {0}'.format(i))
random_indices = np.random.randint(0, len(dataset['texts']), size=10)
dataset['texts'][random_indices]
Run Code Online (Sandbox Code Playgroud)
而如果我查询如下,它需要不到 5 秒:
# Querying data: …Run Code Online (Sandbox Code Playgroud)