7

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

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)

Is there any way to se the range of the sliders to be symmetrical (for example around zero)? It does not seem to me to be possible by just setting the starting value for the parameters.

MyCarta
  • 808
  • 2
  • 12
  • 37

1 Answers1

7

You can create widgets manually and bind them to variables in the interactive function. This way you are much more flexible and can tailor those widgets to your needs.

This example creates two different sliders and sets their max, min, stepsize and initial value and uses them in the interactive function.

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)
cel
  • 30,017
  • 18
  • 97
  • 117
  • Thanks. I should probably make that second part a separate question so I could chose yours as answer for the range. – MyCarta Dec 15 '14 at 18:17
  • What I am lookign for is a way to write back the values of parameters a and b dynamically as they are modifeid by the sliders. Definitely a separate question now that i think of it. – MyCarta Dec 15 '14 at 19:44
  • Here's the second part of the original question as a separate question. http://stackoverflow.com/questions/27492056/ipython-notebook-interactive-function-how-to-save-the-updated-function-paramete – MyCarta Dec 15 '14 at 19:57