CoolFace
Apppublic

computerscience-person/CC229_Marimo_Demo

sourceHugging Facemitupdated 2y agoView on Hugging Face
1likes
app.py274 linesDownload Raw Back to root
1import marimo2 3__generated_with = "0.10.16"4app = marimo.App()5 6 7@app.cell8def _():9    import marimo as mo10    import polars as pl11    from sklearn import datasets12    from sklearn.model_selection import train_test_split13    from sklearn.tree import DecisionTreeClassifier14    from sklearn.metrics import accuracy_score, classification_report, confusion_matrix15 16    mo.md("# Iris Dataset Showcase")17    return (18        DecisionTreeClassifier,19        accuracy_score,20        classification_report,21        confusion_matrix,22        datasets,23        mo,24        pl,25        train_test_split,26    )27 28 29@app.cell(hide_code=True)30def _(datasets):31    iris = datasets.load_iris()32    X = iris.data33    y = iris.target34    return X, iris, y35 36 37@app.cell(hide_code=True)38def _(X, train_test_split, y):39    # Split the dataset into training and testing sets40    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)41    return X_test, X_train, y_test, y_train42 43 44@app.cell45def _(DecisionTreeClassifier, X_train, mo, y_train):46    classifier = DecisionTreeClassifier()47 48    classifier.fit(X_train, y_train)49    mo.md(f"""50        ## Decision Tree Classifier51    """)52    return (classifier,)53 54 55@app.cell56def _(X_test, classifier):57    y_pred = classifier.predict(X_test)58    return (y_pred,)59 60 61@app.cell62def _(63    accuracy_score,64    classification_report,65    confusion_matrix,66    mo,67    y_pred,68    y_test,69):70    # Calculate accuracy71    accuracy = accuracy_score(y_test, y_pred)72 73    # Confusion matrix74    conf_matrix = confusion_matrix(y_test, y_pred)75 76    # Classification report77    class_report = classification_report(y_test, y_pred)78 79    mo.md(f"""80        Accuracy: {accuracy}81 82        Confusion Matrix:83    ```84        {conf_matrix}85    ```86 87 88        Classification Report:89    ```90        {class_report}91    ```92    """)93    return accuracy, class_report, conf_matrix94 95 96@app.cell97def _(X_test, pl, y_pred, y_test):98    import seaborn as sns99    import matplotlib.pyplot as plt100 101    df = pl.DataFrame({102        "sepal length (cm)": X_test[:, 0],103        "sepal width (cm)": X_test[:, 1],104        "Predicted": y_pred,105        "Actual": y_test106    })107    return df, plt, sns108 109 110@app.cell111def _(df, mo, plt, sns):112    plt.figure(figsize=(10, 6))113    sns.scatterplot(data=df, x='sepal length (cm)', y='sepal width (cm)', hue='Predicted', style='Actual', palette='Set1', markers=['o', 's', 'D'])114    plt.title('Iris Dataset: Sepal Length vs Sepal Width')115    plt.xlabel('Sepal Length (cm)')116    plt.ylabel('Sepal Width (cm)')117    plt.legend(title='Class')118    mo.vstack(119        [120            mo.md("## Iris Dataset"),121            plt.gcf()122        ]123    )124    return125 126 127@app.cell128def _(conf_matrix, iris, mo, plt, sns):129    plt.figure(figsize=(8, 6))130    sns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=iris.target_names, yticklabels=iris.target_names)131    plt.xlabel('Predicted')132    plt.ylabel('Actual')133    mo.vstack([134        mo.md("## Confusion Matrix"),135        plt.gcf()136    ])137    return138 139 140@app.cell(hide_code=True)141def _(iris, pl):142    iris_df = pl.DataFrame(data=iris.data, schema=iris.feature_names)143    iris_df = iris_df.with_columns(pl.Series("species", iris.target))144    return (iris_df,)145 146 147@app.cell148def _(iris_df, mo, plt, sns):149    sns.pairplot(iris_df.to_pandas(), hue='species', palette='Set1', markers=["o", "s", "D"])150    mo.vstack([151        mo.md("## Pair Plot"),152        plt.gcf()153    ])154    return155 156 157@app.cell158def _(classifier, iris, mo, plt):159    from sklearn.tree import plot_tree160 161    plt.figure(figsize=(12, 8))162    plot_tree(classifier, filled=True, feature_names=iris.feature_names, class_names=iris.target_names)163    mo.vstack([164        mo.md("## Classifier Decision Tree Visualization"),165        plt.gcf()166    ])167    return (plot_tree,)168 169 170@app.cell(hide_code=True)171def _():172    tips = {173        "Saving": (174            """175            **Saving**176 177            - _Name_ your app using the box at the top of the screen, or178              with `Ctrl/Cmd+s`. You can also create a named app at the179              command line, e.g., `marimo edit app_name.py`.180 181            - _Save_ by clicking the save icon on the bottom right, or by182              inputting `Ctrl/Cmd+s`. By default marimo is configured183              to autosave.184            """185        ),186        "Running": (187            """188            1. _Run a cell_ by clicking the play ( ▷ ) button on the top189            right of a cell, or by inputting `Ctrl/Cmd+Enter`.190 191            2. _Run a stale cell_  by clicking the yellow run button on the192            right of the cell, or by inputting `Ctrl/Cmd+Enter`. A cell is193            stale when its code has been modified but not run.194 195            3. _Run all stale cells_ by clicking the play ( ▷ ) button on196            the bottom right of the screen, or input `Ctrl/Cmd+Shift+r`.197            """198        ),199        "Console Output": (200            """201            Console output (e.g., `print()` statements) is shown below a202            cell.203            """204        ),205        "Creating, Moving, and Deleting Cells": (206            """207            1. _Create_ a new cell above or below a given one by clicking208                the plus button to the left of the cell, which appears on209                mouse hover.210 211            2. _Move_ a cell up or down by dragging on the handle to the 212                right of the cell, which appears on mouse hover.213 214            3. _Delete_ a cell by clicking the trash bin icon. Bring it215                back by clicking the undo button on the bottom right of the216                screen, or with `Ctrl/Cmd+Shift+z`.217            """218        ),219        "Disabling Automatic Execution": (220            """221            Via the notebook settings (gear icon) or footer panel, you222            can disable automatic execution. This is helpful when223            working with expensive notebooks or notebooks that have224            side-effects like database transactions.225            """226        ),227        "Disabling Cells": (228            """229            You can disable a cell via the cell context menu.230            marimo will never run a disabled cell or any cells that depend on it.231            This can help prevent accidental execution of expensive computations232            when editing a notebook.233            """234        ),235        "Code Folding": (236            """237            You can collapse or fold the code in a cell by clicking the arrow238            icons in the line number column to the left, or by using keyboard239            shortcuts.240 241            Use the command palette (`Ctrl/Cmd+k`) or a keyboard shortcut to242            quickly fold or unfold all cells.243            """244        ),245        "Code Formatting": (246            """247            If you have [ruff](https://github.com/astral-sh/ruff) installed,248            you can format a cell with the keyboard shortcut `Ctrl/Cmd+b`.249            """250        ),251        "Command Palette": (252            """253            Use `Ctrl/Cmd+k` to open the command palette.254            """255        ),256        "Keyboard Shortcuts": (257            """258            Open the notebook menu (top-right) or input `Ctrl/Cmd+Shift+h` to259            view a list of all keyboard shortcuts.260            """261        ),262        "Configuration": (263            """264           Configure the editor by clicking the gears icon near the top-right265           of the screen.266           """267        ),268    }269    return (tips,)270 271 272if __name__ == "__main__":273    app.run()274