如何以编程方式设置交互参数?

时间:2017-11-03 18:44:24

标签: python jupyter-notebook ipython-notebook interactive

假设我有函数,它接受参数列表。列表可以是可变长度,功能正常。例如:

import math
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
%matplotlib inline  

def PlotSuperposition(weights):
    def f(x):
        y = 0
        for i, weight in enumerate(weights):
            if i==0:
                y+=weight
            else:
                y += weight*math.sin(x*i)
        return y
    vf = np.vectorize(f)
    xx = np.arange(0,6,0.1)
    plt.plot(xx, vf(xx))
    plt.gca().set_ylim(-5,5)

PlotSuperposition([1,1,2])

显示

enter image description here

我可以对给定数量的参数进行硬编码交互,例如

interact(lambda w0, w1, w2: PlotSuperposition([w0,w1,w2]), w0=(-3,+3,0.1), w1=(-3,+3,0.1), w2=(-3,+3,0.1))

显示

enter image description here

但是如何以编程方式定义多个滑块呢?

我试过

n_weights=10
weight_sliders = [widgets.FloatSlider(
        value=0,
        min=-10.0,
        max=10.0,
        step=0.1,
        description='w%d' % i,
        disabled=False,
        continuous_update=False,
        orientation='horizontal',
        readout=True,
        readout_format='.1f',
    ) for i in range(n_weights)]
interact(PlotSuperposition, weights=weight_sliders)

但收到错误

 TypeError: 'FloatSlider' object is not iterable

PlotSuperposition内,表示交互不会将值列表传递给函数。

如何完成?

1 个答案:

答案 0 :(得分:2)

首先,修改你的函数以获取任意数量的关键字参数而不是普通列表:

def PlotSuperposition(**kwargs):
    def f(x):
        y = 0
        for i, weight in enumerate(kwargs.values()):
            if i==0:
                y+=weight
            else:
                y += weight*math.sin(x*i)
        return y
    vf = np.vectorize(f)
    xx = np.arange(0,6,0.1)
    plt.plot(xx, vf(xx))
    plt.gca().set_ylim(-5,5)

注意kwargs前面的星号。然后,使用键/值参数字典调用interact

kwargs = {'w{}'.format(i):slider for i, slider in enumerate(weight_sliders)}

interact(PlotSuperposition, **kwargs)

enter image description here