如何在 IPython Notebook 中缓存?

How to cache in IPython Notebook?

环境:

每次关闭 IPython 笔记本并重新打开它时,我都必须重新 运行 所有单元格。但有些细胞涉及密集计算。

相比之下,knitr 在 R 中默认将结果保存在缓存目录中,因此只有新代码和新设置才会调用计算。

我查看了 ipycache,但它似乎缓存了一个单元格而不是笔记本。 knitr 在 IPython 中是否有对应的缓存?

你能举例说明你正在尝试做什么吗?当我在 IPython 笔记本中 运行 一些昂贵的东西时,我几乎总是在事后将它写入磁盘。例如,如果我的数据是 JSON 对象的列表,我将它以行分隔 JSON 格式化字符串的形式写入磁盘:

with open('path_to_file.json', 'a') as file:
    for item in data: 
        line = json.dumps(item)
        file.write(line + '\n')

然后您可以用同样的方式读回数据:

data = []
with open('path_to_file.json', 'a') as file:
    for line in file: 
        data_item = json.loads(line)
        data.append(data_item)

我认为一般来说这是一个很好的做法,因为它为您提供了备份。您也可以使用泡菜做同样的事情。如果您的数据真的很大,您实际上可以 gzip.open 直接写入 zip 文件。

编辑

要将 scikit 学习模型保存到磁盘,请使用 joblib.pickle

from sklearn.cluster import KMeans

km = KMeans(n_clusters=num_clusters)
km.fit(some_data)


from sklearn.externals import joblib
# dump to pickle
joblib.dump(km, 'model.pkl')

# and reload from pickle
km = joblib.load('model.pkl')

不幸的是,似乎没有像自动缓存这样方便的东西。 %store 魔术选项已关闭,但需要您手动明确地进行缓存和重新加载。

在您的 Jupyter 笔记本中:

a = 1
%store a

现在,假设您关闭笔记本并重新启动内核。您不再有权访问局部变量。但是,您 可以 重新加载您使用 -r 选项存储的变量。

%store -r a
print a # Should print 1

事实上你要求的功能已经存在,不需要通过转储手动重新实现它。

您可以使用 %store 或更好的 %%cache 魔法(扩展)来存储这些间歇性单元格的结果,因此不必重新计算它们(参见 https://github.com/rossant/ipycache

就这么简单:

%load_ext ipycache

然后,在单元格中,例如:

%%cache mycache.pkl var1 var2
var1 = 1
var2 = 2

When you execute this cell the first time, the code is executed, and the variables var1 and var2 are saved in mycache.pkl in the current directory along with the outputs. Rich display outputs are only saved if you use the development version of IPython. When you execute this cell again, the code is skipped, the variables are loaded from the file and injected into the namespace, and the outputs are restored in the notebook.

它会保存所有图形、生成的输出以及自动为您指定的所有变量:)

使用 cache magic.

%cache myVar = someSlowCalculation(some, "parameters")

This will calculate someSlowCalculation(some, "parameters") once. And in subsequent calls it restores myVar from storage.

https://pypi.org/project/ipython-cache/

在幕后,它与公认的答案几乎相同。