def quiz_tfidf():
    # lesson 1, quiz 4
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()

    with description:
        display(
            widgets.HTMLMath(
                value=r"Consider the collection $D$ containing 3 documents"))
        display(
            widgets.HTMLMath(
                value=
                r'''1. $d_1$ = "If you tell the truth you don't have to remember anything."'''
            ))
        display(
            widgets.HTMLMath(
                value=
                r'''2. $d_2$ = "If you don't read the newspaper, you're uninformed. If you read the newspaper, you're misinformed."'''
            ))
        display(
            widgets.HTMLMath(
                value=
                r'''3. $d_3$ = "A lie can travel half way around the world while the truth is putting on its shoes."'''
            ))
        display(
            widgets.HTMLMath(
                value=r'''Compute $$TFIDF(\mathrm{''If''}, d_1, D)$$'''))
    return Quiz(description, ["2.2", "0.81", "0.405", "1.5"], "0.405")
def quiz_bumps():
    # lesson 6, quiz 1
    from IPython.display import display
    import ipywidgets as widgets
    import matplotlib.pyplot as plt

    description = widgets.Output()
    with description:
        w = widgets.HTMLMath(value=r"Consider the following function $f(x)$:")
        display(w)

    with description:
        _x = [-1, 0, 0, 1, 1, 2]
        _y = [2, 2, 3, 3, 4, 4]
        plt.figure(figsize=(8, 4))
        plt.plot(_x, _y)
        plt.show()

    with description:
        display(widgets.HTMLMath(r"Which formula for $f(x)$ is correct?"))
        display(
            widgets.HTMLMath(r"""
            <ol>
                <li>$f(x) = \Pi_{-1, 0, 2}(x) + \Pi_{0, 1, 1}(x) + \Pi_{1, 2, 1}(x)$</li>
                <li>$f(x) = \Pi_{-1, 0, 2}(x) + \Pi_{0, 1, 3}(x) + \Pi_{1, 2, 4}(x)$</li>
                <li>$f(x) = \Pi_{-1, 0, 0}(x) + \Pi_{0, 1, 1}(x) + \Pi_{1, 2, 2}(x)$</li>
            </ol>
        """))
        display(widgets.HTML("Choose the correct answer below"))

    return Quiz(description, [1, 2, 3], 2)
def quiz_estimate_clustering_quality():
    # lecture 3, quiz 2
    import ipywidgets as widgets
    from IPython.display import display
    from tabulate import tabulate

    description = widgets.Output()
    with description:
        display(
            widgets.HTMLMath(value=r"""
            Suppose you have 4 points with the following true labels and clusters:
        """))
        table = [
            ("$x_1$", "1", "2"),
            ("$x_2$", "1", "2"),
            ("$x_3$", "2", "1"),
            ("$x_4$", "1", "1"),
        ]
        display(
            widgets.HTMLMath(value=tabulate(
                table, headers=("point", "label",
                                "cluster"), tablefmt="html")))
        display(
            widgets.HTML(
                "What is the clustering quality according to the definition above?"
            ))

    return Quiz(description, ["0", "0.25", "0.5", "0.75"], "0.5")
def quiz_derivative():
    # lesson 6, quiz 2
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()
    with description:
        w = widgets.HTMLMath(
            value=
            r"Consider the function $$\tilde h(x)=\sum\limits_{1 \leq k \leq K} w_k g(a_k x + b_k) + s_k$$"
        )
        display(w)

    with description:
        display(
            widgets.HTMLMath(
                r"What is the derivative $\dfrac{\partial \ell(y, \tilde h(x))}{\partial s_k}$?"
            ))
        display(
            widgets.HTMLMath(r"""
            <ol>
                <li>$\dfrac{\partial \ell(y, \tilde h(x))}{\partial s_k} = (y - \tilde h(x)) \cdot g(a_k x + b_k)$</li>
                <li>$\dfrac{\partial \ell(y, \tilde h(x))}{\partial s_k} = w_k \cdot (y - \tilde h(x))$</li>
                <li>$\dfrac{\partial \ell(y, \tilde h(x))}{\partial s_k} = y - \tilde h(x)$</li>
            </ol>
        """))
        display(widgets.HTML("Choose the correct answer below"))

    return Quiz(description, [1, 2, 3], 3)
Example #5
0
def progress_bar():
  
    t1 = widgets.HTMLMath(value='Calculating . . .')
    t2 = widgets.HTMLMath(value='{:,.3g}%'.format(0))
    s = ' - ETA: {}  -  {}: {:,.3g}'
    t3 = widgets.HTMLMath(value=s.format(np.nan,'metric',0))
    w = widgets.VBox([t1, widgets.HBox([t2,t3])])
    display(w)
    return t1, t2, t3
Example #6
0
 def on_submit(event):
     answer = form.value.strip()
     if not case_sensitive:
         answer = answer.lower()
     accept = False
     lowest_distance = edit_distance + 1
     bestMatch = None
     for i, a in enumerate(answers):
         if case_sensitive:
             d = edit_dist_bnd(answer, a, lowest_distance)
         else:
             d = edit_dist_bnd(answer, a.lower(), lowest_distance)
         if d < lowest_distance:
             accept = True
             bestMatch = i
             lowest_distance = d
     feedback_str = None
     if isinstance(feedback, str):
         chosen_feedback = feedback
     if accept:
         if isinstance(feedback, list):
             feedback_str = feedback[bestMatch]
         elif isinstance(feedback, dict):
             feedback_str = feedback.get(answers[bestMatch], None)
     else:
         if isinstance(feedback, dict):
             lowest_distance = edit_distance + 1
             for (k, v) in feedback.items():
                 if case_sensitive:
                     d = edit_dist_bnd(answer, k, lowest_distance)
                 else:
                     d = edit_dist_bnd(answer, k.lower(),
                                       lowest_distance)
                 if d < lowest_distance:
                     feedback_str = v
                     lowest_distance = d
     if feedback_str is None:
         feedback_str = ''
     else:
         feedback_str = '<p>' + feedback_str
     if accept:
         label = widgets.HTMLMath('Correct!{}'.format(feedback_str))
         label.add_class('correct')
         remove = container.children[-1]
         container.children = container.children[:-1] + (label, )
         remove.close()
     else:
         label = widgets.HTMLMath(
             'Incorrect.{}<p>Please try again.'.format(feedback_str))
         label.add_class('incorrect')
         remove = container.children[-1]
         container.children = container.children[:-1] + (label, )
         remove.close()
def quiz_coherence():
    # lecture 3, quiz 4
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()
    with description:
        display(
            widgets.HTMLMath(value=r"""
            Consider three words $A$, $B$, $C$ that occur with probabilities
            $$
            \Pr(A) = \frac{1}{2}, \Pr(B) = \frac{1}{4}, \Pr(C) = \frac{1}{2}
            $$
            and co-occur with probabilities
            $$
            \Pr(A, B) = \frac{1}{4}, \Pr(B, C) = \frac{1}{16}, \Pr(A, C) = \frac{1}{4}
            $$
            Choose the pair of words with the highest value of $PMI$.
        """))

    return Quiz(description, [
        "A and B",
        "B and C",
        "A and C",
    ], "A and B")
def quiz_perplexity():
    # lesson 2 quiz 5
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()

    with description:
        display(
            widgets.HTMLMath(value=r"""
            Consider a unigram language model with the following probabilities:
            <ul>
                <li>$\Pr(\textrm{"A"})$ = 0.5</li>
                <li>$\Pr(\textrm{"B"})$ = 0.1</li>
                <li>$\Pr(\textrm{"C"})$ = 0.25</li>
            </ul>
            Compute $\textrm{Perplexity}(\textrm{"AABCC"})$
        """))

    return Quiz(description, [
        "3.64",
        "0.27",
        "640",
        "0.0016",
    ], "3.64")
def lattice_type():
    # first create all the individual widgets, and initialize them with default values.
    # The initialization part is important, and the initialization of all widgets must be consistent.

    type_choice = widgets.ToggleButtons(
        # options are (label, value) pairs
        value='ordinary',
        options=[('Ordinary', 'ordinary'), ('Polynomial', 'polynomial')],
        description='Choose one:',
        style=style_default)
    type_info = widgets.HTMLMath(value=type_data[type_choice.value])

    # then wrap the widgets inside containers: the containters are nested, because this allows for a compact
    # visualization for the user. For information about containers and their layout, see:
    # https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Styling.html#The-Flexbox-layout
    # The outmost container is always an Accordion.
    lattice_type = widgets.Accordion([widgets.VBox([type_choice, type_info])])
    lattice_type.set_title(0, 'Lattice Type')

    # Instanciate and return the BaseGUIElement which encapsulates all the widgets created above.
    # Add each widget as an attribute of the Element.
    # We almost always use the same name for the widget (local name in the function) and the attribute (global name that will be accessible everywhere)
    # To register callbacks, use the _callbacks dictionary where the key is the widget launching the callback and
    # the value is the callback function itself.
    # See the BaseGUIElement class for more information.
    return BaseGUIElement(type_info=type_info,
                          main=lattice_type,
                          type_choice=type_choice,
                          _callbacks={'type_choice': change_lattice_type})
def quiz_bigram_lm():
    # lesson 2 quiz 3
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()

    with description:
        display(
            widgets.HTMLMath(value=r"""
            Consider a bigram language model with the following probabilities:
            <ul>
                <li>$\Pr(\textrm{"am so"})$ = 0.0007</li>
                <li>$\Pr(\textrm{"am very"})$ = 0.0009</li>
                <li>$\Pr(\textrm{"am the"})$ = 0.0009</li>
                <li>$\Pr(\textrm{"I am"})$ = 0.019</li>
                <li>$\Pr(\textrm{"I"})$ = 0.16</li>
                <li>$\Pr(\textrm{"am"})$ = 0.02</li>
                <li>$\Pr(\textrm{"so"})$ = 0.04</li>
            </ul>
            Find $\Pr(\textrm{"I am so"})$
        """))

    return Quiz(description, [
        "0.00076",
        "0.000665",
        "0.0003325",
    ], "0.000665")
Example #11
0
def create_elem_weights(type_weights, dimension_int, gui):
    weights_set_all_id = gui.weights.weights_set_all_id
    if type_weights == 'Product':
        value = ['0.8'] * dimension_int
    elif type_weights == 'Order-Dependent':
        value = [
            str(round(0.8**(k + 1) * (k <= 2), 3))
            for k in range(dimension_int)
        ]
    form = widgets.HBox([
        widgets.Text(value=value[k],
                     description='',
                     layout=widgets.Layout(width='50px'))
        for k in range(dimension_int)
    ])
    set_all = widgets.Text(
        value='',
        placeholder=placeholder_set_all[type_weights],
        description='OR set all at once with (valid Python) expression: %s =' %
        (math_strings[type_weights]),
        disabled=False,
        layout=widgets.Layout(margin='0px 0px 0px 80px', width='550px'),
        style=style_default)
    weights = widgets.VBox([
        widgets.HBox([
            widgets.HTMLMath(title_strings[type_weights],
                             layout=widgets.Layout(width='170px')), form
        ]), set_all
    ])
    set_all.observe(
        lambda change: set_all_weights(change, 1, gui, type_weights))
    weights_set_all_id[set_all] = weights
    return weights
Example #12
0
 def on_correct(value):
     feedback_str = ''
     #label = widgets.HTML('<div style"{}">Correct!{}</div>'.format(correct_style,feedback_str))
     label = widgets.HTMLMath('Correct!{}'.format(feedback_str))
     label.add_class('correct')
     remove = container.children[-1]
     container.children = container.children[:-1] + (label, )
     remove.close()
Example #13
0
 def on_correct(value):
     feedback_str = '' if feedback is None or feedback[
         value_to_index[value]] is None else '<p>{}'.format(
             feedback[value_to_index[value]])
     label = widgets.HTMLMath('Correct!{}'.format(feedback_str))
     label.add_class('correct')
     remove = container.children[-1]
     container.children = container.children[:-1] + (label, )
     remove.close()
Example #14
0
 def buildui(self) -> None:
     # self._link = \
     #   wd.link((self._slider, 'value'), (self._floatBox, 'value'))
     self._ui = wd.HBox([
         wd.HTMLMath(value=self._mathRep),
         #      self._floatBox,
         self._slider,
         wd.Label(value="[" + self._units + "]")
     ])
def quiz_vector_distance():
    # lesson 1, quiz 5
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()

    with description:
        display(
            widgets.HTMLMath(value=r"Consider the following set of vectors"))
        display(widgets.HTMLMath(value=r"$$\mathbb{a} = (0.5, 0.5)$$"))
        display(widgets.HTMLMath(value=r"$$\mathbb{b} = (0.4, 0.8)$$"))
        display(widgets.HTMLMath(value=r"$$\mathbb{c} = (0, 0.5)$$"))

        display(
            widgets.HTMLMath(
                value=r"Which one is the closest to $\mathbb{w} = (1, 0)$?"))

    return Quiz(description, ["a", "b", "c"], "a")
def quiz_kmeans():
    # lecture 3, quiz 1
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()
    with description:
        display(
            widgets.HTMLMath(value=r"""
            Suppose you run $k$-means algorithm on 4 points:
            <ul>
                <li>$x_1 = (3, 1)$</li>
                <li>$x_2 = (4, 2)$</li>
                <li>$x_3 = (3, 3)$</li>
                <li>$x_4 = (6, 2)$</li>
            </ul>
            with initial cluster centers
            <ul>
                <li>$c_1 = (0, 2)$</li>
                <li>$c_2 = (7, 2)$</li>
            </ul>
        """))
        display(
            widgets.HTMLMath(
                value=
                r"Compute clusters and new coordinates of $c_1$ and $c_2$ after one full iteration, i.e. after one E-step and one M-step."
            ))
        display(
            widgets.HTMLMath(value=r"""
            Options:
            <ol>
                <li>cluster 1: $x_1$ and $x_3$; cluster 2: $x_2$ and $x_4$; $c_1 = (0, 2)$; $c_2 = (7, 2)$</li>
                <li>cluster 1: $x_1$ and $x_3$; cluster 2: $x_2$ and $x_4$; $c_1 = (3, 2)$; $c_2 = (5, 2)$</li>
                <li>cluster 1: $x_1$ and $x_2$; cluster 2: $x_3$ and $x_4$; $c_1 = (0, 2)$; $c_2 = (7, 2)$</li>
                <li>cluster 1: $x_1$ and $x_2$; cluster 2: $x_3$ and $x_4$; $c_1 = (3, 2)$; $c_2 = (5, 2)$</li>
            </ol>
        """))
        display(widgets.HTML("Choose the correct answer below."))
        display(widgets.HTML("<b>Hint</b>: draw a picture."))

    return Quiz(description, ["option 1", "option 2", "option 3", "option 4"],
                "option 2")
def display_markdown(path, placeholder='', style_file="style.css"):
    with open(path) as file:
        html = markdown.markdown(file.read())
    with open(style_file) as file:
        style = file.read()
    html = '\n'.join([style, html])
    display(
        widgets.HTMLMath(
            value=html,
            placeholder=placeholder,
            description='',
        ))
Example #18
0
    def __init__(self):
        self.dt = 0.01; 

        ### Dropdown + display A matrix
        self.A_matrices = dict()
        self.A_matrices['A1'] = np.mat([[.9, 0.], [0., 0.9]])
        self.A_matrices['A2'] = np.mat([[1.1, 0.], [0., 1.1]])
        self.A_matrices['A3'] = np.mat([[.9, -.1], [.1, 0.9]])
        self.A_matrices['A4'] = np.mat([[1.05, -.2], [.2, 1.05]])
        self.A_matrices['A5'] = np.mat([[.9, 0.], [0., -1.1]])

        ### Class for holding onto data 
        self.X0_data = PlotData()

        ### Make the dropdown window ####
        self.A_dropdown = widgets.Dropdown(options=['None', 'A1', 'A2', 'A3', 'A4', 'A5'], 
                                      value='None', description='A Matrix: ', disabled=False,
                                      layout={'width': 'initial'}, style={'description_width': 'initial'})
        self.A_dropdown.observe(self.linkA)

        ### Make the A display; 
        self.A_display = widgets.HTMLMath()

        ### Get the childern: 
        self.children1 = [self.A_dropdown, self.A_display]

         ### Plot + Clear button 
        self.out1 = widgets.Output()
        with self.out1:
            fig1, axes1 = plt.subplots(figsize=(5, 5))
            self.format_ax1(axes1)
            plt.show(fig1)
        self.fig = fig1 
        self.axes = axes1

        ### Clear button; 
        self.button=widgets.Button(description='Clear')
        self.button.on_click(self.clear_ax)
        self.children2 = [self.out1, self.button]

        #### Init conditions + time slider 
        self.num_ts = widgets.interactive(self.plot_x0_prop, {'manual': True}, 
                                     num_timepoints=widgets.IntSlider(min=1, max=20, step=1),
                                     style={'description_width': 'initial'})
        self.num_x0 = widgets.interactive(self.plot_x0, {'manual': True}, 
                                     initial_x0=widgets.IntSlider(min=1, max=10, step=1),
                                    style={'description_width': 'initial'});
            
        self.children3 = [self.num_x0, self.num_ts]
Example #19
0
    def __init__(self, statement, choices):

        # get number of choices
        self.num_choices = len(choices)
        self.choices = choices

        # Shuffle answers
        self.indices = [i for i in range(self.num_choices)]
        random.shuffle(self.indices)
        self.correct = self.indices.index(0)

        # Define CSS properties to make text larger
        display(HTML("<style>.large_font { font-size: 100% }</style>"))
        display(HTML("<style>.xlarge_font { font-size: 120% }</style>"))

        # store the statement in a widget
        self.statement = w.HTMLMath(value=statement)

        # enlarge text
        self.statement.add_class("xlarge_font")

        # Create labels for each answer choice
        answers = [
            w.Label(value=self.choices[self.indices[i]])
            for i in range(self.num_choices)
        ]

        # Enlarge text for labels
        for a in answers:
            a.add_class("large_font")

        # Create radio buttons with answers as labels (slots)
        self.choice_buttons = v.RadioGroup(v_model=None,
                                           children=[
                                               v.Radio(v_slots=[{
                                                   'name': 'label',
                                                   'children': [a]
                                               }]) for a in answers
                                           ])

        # Create a submit button
        self.check_button = v.Btn(color='primary', children=['Check Answer'])

        # If button is clicked, check the currently selected answer
        self.check_button.on_event("click", self.on_click_submit)

        # Create a feedback area
        self.feedback = w.Output()
Example #20
0
def process_data(X):

    X = read_data(X)

    alpha95 = np.empty(X['N'])
    for i in range(X['N']):
        alpha95[i] = MADtoA95(X['mad'][i], X['n'][i], X['anchor'][i])

    rho = A3(A95toKR(alpha95))

    MU = []
    for i in range(X['N']):
        temp = dir2cart((X['dec'][i], X['inc'][i]))
        MU.append(np.squeeze(temp))
    A = np.sum(rho[:, np.newaxis] * MU, axis=0)
    A0 = np.sum(MU, axis=0)

    R = np.linalg.norm(A)
    R0 = np.linalg.norm(A0)

    MU = A / R
    MU0 = A0 / R0

    X['mu*'] = cart2dir(MU)[0:2]
    X['a95*'] = (a95(R, X['N']))

    X['mu'] = cart2dir(MU0)[0:2]
    X['a95'] = (a95(R0, X['N']))

    # Print results
    spacer = ipyw.HTML(value='<font color="white">Spacer text</font>')
    title_main = ipyw.HTML(value='<h3>Results</h3>')
    hr = ipyw.HTML(
        value=
        '<hr style="height:2px;border:none;color:#333;background-color:#333;" />'
    )
    title_star = ipyw.HTML(value='<h4>Incorperating uncertainty</h4>')
    inc_star = ipyw.HTMLMath(
        value='Inc$^*$ [deg.] = {0:.2f}'.format(X['mu*'][1]))
    dec_star = ipyw.HTMLMath(
        value='Dec$^*$ [deg.] = {0:.2f}'.format(X['mu*'][0]))
    a95_star = ipyw.HTMLMath(
        value=r'$\alpha 95^*$ [deg.] = {0:.2f}'.format(X['a95*']))
    title_null = ipyw.HTML(value='<h4>Without uncertainty</h4>')
    inc_null = ipyw.HTMLMath(value='Inc [deg.] = {0:.2f}'.format(X['mu'][1]))
    dec_null = ipyw.HTMLMath(value='Dec [deg.] = {0:.2f}'.format(X['mu'][0]))
    a95_null = ipyw.HTMLMath(
        value=r'$\alpha 95$ [deg.] = {0:.2f}'.format(X['a95']))
    results_star = ipyw.VBox((title_star, inc_star, dec_star, a95_star))
    results_null = ipyw.VBox((title_null, inc_null, dec_null, a95_null))
    results_comb = ipyw.HBox((results_star, spacer, results_null))
    results = ipyw.VBox((hr, title_main, results_comb, hr))
    display(results)

    return X
Example #21
0
def fractal(fn, imgx=800, imgy=800, xa=-1, xb=1, ya=-1, yb=1):
    image = Image.new("RGBA", (imgx, imgy))
    f = eval('lambda z: ' + fn)
    Z = []
    maxd = 0.005
    for y in range(imgy):
        zy = y * (yb - ya) / (imgy - 1) + ya
        for x in range(imgx):
            zx = x * (xb - xa) / (imgx - 1) + xa
            z = complex(zx, zy)
            for i in range(maxit):
                dz = (f(z + complex(h, h)) - f(z)) / complex(h, h)
                z0 = z - f(z) / dz
                if abs(z0 - z) < eps:
                    break
                z = z0
            #Se obtuvo una raiz o se superó el número de iteraciones
            if i < (maxit - 1):
                dist = distPC(Z, z)
                if dist[0] < maxd:
                    item = dist[1]
                else:
                    Z.append(z)
                    item = len(Z) - 1
                r = ((item + 7) % len(Z) * 32) % 225
                g = ((item + 5) % len(Z) * 57) % 225
                b = ((item) % len(Z) * 26) % 225
                a = 64 + int(i * 192 / maxit)
            else:
                #El punto non converge a ninguna raíz, se pone el pixel en Blanco.
                r = 255
                g = 255
                b = 255
                a = 255

            image.putpixel((x, y), (r, g, b, a))

    wf = widgets.HTMLMath(
        value="$f(z)={}$ <p> Raices:{}".format( \
               spp.latex(parse_expr(fn)),Z),
        placeholder='',
        description='',
        layout=Layout(width='100%'),
    )
    display(wf)

    return image
Example #22
0
 def on_incorrect(value):
     feedback_strs = []
     if feedback is not None:
         for i in len(value):
             if value[i] != value_in_answer[i]:
                 if feedback[i] is not None:
                     feedback_strs.append(feedback[i])
     if feedback_strs:
         feedback_str = '<p>{}'.format('<p>'.join(feedback_strs))
     else:
         feedback_str = ''
     label = widgets.HTMLMath(
         'Incorrect.{}<p>Please try again.'.format(feedback_str))
     label.add_class('incorrect')
     remove = container.children[-1]
     container.children = container.children[:-1] + (label, )
     remove.close()
Example #23
0
    def _update(self):
        desc = self._desc
        if self.units_str != '':
            desc += "\nValues must be in units of %s." % self.units_str

        if self._min is not None:
            desc += "\nMin: %s\tMax: %s\n" % (self._min, self._max)

        popup = '<div data-toggle="popover" title="%s" data-container="body">%s</div>' % (
            desc, self.name)
        if self.label is None:
            self.label = widgets.HTML(value=popup,
                                      layout=widgets.Layout(flex='2 1 auto'))
            self.unit_label = widgets.HTMLMath(value=self.units_tex,
                                               layout={'min_width': '6ch'})
            return
        self.label.value = popup
        self.unit_label.value = self.units_tex
def interactive_progress_graph(timespan, progress_data_func):
    
    # Para renderizar LaTeX
    # ce.typeset()
    
    # Se obtienen los datos originales
    x_data = timespan
    y_data = progress_data_func(x_data, 22.7, 0)
    
    def update(a):
        
        plt.figure(dpi=150)
        plt.title("Variación de la concentración de producto por unidad de tiempo")
        plt.xlabel("Tiempo (min)")
        plt.ylabel("Producto (uM)")
        
        # Update temp parameters
        MicMent_progress = np.add(np.multiply(x_data, a), 0)

        plt.scatter(x_data, y_data, c="r", label="a: {}".format(500), s=8.0)
        plt.scatter(x_data, MicMent_progress, c="b", label="a modificada: {}".format(a), s=8.0)
        plt.plot(x_data, y_data, c="r", lw=2.0, alpha=0.5)
        plt.plot(x_data, MicMent_progress, c="b", lw=2.0, alpha=0.5)
        plt.legend(bbox_to_anchor=(1.05, 0.5), loc='center left')
        
    a_slider = widgets.FloatSlider(value=22.7, min=0, max=100.0, step=0.5, continuous_update=True, description="a", layout=widgets.Layout(width='auto', height='auto'), style={'description_width': 'initial'})

    output_graph = widgets.interactive_output(update, {'a':a_slider})
    header = widgets.HTML(value="<H1><center>Gráfico Interactivo Curva Progreso - Enzimas</center></H1>", layout=widgets.Layout(width='auto', grid_area='header'))
    footer = widgets.HTML(value="<H1><center>A continuación se realizarán algunas actividades relacionadas con las curvas de progreso y su utilidad en la cinética enzimática</center></H1>", layout=widgets.Layout(width='auto', grid_area='header'))
    equation = widgets.HTMLMath(value="", layout=widgets.Layout(width='auto', grid_area='header'))
    sliders = widgets.VBox([a_slider])

    final_output = widgets.AppLayout(header=header,
            left_sidebar=sliders,
            center=output_graph,
            footer=footer,
            right_sidebar=None,
            align_items='center',
            pane_widths=[3, 3, 1],
            pane_heights=[1, 5, '60px'])
    
    return final_output
def quiz_count_ngrams():
    # lesson 2 quiz 4
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()

    with description:
        display(
            widgets.HTMLMath(value=r"""
            Given the vocabulary $V$, what is the number of all possible $n$-grams constructed from $V$?
            Assume there is no padding.
        """))

    return Quiz(description, [
        r"$|V|$",
        r"$n + |V|$",
        r"$n\cdot|V|$",
        r"$|V|^n$",
    ], r"$|V|^n$")
Example #26
0
def construction_method():
    construction_choice = widgets.ToggleButtons(value='sobol',
                                                options=[('Sobol', 'sobol'),
                                                         ('Polynomial',
                                                          'polynomial'),
                                                         ('Explicit',
                                                          'explicit')],
                                                description='Choose one:',
                                                style=style_default)

    constr_info = widgets.HTMLMath(
        value=constr_data[construction_choice.value])
    construction = widgets.Accordion(
        [widgets.VBox([construction_choice, constr_info])],
        layout=widgets.Layout(display="none"))
    construction.set_title(0, 'Construction Method')
    return BaseGUIElement(
        constr_info=constr_info,
        construction_choice=construction_choice,
        main=construction,
        _callbacks={'construction_choice': change_constr_choice})
def quiz_random_benchmark():
    # lesson 2 quiz 6
    import ipywidgets as widgets
    from IPython.display import display

    description = widgets.Output()

    with description:
        display(
            widgets.HTMLMath(value=r"""
            Suppose that we compute accuracy on the dataset with 4 classes, and there is equal number of samples of each class.
            (In other words, all classes are balanced.)
            What is accuracy of "random" classifier, that predicts random category with probability 0.25?
        """))

    return Quiz(description, [
        "0",
        "0.0625",
        "0.25",
        "0.5",
    ], "0.25")
Example #28
0
 def create_results(self):
     
     for box in self.output_box.children:
         box.clear_output()
     
     # Create output.
     bar_cols = ['size', 'qty', 'x', 'y', 'strain', 'stress', 'F' ]
     bar_data = {}
     for b in self.model.long_reinf:
         bar_data[b.name] = [b.size, b.qty, b.x, b.y, b.strain, b.stress, b.F]
     bars_df = pd.DataFrame.from_dict(bar_data, orient='index', columns=bar_cols)
     
     with self.output_box.children[1]:
         display(wg.HTMLMath("<h3> Bars </h3>"))
         display(bars_df)
         
         print('c =', self.model.c, 'in')
         print('a =', self.model.a, 'in')
         print('beta1 =', self.model.material.beta1)
         print('phi =', self.model.phi)
         print('Mn =', self.model.Mnx, 'lb*in')
         print('phi*Mn =', self.model.phi_Mnx, 'lb*in')
         print('phi*Mn =', self.model.phi_Mnx/12/1000, 'k*ft')
def quiz_correct_computational_graph():
    # lecture 6, quiz 3
    import ipywidgets as widgets
    from IPython.display import display
    description = widgets.Output()
    with description:
        display(
            widgets.HTMLMath(value=r"""
        Choose the correct computational graph for $F(\alpha, \beta) = f\left(\dfrac{\alpha}{\beta}\right)$
        """))
    with description:
        display(
            widgets.HTML("""
            <b>Option 1</b>
            <br>
            <img src="https://raw.githubusercontent.com/horoshenkih/harbour-space-text-mining-course/master/pic/backprop-1.png">
            <br>

            <b>Option 2</b>
            <br>
            <img src="https://raw.githubusercontent.com/horoshenkih/harbour-space-text-mining-course/master/pic/backprop-2.png">
            <br>

            <b>Option 3</b>
            <br>
            <img src="https://raw.githubusercontent.com/horoshenkih/harbour-space-text-mining-course/master/pic/backprop-3.png">
            <br>

            <b>Option 4</b>
            <br>
            <img src="https://raw.githubusercontent.com/horoshenkih/harbour-space-text-mining-course/master/pic/backprop-4.png">
            <br>
            """))

    return Quiz(description, ["Option 1", "Option 2", "Option 3", "Option 4"],
                "Option 4")
def quiz_derivative_pytorch():
    from IPython.display import display

    def solution(x):
        import torch
        x = torch.tensor(x, requires_grad=True)
        z = torch.pow(x, x)
        z.backward()
        return x.grad.item()

    import ipywidgets as widgets
    description = widgets.Output()

    with description:
        w = widgets.HTMLMath(
            r"Compute the derivative of $f(x) = x^x$ with PyTorch. Hint: use torch.pow function.<hr>"
        )
        display(w)

    return Function(description,
                    etalon_solution=solution,
                    input_list=[[float(x)] for x in range(1, 20, 2)],
                    input_output_list=[],
                    show_n_answers=2)