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

4
假设我有一个函数,可以接受参数列表。列表长度可以变化,而函数可以处理。例如:
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个回答

5
首先,修改您的函数以接受任意数量的关键字参数而不是纯列表:
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接