【问题标题】:IPython notebook interactive function: how to set the slider rangeIPython notebook交互功能:如何设置滑块范围
【发布时间】:2014-12-15 17:34:19
【问题描述】:

我在 Ipython notebook 中编写了以下代码来生成一个 sigmoid 函数,该函数由参数 a 控制,该参数定义 sigmoid 中心的位置,b 定义其宽度:

%matplotlib inline
    import numpy as np
    import matplotlib.pyplot as plt

def sigmoid(x,a,b):
    #sigmoid function with parameters a = center; b = width
    s= 1/(1+np.exp(-(x-a)/b))
    return 100.0*(s-min(s))/(max(s)-min(s)) # normalize sigmoid to 0-100

x = np.linspace(0,10,256)
sigm = sigmoid(x, a=5, b=1)
fig = plt.figure(figsize=(24,6))
ax1 = fig.add_subplot(2, 1, 1)
ax1.set_xticks([])
ax1.set_xticks([])
plt.plot(x,sigm,lw=2,color='black')
plt.xlim(x.min(), x.max())

我想为参数 a 和 b 添加交互性,所以我重写了如下函数:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from IPython.html.widgets import interactive
from IPython.display import display

def sigmoid_demo(a=5,b=1):
    x = np.linspace(0,10,256)
    s = 1/(1+np.exp(-(x-a)/(b+0.1))) # +0.1 to avoid dividing by 0
    sn = 100.0*(s-min(s))/(max(s)-min(s)) # normalize sigmoid to 0-100
    fig = plt.figure(figsize=(24,6))
    ax1 = fig.add_subplot(2, 1, 1)
    ax1.set_xticks([])
    ax1.set_yticks([])
    plt.plot(x,sn,lw=2,color='black')
    plt.xlim(x.min(), x.max())

w=widgets.interactive(sigmoid_demo,a=5,b=1)
display(w)

有没有办法将滑块的范围设置为对称(例如大约为零)?在我看来,仅通过设置参数的起始值是不可能的。

【问题讨论】:

    标签: python widget slider ipython-notebook interactive


    【解决方案1】:

    您可以手动创建小部件并将它们绑定到interactive 函数中的变量。这样您就更加灵活,并且可以根据您的需要定制这些小部件。

    此示例创建两个不同的滑块并设置它们的最大值、最小值、步长和初始值,并在 interactive 函数中使用它们。

    a_slider = widgets.IntSliderWidget(min=-5, max=5, step=1, value=0)
    b_slider = widgets.FloatSliderWidget(min=-5, max=5, step=0.3, value=0)
    w=widgets.interactive(sigmoid_demo,a=a_slider,b=b_slider)
    display(w)
    

    【讨论】:

    • 谢谢。我可能应该把第二部分作为一个单独的问题,这样我就可以选择你的作为范围的答案。
    • 我正在寻找的是一种在滑块修改参数 a 和 b 时动态写回参数值的方法。现在我想到它绝对是一个单独的问题。
    • 这是原始问题的第二部分,作为一个单独的问题。 stackoverflow.com/questions/27492056/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多