Dim*_*ims 4 python interactive ipython-notebook jupyter-notebook
假设我有函数,它接受参数列表。列表可以是可变长度的,功能也可以。例如:
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])
Run Code Online (Sandbox Code Playgroud)
显示
我可以对给定数量的参数进行硬编码交互,就像这里
interact(lambda w0, w1, w2: PlotSuperposition([w0,w1,w2]), w0=(-3,+3,0.1), w1=(-3,+3,0.1), w2=(-3,+3,0.1))
Run Code Online (Sandbox Code Playgroud)
这表现了
但是如何以编程方式定义滑块的数量?
我试过
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)
Run Code Online (Sandbox Code Playgroud)
但有错误
TypeError: 'FloatSlider' object is not iterable
Run Code Online (Sandbox Code Playgroud)
里面PlotSuperposition说交互不会将值列表传递给函数。
如何实现?
首先,修改您的函数以采用任意数量的关键字参数而不是普通列表:
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)
Run Code Online (Sandbox Code Playgroud)
注意前面的星号kwargs。然后,interact使用键/值参数字典调用:
kwargs = {'w{}'.format(i):slider for i, slider in enumerate(weight_sliders)}
interact(PlotSuperposition, **kwargs)
Run Code Online (Sandbox Code Playgroud)