IPython notebook 交互函数:如何保存更新的函数参数 [英] IPython notebook interactive function: how to save the updated function parameters

查看:35
本文介绍了IPython notebook 交互函数:如何保存更新的函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wrote the code below in Ipython notebook to generate a sigmoid function controlled by parameters a which defines the position of the sigmoid center, and b which defines its width:

%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 添加交互性,所以我重写了如下函数:

I wanted to add interactivity for parameters a and b so I re-wrote the function as below:

%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)

是否可以将修改后的 sigmoid 函数参数 a 和 b 在被滑块修改时动态保存到变量中,以便它们可以在另一个子图或单独的图中使用,并进行进一步的计算.?

Is it possible to save the modified sigmoid function parameters a and b to variables dynamically as they are modified by the sliders, so they can be used in another subplot or separate plot, and do further calculations.?

我浏览了所有我能找到的交互式小部件示例,但没有看到任何指向该方向的东西(这些小部件相当新,因此它们的文档似乎不像其他功能那样广泛).对正确方向的任何建议表示赞赏.

I've gone through all examples of interactive widgets I could find but have not see anything pointing in that direction (these widgets are fairly new, so documentation for them does not seem as extensive as for other features). Any suggestions in the right direction is appreciated.

推荐答案

您要手动创建浮动小部件:

You want to create the float widget manually:

from IPython.html.widgets import FloatSlider

# same as before

F1 = FloatSlider(value=5, min=0, max=10)
w=interactive(sigmoid_demo, a=F1, b=7)
display(w)

然后你可以随时访问F1.value,它将是当前滑块的值.

Then you can access F1.value any time after and it will be the current slider value.

你也可以遍历 w.widgets 但这很痛苦.

You can also loop through w.widgets but that's painful.

这篇关于IPython notebook 交互函数:如何保存更新的函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆