使用不同的输入参数循环/运行ipython笔记本的部分内容 [英] Run parts of a ipython notebook in a loop / with different input parameter

查看:97
本文介绍了使用不同的输入参数循环/运行ipython笔记本的部分内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个分析数据集的ipython笔记本。现在我想使用此代码循环遍历不同的数据集。

I have written a ipython notebook, which analyses a dataset. Now I want to use this code to loop over different datasets.

代码分为大约50个单元格(包括注释,降价解释,......)。有没有办法在循环中运行部分笔记本或运行具有不同输入参数的整个笔记本?

The code is split into about 50 cells (including comments, markdown explanations,...). Is there a way to run parts of a notebook in a loop or running a whole notebook with different input parameters?

我不想将所有单元格合并为一个函数或者将代码下载为python脚本,因为我真的想通过仅执行某些单元来运行(并试验)部分分析。

I don't want to merge all cells into one function or download the code as a python script, as I really like to run (and experimenting with) parts of the analysis by executing only certain cells.

基本上它将一部分脚本重构成一个函数并在一个循环中调用该函数,只是脚本部分是笔记本单元格。

Basically its refactoring parts of a script into a function and calling the function in a loop, just that the "parts of the script" are notebook cells.

推荐答案

在这些场景中我通常做的是将重要单元格包装为函数(您不必合并它们中的任何一个)并且有一个主单元格迭代参数列表并调用这些函数。例如。这就是我的一个笔记本中的主单元格:

What I usually do in these scenarios is wrap the important cells as functions (you don't have to merge any of them) and have a certain master cell that iterates over a list of parameters and calls these functions. E.g. this is what a "master cell" looks like in one of my notebooks:

import itertools
# parameters
P_peak_all = [100, 200]
idle_ratio_all = [0., 0.3, 0.6]
# iterate through these parameters and call the notebook's logic
for P_peak, idle_ratio in itertools.product(P_peak_all, idle_ratio_all):
    print(P_peak, idle_ratio, P_peak*idle_ratio)
    print('========================')
    m_synth, m_synth_ns = build_synth_measurement(P_peak, idle_ratio)
    compare_measurements(m_synth, m_synth_ns, "Peak pauser", "No scheduler", file_note="-%d-%d" % (P_peak, int(idle_ratio*100)))

您仍然可以获得一些数据拖动整个笔记本(即用您的数据调用单元格底部的每个函数),以便能够为单个单元格测试实时内容。例如,某些单元格可能会声明:

You can still have some data dragging throughout the notebook (i.e. calling each function at the bottom of the cell with your data) to be able to test stuff live for individual cells. For example some cell might state:

def square(x):
    y = x**2
    return y
square(x) # where x is your data running from the prior cells 

这让你可以实时试验并仍然从主单元格中调用通用功能。

Which lets you experiment live and still call the generic functionality from the master cell.

我知道使用函数重构笔记本是一些额外的工作,但我发现它实际上增加了笔记本的可读性,这在你经过较长时间后回到它上面很有用,并且如果需要的话,更容易将它转换为适当的脚本或模块。

I know it's some additional work to refactor your notebook using functions, but I found it actually increases my notebook's readability which is useful when you come back to it after a longer period and it's easier to convert it to a "proper" script or module if necessary.

这篇关于使用不同的输入参数循环/运行ipython笔记本的部分内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆