Exemple #1
0
def interactive_logistic_regression(X,
                                    y,
                                    target_names=None,
                                    feature_names=None,
                                    stacked: bool = False):
    from panel import widgets
    import panel as pn

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y,
                                                        stratify=y,
                                                        random_state=42)
    embedding = umap.UMAP(n_components=2, random_state=160290).fit_transform(
        np.concatenate([X_train, X_test]))

    def interactive_model(C, penalty, fit_intercept, intercept_scaling,
                          l1_ratio, class_weight):
        model = LogisticRegression(
            C=C,
            penalty=penalty,
            solver="saga",
            fit_intercept=fit_intercept,
            intercept_scaling=intercept_scaling,
            l1_ratio=l1_ratio,
            class_weight=class_weight,
            random_state=42,
        ).fit(X, y)
        return plot_model_evaluation(
            model,
            X_train,
            y_train,
            X_test,
            y_test,
            target_names=target_names,
            feature_names=feature_names,
            stacked=stacked,
            embedding=embedding,
        )

    c_slider = widgets.LiteralInput(value=1, name="C")
    penalty_tog = widgets.RadioButtonGroup(
        name="penalty", options=["none", "l1", "l2", "elasticnet"])
    fit_intercept = widgets.Toggle(name="fit_intercept")
    intercept_scaling = widgets.LiteralInput(value=1, name="intercept_scaling")
    l1_ratio = widgets.FloatSlider(end=1.0,
                                   start=0.0,
                                   value=0.5,
                                   name="l1_ratio")
    class_weight = widgets.LiteralInput(value=None, name="class_weight")
    return pn.interact(
        interactive_model,
        C=c_slider,
        penalty=penalty_tog,
        fit_intercept=fit_intercept,
        intercept_scaling=intercept_scaling,
        l1_ratio=l1_ratio,
        class_weight=class_weight,
    )
Exemple #2
0
def map_dash():
    """Map dashboard"""
    # Create the map
    map_pane = pn.pane.plot.Folium(sizing_mode="scale_both", min_width=800)

    # Initialize map at Joshua Tree in July
    unit = 'JOTR'
    month = 7
    coords = get_coords(unit, parks)
    bnds = get_bounds(unit, boundaries)
    traffic = get_traffic(unit, traffic_data)
    visitors = get_visitors(unit, month, publicUse)
    map_pane.object = makeMap(unit, month, coords, bnds, visitors, traffic)

    # Create the dropdown menus for month and visitors
    month_buttons = pnw.RadioButtonGroup(name='Month',
                                         options=list(month_dict.keys()),
                                         button_type='primary',
                                         value='July')
    traffic_checkbox = pnw.Checkbox(name='Display traffic counters',
                                    value=True)
    park_select = pnw.Select(name='Where do you want to go?',
                             options=list(park_dict.keys()),
                             value='Joshua Tree NP')

    # Trigger map updates
    def update_map(event):
        month = month_dict[month_buttons.value]
        unit = park_dict[park_select.value]
        coords = get_coords(unit, parks)
        bnds = get_bounds(unit, boundaries)
        traffic = get_traffic(unit, traffic_data)
        visitors = get_visitors(unit, month, publicUse)
        map_pane.object = makeMap(unit,
                                  month,
                                  coords,
                                  bnds,
                                  visitors,
                                  traffic,
                                  useTraffic=traffic_checkbox.value)
        return

    # Updates
    month_buttons.param.watch(update_map, 'value')
    month_buttons.param.trigger('value')
    park_select.param.watch(update_map, 'value')
    park_select.param.trigger('value')
    traffic_checkbox.param.watch(update_map, 'value')
    traffic_checkbox.param.trigger('value')

    # Fully return the map
    app = pn.Column(month_buttons,
                    traffic_checkbox,
                    park_select,
                    map_pane,
                    width_policy='fit')
    return app


#pn.extension()

#app = map_dash()
#app.servable()
#server = app.show(threaded=True)
Exemple #3
0
    """
    Return only the rows of df which belong to the requested event.
    """
    return df[df['event'] == e]


def get_ax():
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    return fig, ax


# declare variable widgets
athlete_name = pnw.Select(name='Athlete',
                          options=list(individual_events['Name'].unique()))
event_distance = pnw.RadioButtonGroup(name='Event', value=ALL_EVENTS_NAME)
start_position = pnw.RadioButtonGroup(name='Start Position')
position_gain_loss = pnw.RadioButtonGroup(name='Position Gain/Loss')
athlete_races = pnw.DataFrame()
athlete_races_single_event = pnw.DataFrame()
athlete_laptimes = pnw.DataFrame()
athlete_laptimes_single_event = pnw.DataFrame()


def athlete_name_changed(event):
    """
    Triggering event is athlete_name.value
    """
    athlete_races.value = individual_events[individual_events['Name'] ==
                                            event.new]
    athlete_laptimes.value = laptimes[laptimes['Name'] == event.new]
Exemple #4
0
import pandas as pd
import panel as pn
import panel.widgets as pnw
from matplotlib.backends.backend_agg import FigureCanvas
from matplotlib.figure import Figure

DATA_URL = (
    "https://raw.githubusercontent.com/LuisM78/Occupancy-detection-data/master/datatraining.txt"
)

data = pd.read_csv(DATA_URL)
data["date"] = data.date.astype("datetime64[ns]")
data = data.set_index("date")

variable = pnw.RadioButtonGroup(name="variable",
                                value="Temperature",
                                options=list(data.columns))
window = pnw.IntSlider(name="window", value=10, start=1, end=60)


def mpl_plot(avg, highlight):
    fig = Figure()
    FigureCanvas(fig)  # not needed in mpl >= 3.1
    ax = fig.add_subplot()
    avg.plot(ax=ax)
    if len(highlight):
        highlight.plot(style="o", ax=ax)
    return fig


def find_outliers(variable="Temperature",
pn.extension("plotly")

files = os.listdir('data')
AAFMG = []
for f in files:
    data = pd.read_csv('data/' + f)
    data['Symbol'] = f.replace('.csv', '')
    AAFMG.append(data)
AAFMG = pd.concat(AAFMG)
AAFMG['Date'] = pd.to_datetime(AAFMG['Date'])

# Create Widget Components
symbol = pnw.Select(name='symbol',
                    options=['AAPL', 'AMZN', 'FB', 'GOOGL', 'MSFT'])
value = pnw.RadioButtonGroup(
    name='value',
    options=['Open', 'High', 'Low', 'Close', 'Adj Close', 'Volume'])
window = pnw.IntSlider(name='window', start=7, end=365, value=30)
date_range = pnw.DateRangeSlider(name='date range',
                                 start=datetime.datetime(1980, 12, 12),
                                 end=datetime.datetime(2020, 4, 1),
                                 value=(datetime.datetime(2017, 4, 1),
                                        datetime.datetime(2020, 4, 1)))


# Define Reactive Plot Function
@pn.depends(symbol, value, window, date_range)
def reactive_plot(symbol, value, window, date_range):
    df = AAFMG.loc[AAFMG['Symbol'] == symbol]
    df = df.sort_values('Date')
    df['MA'] = df[value].rolling(window=window).mean()
Exemple #6
0
                  window=30,
                  sigma=10,
                  view_fn=mpl_plot):
    avg = data[variable].rolling(window=window).mean()
    residual = data[variable] - avg
    std = residual.rolling(window=window).std()
    outliers = (np.abs(residual) > std * sigma)
    return view_fn(avg, avg[outliers])


pn.extension()
pn.interact(find_outliers)

text = "<br>\n# Room Occupancy\nSelect the variable, and the time window for smoothing"

kw = dict(window=(1, 60), variable=sorted(list(data.columns)), sigma=(1, 20))
i = pn.interact(find_outliers, **kw)

p = pn.Row(i[1][0], pn.Column(text, i[0][0], i[0][1]))

variable = pnw.RadioButtonGroup(name='variable',
                                value='Temperature',
                                options=list(data.columns))
window = pnw.IntSlider(name='window', value=10, start=1, end=60)

reactive_outliers = pn.bind(find_outliers, variable, window, 10)

widgets = pn.Column("<br>\n# Room occupancy", variable, window)
occupancy = pn.Row(reactive_outliers, widgets)
occupancy.servable()
Exemple #7
0
    def _update_widgets_panel(self):
        self._default_component[self.component_type] = self.component

        component = None
        controls = None
        if self.component is pn.pane.HoloViews:
            component = pn.pane.HoloViews(_create_hvplot())
        if self.component is pn.pane.ECharts:
            # Issue https://github.com/holoviz/panel/issues/1817
            component = pn.pane.ECharts(_create_echarts_plot(),
                                        min_height=400,
                                        min_width=200,
                                        sizing_mode="stretch_both")
        if self.component is pnw.Ace:
            py_code = inspect.getsource(_create_hvplot)
            component = pnw.Ace(
                value=py_code,
                sizing_mode="stretch_width",
                language="python",
                height=400,
                theme=self._ace_theme,
            )
        elif self.component is pnw.AutocompleteInput:
            component = pnw.AutocompleteInput(
                name="Autocomplete Input",
                options=["Biology", "Chemistry", "Physics"],
                placeholder="Write something here",
            )
        elif self.component is pnw.Button:
            component = pnw.Button(name="Click me", button_type="primary")
        elif self.component is pnw.CheckBoxGroup:
            component = pnw.CheckBoxGroup(
                name="Checkbox Group",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                inline=True,
            )
        elif self.component is pnw.CheckButtonGroup:
            component = pnw.CheckButtonGroup(
                name="Check Button Group",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                button_type="success",
            )
        elif self.component is pnw.Checkbox:
            component = pnw.Checkbox(name="Checkbox")
        elif self.component is pnw.ColorPicker:
            component = pnw.ColorPicker(name="Color Picker", value="#DF3874")
        elif self.component is pnw.CrossSelector:
            component = pnw.CrossSelector(
                name="Fruits",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                height=300,
            )
        elif self.component is pnw.DataFrame:
            component = self.component(name="Hello")
            component.value = get_dataframe()
            component.formatters = get_default_formatters(component.value)
            controls = pn.Spacer()
        elif self.component is pnw.DatePicker:
            component = pnw.DatePicker(name="Date Picker")
            # Issue: https://github.com/holoviz/panel/issues/1810
            # component.start = date(2020, 1, 20)
            # component.end = date(2020, 2, 20)
            # component.value = date(2020, 2, 18)
        elif self.component is pnw.DateRangeSlider:
            component = self.component(name="Hello")
            component.start = date(2020, 1, 20)
            component.end = date(2020, 2, 20)
            component.value = (date(2020, 2, 18), date(2020, 2, 20))
        elif self.component is pnw.DateSlider:
            component = self.component(name="Hello")
            component.start = date(2020, 1, 20)
            component.end = date(2020, 2, 20)
            component.value = date(2020, 2, 18)
        elif self.component is pnw.DatetimeInput:
            component = self.component(name="Hello")
            component.value = datetime(2020, 2, 18, 1, 2, 3)
        elif self.component is pnw.DatetimeRangeInput:
            component = self.component(
                name="Hello",
                start=datetime(2020, 1, 20),
                end=datetime(2020, 2, 20),
                value=(datetime(2020, 2, 18), datetime(2020, 2, 20)),
            )
        elif self.component is pnw.DiscretePlayer:
            component = pnw.DiscretePlayer(
                name="Discrete Player",
                options=[2, 4, 8, 16, 32, 64, 128],
                value=32,
                loop_policy="loop",
            )
        elif self.component is pnw.DiscreteSlider:
            component = pnw.DiscreteSlider(name="Discrete Slider",
                                           options=[2, 4, 8, 16, 32, 64, 128],
                                           value=32)
        elif self.component is pnw.FileDownload:
            component = pnw.FileDownload(file="README.md",
                                         filename="README.md")
        elif self.component is pnw.FileInput:
            component = pnw.FileInput(accept=".csv,.json")
        elif self.component is pnw.FileSelector:
            component = pnw.FileSelector(name="Hello", max_height=400)
        elif self.component is pnw.FloatInput:
            component = pnw.FloatInput(name="FloatInput",
                                       value=5.0,
                                       step=1e-1,
                                       start=0,
                                       end=1000)
        elif self.component is pnw.FloatSlider:
            component = pnw.FloatSlider(name="Float Slider",
                                        start=0,
                                        end=3.141,
                                        step=0.01,
                                        value=1.57)
        elif self.component is pnw.IntInput:
            component = pnw.IntInput(name="IntInput",
                                     value=5,
                                     step=2,
                                     start=0,
                                     end=1000)
        elif self.component is pnw.IntRangeSlider:
            component = pnw.IntRangeSlider(name="Integer Range Slider",
                                           start=0,
                                           end=100,
                                           value=(8, 40),
                                           step=2)
        elif self.component is pnw.IntSlider:
            component = pnw.IntSlider(name="Integer Slider",
                                      start=0,
                                      end=20,
                                      step=2,
                                      value=4)
        elif self.component is pnw.LiteralInput:
            component = pnw.LiteralInput(name="Literal Input (dict)",
                                         value={"key": [1, 2, 3]},
                                         type=dict)
        elif self.component is pnw.MenuButton:
            menu_items = [
                ("Option A", "a"),
                ("Option B", "b"),
                ("Option C", "c"),
                None,
                ("Help", "help"),
            ]
            component = pnw.MenuButton(name="Dropdown",
                                       items=menu_items,
                                       button_type="primary")
        elif self.component is pnw.MultiChoice:
            component = pnw.MultiChoice(
                name="MultiSelect",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
            )
        elif self.component is pnw.MultiSelect:
            component = pnw.MultiSelect(
                name="MultiSelect",
                value=["Apple", "Pear"],
                options=["Apple", "Banana", "Pear", "Strawberry"],
                size=8,
            )
        elif self.component is pnw.PasswordInput:
            component = pnw.PasswordInput(name="Password Input",
                                          placeholder="Enter a string here...")
        elif self.component is pnw.Player:
            component = pnw.Player(name="Player",
                                   start=0,
                                   end=100,
                                   value=32,
                                   loop_policy="loop")
        elif self.component is pnw.Progress:
            component = pnw.Progress(name="Progress", value=20, width=200)
        elif self.component is pnw.RadioBoxGroup:
            component = pnw.RadioBoxGroup(
                name="RadioBoxGroup",
                options=["Biology", "Chemistry", "Physics"],
                inline=True)
        elif self.component is pnw.RadioButtonGroup:
            component = pnw.RadioButtonGroup(
                name="Radio Button Group",
                options=["Biology", "Chemistry", "Physics"],
                button_type="success",
            )
        elif self.component is pnw.RangeSlider:
            component = pnw.RangeSlider(
                name="Range Slider",
                start=0,
                end=math.pi,
                value=(math.pi / 4.0, math.pi / 2.0),
                step=0.01,
            )
        elif self.component is pnw.Select:
            component = pnw.Select(name="Select",
                                   options=["Biology", "Chemistry", "Physics"])
        elif self.component is pnw.StaticText:
            component = pnw.StaticText(name="Static Text", value="A string")
        elif self.component is pnw.TextAreaInput:
            component = pnw.input.TextAreaInput(
                name="Text Area Input", placeholder="Enter a string here...")
        elif self.component is pnw.TextInput:
            component = pnw.TextInput(name="Text Input",
                                      placeholder="Enter a string here...")
        elif self.component == pnw.Toggle:
            component = pnw.Toggle(name="Toggle", button_type="success")
        elif self.component == pnw.VideoStream:
            component = pnw.VideoStream(name="Video Stream",
                                        sizing_mode="stretch_width",
                                        height=300)
        if not component:
            component = self.component(name="Hello")
        if not controls:
            controls = component.controls()
        controls.margin = 0
        self._component_panel[:] = [
            pn.pane.Markdown("## " + component.__class__.name + " " +
                             self.component_type),
            component,
            pn.layout.Divider(),
            pn.pane.Markdown("## Parameters"),
            controls,
        ]