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

Python 如何以编程方式设置交互参数?,python,jupyter-notebook,ipython-notebook,interactive,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(weight

假设我有一个接受参数列表的函数。列表可以是可变长度的,函数可以使用它。例如:

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])
显示

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

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

但是,我如何通过编程来定义滑块的数量呢

我试过了

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
plotsupplication
中,表示interact不会将值列表传递给函数


如何完成?

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

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
前面的星号。然后,使用键/值参数字典调用
交互

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

interact(PlotSuperposition, **kwargs)