{"spec_id":"contour-decision-boundary","library":"bokeh","language":"python","code":"\"\"\" anyplot.ai\ncontour-decision-boundary: Decision Boundary Classifier Visualization\nLibrary: bokeh 3.9.0 | Python 3.13.13\nQuality: 85/100 | Updated: 2026-05-16\n\"\"\"\n\nimport os\nimport sys\nimport time\nfrom pathlib import Path\n\n\n# Remove current directory from path to avoid shadowing bokeh package\nif \"\" in sys.path:\n    sys.path.remove(\"\")\nsys.path.insert(0, \"/home/runner/work/anyplot/anyplot/.venv/lib/python3.13/site-packages\")\n\n# Change to script directory to save files in the correct location\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\n# isort: off\nimport numpy as np\nfrom bokeh.io import output_file, save\nfrom bokeh.models import (\n    ColumnDataSource,\n    HoverTool,\n    Legend,\n    LegendItem,\n    LinearColorMapper,\n)\nfrom bokeh.palettes import Cividis256\nfrom bokeh.plotting import figure\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom sklearn.datasets import make_moons\nfrom sklearn.neighbors import KNeighborsClassifier\n# isort: on\n\n# Theme tokens\nTHEME = os.getenv(\"ANYPLOT_THEME\", \"light\")\nPAGE_BG = \"#FAF8F1\" if THEME == \"light\" else \"#1A1A17\"\nELEVATED_BG = \"#FFFDF6\" if THEME == \"light\" else \"#242420\"\nINK = \"#1A1A17\" if THEME == \"light\" else \"#F0EFE8\"\nINK_SOFT = \"#4A4A44\" if THEME == \"light\" else \"#B8B7B0\"\n\n# Okabe-Ito colors for classes\nCLASS_COLORS = [\"#009E73\", \"#C475FD\"]  # Positions 1 and 2 of the palette\n\n# Data - Generate synthetic classification data\nnp.random.seed(42)\nX, y = make_moons(n_samples=200, noise=0.25, random_state=42)\n\n# Train a classifier\nclf = KNeighborsClassifier(n_neighbors=15)\nclf.fit(X, y)\n\n# Create mesh grid for decision boundary\nx_min, x_max = X[:, 0].min() - 0.5, X[:, 0].max() + 0.5\ny_min, y_max = X[:, 1].min() - 0.5, X[:, 1].max() + 0.5\nh = 0.02  # Step size\nxx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n\n# Get predictions for mesh grid\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel()])\nZ = Z.reshape(xx.shape)\n\n# Create figure\np = figure(\n    width=4800,\n    height=2700,\n    title=\"Decision Boundary Classifier Visualization\",\n    x_axis_label=\"Feature 1\",\n    y_axis_label=\"Feature 2\",\n    tools=\"\",\n    toolbar_location=None,\n    x_range=(x_min, x_max),\n    y_range=(y_min, y_max),\n)\n\n# Use continuous colormap for decision regions (Cividis for diverging appearance)\ncolor_mapper = LinearColorMapper(palette=Cividis256, low=0, high=1)\np.image(\n    image=[Z.astype(float)], x=x_min, y=y_min, dw=x_max - x_min, dh=y_max - y_min, color_mapper=color_mapper, alpha=0.4\n)\n\n# Separate data points by class\nclass_0_mask = y == 0\nclass_1_mask = y == 1\n\n# Get predictions for training points to identify misclassified\ny_pred = clf.predict(X)\ncorrect_mask = y == y_pred\n\n# Data sources for each class with hover info\nsource_class0 = ColumnDataSource(\n    data={\n        \"x\": X[class_0_mask, 0],\n        \"y\": X[class_0_mask, 1],\n        \"class\": [\"Class 0\"] * np.sum(class_0_mask),\n        \"status\": [\"Correct\" if c else \"Misclassified\" for c in correct_mask[class_0_mask]],\n    }\n)\n\nsource_class1 = ColumnDataSource(\n    data={\n        \"x\": X[class_1_mask, 0],\n        \"y\": X[class_1_mask, 1],\n        \"class\": [\"Class 1\"] * np.sum(class_1_mask),\n        \"status\": [\"Correct\" if c else \"Misclassified\" for c in correct_mask[class_1_mask]],\n    }\n)\n\n# Plot training points for each class\nc0_scatter = p.scatter(\n    x=\"x\",\n    y=\"y\",\n    source=source_class0,\n    size=25,\n    fill_color=CLASS_COLORS[0],\n    line_color=\"white\",\n    line_width=3,\n    alpha=0.85,\n)\n\nc1_scatter = p.scatter(\n    x=\"x\",\n    y=\"y\",\n    source=source_class1,\n    size=25,\n    fill_color=CLASS_COLORS[1],\n    line_color=\"white\",\n    line_width=3,\n    alpha=0.85,\n)\n\n# Mark misclassified points with X marker\nmisclassified_mask = ~correct_mask\nmisclassified_marker = None\nif np.any(misclassified_mask):\n    source_misclassified = ColumnDataSource(\n        data={\n            \"x\": X[misclassified_mask, 0],\n            \"y\": X[misclassified_mask, 1],\n            \"true_class\": [f\"Class {c}\" for c in y[misclassified_mask]],\n            \"pred_class\": [f\"Class {c}\" for c in y_pred[misclassified_mask]],\n        }\n    )\n    misclassified_marker = p.scatter(\n        x=\"x\", y=\"y\", source=source_misclassified, marker=\"x\", size=45, line_color=\"#CC3333\", line_width=5, alpha=1.0\n    )\n\n# Add HoverTool for interactivity\nhover = HoverTool(\n    tooltips=[(\"Feature 1\", \"@x{0.2f}\"), (\"Feature 2\", \"@y{0.2f}\"), (\"Class\", \"@class\"), (\"Status\", \"@status\")],\n    renderers=[c0_scatter, c1_scatter],\n)\np.add_tools(hover)\n\n# Add separate HoverTool for misclassified points\nif misclassified_marker is not None:\n    hover_misclassified = HoverTool(\n        tooltips=[\n            (\"Feature 1\", \"@x{0.2f}\"),\n            (\"Feature 2\", \"@y{0.2f}\"),\n            (\"True Class\", \"@true_class\"),\n            (\"Predicted\", \"@pred_class\"),\n        ],\n        renderers=[misclassified_marker],\n    )\n    p.add_tools(hover_misclassified)\n\n# Create legend with classes and misclassified entry\nlegend_items = [\n    LegendItem(label=\"Class 0\", renderers=[c0_scatter]),\n    LegendItem(label=\"Class 1\", renderers=[c1_scatter]),\n]\nif misclassified_marker is not None:\n    legend_items.append(LegendItem(label=\"Misclassified\", renderers=[misclassified_marker]))\n\nlegend = Legend(items=legend_items, location=\"top_right\")\nlegend.label_text_font_size = \"18pt\"\nlegend.glyph_height = 35\nlegend.glyph_width = 35\nlegend.background_fill_alpha = 0.95\nlegend.padding = 15\nlegend.spacing = 10\np.add_layout(legend, \"right\")\n\n# Title and axis styling\np.title.text_font_size = \"28pt\"\np.title.text_color = INK\np.xaxis.axis_label_text_font_size = \"22pt\"\np.yaxis.axis_label_text_font_size = \"22pt\"\np.xaxis.axis_label_text_color = INK\np.yaxis.axis_label_text_color = INK\np.xaxis.major_label_text_font_size = \"18pt\"\np.yaxis.major_label_text_font_size = \"18pt\"\np.xaxis.major_label_text_color = INK_SOFT\np.yaxis.major_label_text_color = INK_SOFT\n\n# Grid styling\np.xgrid.grid_line_color = INK\np.ygrid.grid_line_color = INK\np.xgrid.grid_line_alpha = 0.10\np.ygrid.grid_line_alpha = 0.10\n\n# Axis and background styling\np.xaxis.axis_line_color = INK_SOFT\np.yaxis.axis_line_color = INK_SOFT\np.xaxis.major_tick_line_color = INK_SOFT\np.yaxis.major_tick_line_color = INK_SOFT\np.background_fill_color = PAGE_BG\np.border_fill_color = PAGE_BG\np.outline_line_color = INK_SOFT\n\n# Legend styling\nif legend:\n    legend.background_fill_color = ELEVATED_BG\n    legend.border_line_color = INK_SOFT\n    legend.label_text_color = INK_SOFT\n\n# Save HTML file\noutput_file(f\"plot-{THEME}.html\")\nsave(p)\n\n# Screenshot with Selenium\nW, H = 4800, 2700\nopts = Options()\nfor arg in (\n    \"--headless=new\",\n    \"--no-sandbox\",\n    \"--disable-dev-shm-usage\",\n    \"--disable-gpu\",\n    f\"--window-size={W},{H}\",\n    \"--hide-scrollbars\",\n):\n    opts.add_argument(arg)\n\ndriver = webdriver.Chrome(options=opts)\ndriver.set_window_size(W, H)\ndriver.get(f\"file://{Path(f'plot-{THEME}.html').resolve()}\")\ntime.sleep(3)  # Let Bokeh's JS render the canvas\ndriver.save_screenshot(f\"plot-{THEME}.png\")\ndriver.quit()\n"}