From 3479995c18b234a0038846f9440b22bbee156c78 Mon Sep 17 00:00:00 2001 From: Joseph Damiba Date: Sun, 23 Feb 2020 20:19:16 -0500 Subject: [PATCH 1/4] add new section --- _includes/layouts/side-bar.html | 8 + _includes/posts/documentation_eg.html | 32 ++++ _posts/python/2020-02-23-ai-index.html | 29 ++++ _posts/python/2020-02-23-ml-knn.md | 229 +++++++++++++++++++++++++ check-or-enforce-order.py | 2 +- front-matter-ci.py | 1 + 6 files changed, 300 insertions(+), 1 deletion(-) create mode 100644 _posts/python/2020-02-23-ai-index.html create mode 100644 _posts/python/2020-02-23-ml-knn.md diff --git a/_includes/layouts/side-bar.html b/_includes/layouts/side-bar.html index 0ffe0aae7..4b1ca0100 100644 --- a/_includes/layouts/side-bar.html +++ b/_includes/layouts/side-bar.html @@ -39,6 +39,8 @@ {% assign financial = true %} {% elsif page.display_as == "3d_charts" %} {% assign 3d_charts = true %} +{% elsif page.display_as == "ai_ml" %} +{% assign ai_ml = true %} {% elsif page.display_as == "advanced_charts"%} {% assign advanced_charts = true %} {% elsif page.display_as == "multiple_axes" %} @@ -259,6 +261,12 @@ {% endif %} + {% if ai_ml == true %} +
  • + Artificial Intelligence and Machine Learning +
  • + {% endif %} + {% if scientific == true %}
  • Scientific Charts diff --git a/_includes/posts/documentation_eg.html b/_includes/posts/documentation_eg.html index 67bd91e90..1f1b1d532 100644 --- a/_includes/posts/documentation_eg.html +++ b/_includes/posts/documentation_eg.html @@ -38,6 +38,8 @@ {% assign chart_studio = true %} {% elsif page.display_as == "advanced_opt" %} {% assign advanced_opt = true %} +{% elsif page.display_as == "ai_ml" %} +{% assign ai_ml = true %} {% elsif page.display_as == "aesthetics" %} @@ -164,6 +166,36 @@ {% endif %} +{% if ai_ml %} +
    +
    Artifical Intelligence and Machine Learning Charts +
    +
    + +
    +
    +{% endif %} + {% if scientific %}
    diff --git a/_posts/python/2020-02-23-ai-index.html b/_posts/python/2020-02-23-ai-index.html new file mode 100644 index 000000000..2818b0b61 --- /dev/null +++ b/_posts/python/2020-02-23-ai-index.html @@ -0,0 +1,29 @@ +--- +permalink: python/ai-ml/ +description: Plotly's Python graphing library makes interactive, publication-quality graphs online. Examples of how to make charts related to artificial intelligence and machine learning. +name: More Artificial Intelligence and Machine Learning Charts +layout: langindex +language: python +display_as: ai_ml +thumbnail: thumbnail/mixed.jpg +page_type: example_index +order: 5 +--- + + +
    +
    + +
    +
    +
    +

    Plotly Python Open Source Graphing Library Artificial Intelligence and Machine Learning Charts

    +

    {{page.description}}

    +
    +
    +
    +
    + + + {% assign languagelist = site.posts | where: "language","python" | where: "display_as","ai_ml" | where: "layout","base" | sort: "order" %} + {% include posts/documentation_eg.html %} diff --git a/_posts/python/2020-02-23-ml-knn.md b/_posts/python/2020-02-23-ml-knn.md new file mode 100644 index 000000000..3cf5cf8c1 --- /dev/null +++ b/_posts/python/2020-02-23-ml-knn.md @@ -0,0 +1,229 @@ +--- +description: How to visualize k-Nearest Neighbors (kNN) created using scikit-learn + in Python with Plotly. +display_as: ai_ml +language: python +layout: base +name: K-Nearest Neighbors (kNN) Classification +order: 1 +page_type: example_index +permalink: python/knn/ +redirect_from: python/machine-learning-tutorials/ +thumbnail: thumbnail/line-and-scatter.jpg +--- + +## Basic Binary Classification with `plotly.express` + +```python +import numpy as np +import plotly.express as px +import plotly.graph_objects as go +from sklearn.datasets import make_moons +from sklearn.neighbors import KNeighborsClassifier + +X, y = make_moons(noise=0.3, random_state=0) +X_test, _ = make_moons(noise=0.3, random_state=1) + +clf = KNeighborsClassifier(15) +clf.fit(X, y.astype(str)) # Fit on training set +y_pred = clf.predict(X_test) # Predict on new data + +fig = px.scatter(x=X_test[:, 0], y=X_test[:, 1], color=y_pred, labels={'color': 'predicted'}) +fig.update_traces(marker_size=10) +fig.show() +``` + +## Visualize Binary Prediction Scores + +```python +import numpy as np +import plotly.express as px +import plotly.graph_objects as go +from sklearn.datasets import make_classification +from sklearn.neighbors import KNeighborsClassifier + +X, y = make_classification(n_features=2, n_redundant=0, random_state=0) +X_test, _ = make_classification(n_features=2, n_redundant=0, random_state=1) + +clf = KNeighborsClassifier(15) +clf.fit(X, y) # Fit on training set +y_score = clf.predict_proba(X_test)[:, 1] # Predict on new data + +fig = px.scatter(x=X_test[:, 0], y=X_test[:, 1], color=y_score, labels={'color': 'score'}) +fig.update_traces(marker_size=10) +fig.show() +``` + +## Probability Estimates with `go.Contour` + +```python +import numpy as np +import plotly.express as px +import plotly.graph_objects as go +from sklearn.datasets import make_moons +from sklearn.neighbors import KNeighborsClassifier + +mesh_size = .02 +margin = 1 + +X, y = make_moons(noise=0.3, random_state=0) + +# Create a mesh grid on which we will run our model +x_min, x_max = X[:, 0].min() - margin, X[:, 0].max() + margin +y_min, y_max = X[:, 1].min() - margin, X[:, 1].max() + margin +xrange = np.arange(x_min, x_max, mesh_size) +yrange = np.arange(y_min, y_max, mesh_size) +xx, yy = np.meshgrid(xrange, yrange) + +# Create classifier, run predictions on grid +clf = KNeighborsClassifier(15, weights='uniform') +clf.fit(X, y) +Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] +Z = Z.reshape(xx.shape) + +fig = px.scatter(X, x=0, y=1, color=y.astype(str), labels={'0':'', '1':''}) +fig.update_traces(marker_size=10, marker_line_width=1) +fig.add_trace( + go.Contour( + x=xrange, + y=yrange, + z=Z, + showscale=False, + colorscale=['Blue', 'Red'], + opacity=0.4, + name='Confidence' + ) +) +fig.show() +``` + +## Multi-class prediction confidence with `go.Heatmap` + +```python +import numpy as np +import plotly.express as px +import plotly.graph_objects as go +from sklearn.neighbors import KNeighborsClassifier + +mesh_size = .02 +margin = 1 + +# We will use the iris data, which is included in px +df = px.data.iris() +X = df[['sepal_length', 'sepal_width']] +y = df.species_id + +# Create a mesh grid on which we will run our model +l_min, l_max = df.sepal_length.min() - margin, df.sepal_length.max() + margin +w_min, w_max = df.sepal_width.min() - margin, df.sepal_width.max() + margin +lrange = np.arange(l_min, l_max, mesh_size) +wrange = np.arange(w_min, w_max, mesh_size) +ll, ww = np.meshgrid(lrange, wrange) + +# Create classifier, run predictions on grid +clf = KNeighborsClassifier(15, weights='distance') +clf.fit(X, y) +Z = clf.predict(np.c_[ll.ravel(), ww.ravel()]) +Z = Z.reshape(ll.shape) +proba = clf.predict_proba(np.c_[ll.ravel(), ww.ravel()]) +proba = proba.reshape(ll.shape + (3,)) + +fig = px.scatter(df, x='sepal_length', y='sepal_width', color='species') +fig.update_traces(marker_size=10, marker_line_width=1) +fig.add_trace( + go.Heatmap( + x=lrange, + y=wrange, + z=Z, + showscale=False, + colorscale=[[0.0, 'blue'], [0.5, 'red'], [1.0, 'green']], + opacity=0.25, + customdata=proba, + hovertemplate=( + 'sepal length: %{x}
    ' + 'sepal width: %{y}
    ' + 'p(setosa): %{customdata[0]:.3f}
    ' + 'p(versicolor): %{customdata[1]:.3f}
    ' + 'p(virginica): %{customdata[2]:.3f}' + ) + ) +) +fig.show() +``` + +## 3D Classification with `px.scatter_3d` + +```python +import numpy as np +import plotly.express as px +import plotly.graph_objects as go +from sklearn.neighbors import KNeighborsClassifier +from sklearn.model_selection import train_test_split + +df = px.data.iris() +features = ["sepal_width", "sepal_length", "petal_width"] + +X = df[features] +y = df.species +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) + +# Create classifier, run predictions on grid +clf = KNeighborsClassifier(15, weights='distance') +clf.fit(X_train, y_train) +y_pred = clf.predict(X_test) +y_score = clf.predict_proba(X_test) +y_score = np.around(y_score.max(axis=1), 4) + +fig = px.scatter_3d( + X_test, + x='sepal_length', + y='sepal_width', + z='petal_width', + symbol=y_pred, + color=y_score, + labels={'symbol': 'prediction', 'color': 'score'} +) +fig.update_layout(legend=dict(x=0, y=0)) +fig.show() +``` + +## High Dimension Visualization with `px.scatter_matrix` + +If you need to visualize classifications that go beyond 3D, you can use the [scatter plot matrix](https://plot.ly/python/splom/). + +```python +import numpy as np +import plotly.express as px +import plotly.graph_objects as go +from sklearn.neighbors import KNeighborsClassifier +from sklearn.model_selection import train_test_split + +df = px.data.iris() +features = ["sepal_width", "sepal_length", "petal_width", "petal_length"] + +X = df[features] +y = df.species +X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) + +# Create classifier, run predictions on grid +clf = KNeighborsClassifier(15, weights='distance') +clf.fit(X_train, y_train) +y_pred = clf.predict(X_test) + +fig = px.scatter_matrix(X_test, dimensions=features, color=y_pred, labels={'color': 'prediction'}) +fig.show() +``` + +### Reference + +Learn more about `px`, `go.Contour`, and `go.Heatmap` here: +* https://plot.ly/python/plotly-express/ +* https://plot.ly/python/heatmaps/ +* https://plot.ly/python/contour-plots/ +* https://plot.ly/python/3d-scatter-plots/ +* https://plot.ly/python/splom/ + +This tutorial was inspired by amazing examples from the official scikit-learn docs: +* https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html +* https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html +* https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html \ No newline at end of file diff --git a/check-or-enforce-order.py b/check-or-enforce-order.py index 205c89fcd..73fd6feee 100644 --- a/check-or-enforce-order.py +++ b/check-or-enforce-order.py @@ -16,7 +16,7 @@ if sys.argv[2] == 'enforce': enforce = True -categories = ["file_settings", "basic", "financial", "statistical", "scientific", "maps", "3d_charts", "multiple_axes"] +categories = ["file_settings", "basic", "financial", "statistical", "scientific", "maps", "3d_charts", "multiple_axes", "ai_ml"] def get_post(path): return fm.load(str(path)) diff --git a/front-matter-ci.py b/front-matter-ci.py index 4f15e220c..265ccb053 100644 --- a/front-matter-ci.py +++ b/front-matter-ci.py @@ -75,6 +75,7 @@ def check_noTrailingSlash(meta_to_check): "maps", "3d_charts", "multiple_axes", + "ai_ml" ] languages = ["python", "python/v3", "plotly_js", "r"] From 40e980d127a94954f48ab510a2a314839aad7edb Mon Sep 17 00:00:00 2001 From: Joseph Damiba Date: Sun, 23 Feb 2020 20:42:47 -0500 Subject: [PATCH 2/4] update reamde with things i forgot --- _data/display_as.yml | 3 +++ _data/display_as_py_r_js.yml | 3 +++ _posts/plotly_js/README.md | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/_data/display_as.yml b/_data/display_as.yml index 572890b70..e49e0c4cb 100644 --- a/_data/display_as.yml +++ b/_data/display_as.yml @@ -19,6 +19,9 @@ basic: statistical: reference: '#statistical-charts' text: Statistical +ai_ml: + reference: '#ai-ml' + text: Artificial Intelligence and Machine Learning scientific: reference: '#scientific-charts' text: Scientific diff --git a/_data/display_as_py_r_js.yml b/_data/display_as_py_r_js.yml index fa010e283..d01a415a9 100644 --- a/_data/display_as_py_r_js.yml +++ b/_data/display_as_py_r_js.yml @@ -19,6 +19,9 @@ basic: statistical: reference: 'statistical-charts' text: Statistical Charts +ai_ml: + reference: '#ai-ml' + text: Artificial Intelligence and Machine Learning scientific: reference: 'scientific-charts' text: Scientific Charts diff --git a/_posts/plotly_js/README.md b/_posts/plotly_js/README.md index ed44a731c..42e1e9873 100644 --- a/_posts/plotly_js/README.md +++ b/_posts/plotly_js/README.md @@ -44,7 +44,7 @@ order: 5 {% assign examples = site.posts | where:"language","plotly_js" | where:"suite","add-chart-type-or-topic"| sort: "order" %} {% include posts/auto_examples.html examples=examples %} ``` - - Make sure to update `_includes/posts/documentation_eg.html` with the new chart type! + - Make sure to update `_includes/posts/documentation_eg.html`, `_includes/layouts/side-bar.html`, and `_data/display_as_py_r_js.yml` and the CI python scripts with the new chart type! - Index pages for chart categories must have `order: 5`. From f583783beeb526b34e0766f9413a204cf7de14a3 Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Tue, 18 Aug 2020 16:38:16 -0400 Subject: [PATCH 3/4] upgrade to new patterns --- _includes/layouts/side-bar.html | 2 +- _includes/posts/documentation_eg.html | 51 ++-- .../posts/mainlang_documentation_eg.html | 24 ++ _posts/python/2020-02-23-ai-index.html | 4 +- _posts/python/2020-02-23-ml-knn.md | 229 ------------------ 5 files changed, 49 insertions(+), 261 deletions(-) delete mode 100644 _posts/python/2020-02-23-ml-knn.md diff --git a/_includes/layouts/side-bar.html b/_includes/layouts/side-bar.html index 4b1ca0100..ed38adbdd 100644 --- a/_includes/layouts/side-bar.html +++ b/_includes/layouts/side-bar.html @@ -263,7 +263,7 @@ {% if ai_ml == true %}
  • - Artificial Intelligence and Machine Learning + Artificial Intelligence and Machine Learning
  • {% endif %} diff --git a/_includes/posts/documentation_eg.html b/_includes/posts/documentation_eg.html index 1f1b1d532..b92a03e3d 100644 --- a/_includes/posts/documentation_eg.html +++ b/_includes/posts/documentation_eg.html @@ -98,7 +98,7 @@ {% if show_header %} Fundamentals {% endif %} - +
      @@ -106,7 +106,7 @@ {% if page.display_as == "file_settings" %} {% include layouts/grid-item.html %} - + {% endif %} {%- endfor -%} @@ -115,12 +115,12 @@
    {% endif %} -{% if chart_type %} -
    +{% if ai_ml %} +
    {% if show_header %} - Basic Charts + Artificial Intelligence and Machine Learning {% endif %} @@ -128,8 +128,7 @@
      {%- for page in languagelist -%} - {% if page.display_as == "chart_type" or page.display_as == "basic" %} - + {% if page.display_as == "ai_ml" %} {% include layouts/grid-item.html %} @@ -141,12 +140,12 @@
    {% endif %} -{% if statistical %} -
    +{% if chart_type %} +
    {% if show_header %} - Statistical Charts + Basic Charts {% endif %} @@ -154,7 +153,8 @@
      {%- for page in languagelist -%} - {% if page.display_as == "statistical" %} + {% if page.display_as == "chart_type" or page.display_as == "basic" %} + {% include layouts/grid-item.html %} @@ -166,28 +166,23 @@
    {% endif %} -{% if ai_ml %} -
    -
    Artifical Intelligence and Machine Learning Charts +{% if statistical %} +
    +
    + {% if show_header %} + + Statistical Charts + + {% endif %} +
      {%- for page in languagelist -%} - {% if page.display_as == "ai_ml" %} - -
    • - - + {% if page.display_as == "statistical" %} - -
      {{page.name}}
      -
      - View Tutorial - {{page.name}} -
      -
      + {% include layouts/grid-item.html %} -
    • {% endif %} {%- endfor -%} @@ -908,4 +903,4 @@

      {% if page.language == "matlab" %}

      MATLAB is a registered trademark of The MathWorks, Inc.

      -{% endif %} \ No newline at end of file +{% endif %} diff --git a/_includes/posts/mainlang_documentation_eg.html b/_includes/posts/mainlang_documentation_eg.html index 43882d4dc..c1c950577 100644 --- a/_includes/posts/mainlang_documentation_eg.html +++ b/_includes/posts/mainlang_documentation_eg.html @@ -41,6 +41,8 @@ {% assign chart_studio = true %} {% elsif page.display_as == "advanced_opt" %} {% assign advanced_opt = true %} +{% elsif page.display_as == "ai_ml" %} +{% assign ai_ml = true %} {% endif %} {%- endfor -%} @@ -78,6 +80,28 @@

    {% endif %} + + +{% if ai_ml %} +
    +
    Artificial Intelligence and Machine Learning + More AI and ML » +
    +
    +
      + {%- for page in languagelist -%} + {% if page.display_as == "ai_ml" and page.order < num_examples %} + + + {% include layouts/grid-item.html %} + {% endif %} + {%- endfor -%} +
    + More AI and ML » +
    +
    +{% endif %} + {% if chart_type %}
    Basic Charts diff --git a/_posts/python/2020-02-23-ai-index.html b/_posts/python/2020-02-23-ai-index.html index 2818b0b61..ebcb59a5f 100644 --- a/_posts/python/2020-02-23-ai-index.html +++ b/_posts/python/2020-02-23-ai-index.html @@ -1,13 +1,12 @@ --- permalink: python/ai-ml/ description: Plotly's Python graphing library makes interactive, publication-quality graphs online. Examples of how to make charts related to artificial intelligence and machine learning. -name: More Artificial Intelligence and Machine Learning Charts +name: AI and ML Charts layout: langindex language: python display_as: ai_ml thumbnail: thumbnail/mixed.jpg page_type: example_index -order: 5 --- @@ -15,7 +14,6 @@
    -

    Plotly Python Open Source Graphing Library Artificial Intelligence and Machine Learning Charts

    {{page.description}}

    diff --git a/_posts/python/2020-02-23-ml-knn.md b/_posts/python/2020-02-23-ml-knn.md deleted file mode 100644 index 3cf5cf8c1..000000000 --- a/_posts/python/2020-02-23-ml-knn.md +++ /dev/null @@ -1,229 +0,0 @@ ---- -description: How to visualize k-Nearest Neighbors (kNN) created using scikit-learn - in Python with Plotly. -display_as: ai_ml -language: python -layout: base -name: K-Nearest Neighbors (kNN) Classification -order: 1 -page_type: example_index -permalink: python/knn/ -redirect_from: python/machine-learning-tutorials/ -thumbnail: thumbnail/line-and-scatter.jpg ---- - -## Basic Binary Classification with `plotly.express` - -```python -import numpy as np -import plotly.express as px -import plotly.graph_objects as go -from sklearn.datasets import make_moons -from sklearn.neighbors import KNeighborsClassifier - -X, y = make_moons(noise=0.3, random_state=0) -X_test, _ = make_moons(noise=0.3, random_state=1) - -clf = KNeighborsClassifier(15) -clf.fit(X, y.astype(str)) # Fit on training set -y_pred = clf.predict(X_test) # Predict on new data - -fig = px.scatter(x=X_test[:, 0], y=X_test[:, 1], color=y_pred, labels={'color': 'predicted'}) -fig.update_traces(marker_size=10) -fig.show() -``` - -## Visualize Binary Prediction Scores - -```python -import numpy as np -import plotly.express as px -import plotly.graph_objects as go -from sklearn.datasets import make_classification -from sklearn.neighbors import KNeighborsClassifier - -X, y = make_classification(n_features=2, n_redundant=0, random_state=0) -X_test, _ = make_classification(n_features=2, n_redundant=0, random_state=1) - -clf = KNeighborsClassifier(15) -clf.fit(X, y) # Fit on training set -y_score = clf.predict_proba(X_test)[:, 1] # Predict on new data - -fig = px.scatter(x=X_test[:, 0], y=X_test[:, 1], color=y_score, labels={'color': 'score'}) -fig.update_traces(marker_size=10) -fig.show() -``` - -## Probability Estimates with `go.Contour` - -```python -import numpy as np -import plotly.express as px -import plotly.graph_objects as go -from sklearn.datasets import make_moons -from sklearn.neighbors import KNeighborsClassifier - -mesh_size = .02 -margin = 1 - -X, y = make_moons(noise=0.3, random_state=0) - -# Create a mesh grid on which we will run our model -x_min, x_max = X[:, 0].min() - margin, X[:, 0].max() + margin -y_min, y_max = X[:, 1].min() - margin, X[:, 1].max() + margin -xrange = np.arange(x_min, x_max, mesh_size) -yrange = np.arange(y_min, y_max, mesh_size) -xx, yy = np.meshgrid(xrange, yrange) - -# Create classifier, run predictions on grid -clf = KNeighborsClassifier(15, weights='uniform') -clf.fit(X, y) -Z = clf.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1] -Z = Z.reshape(xx.shape) - -fig = px.scatter(X, x=0, y=1, color=y.astype(str), labels={'0':'', '1':''}) -fig.update_traces(marker_size=10, marker_line_width=1) -fig.add_trace( - go.Contour( - x=xrange, - y=yrange, - z=Z, - showscale=False, - colorscale=['Blue', 'Red'], - opacity=0.4, - name='Confidence' - ) -) -fig.show() -``` - -## Multi-class prediction confidence with `go.Heatmap` - -```python -import numpy as np -import plotly.express as px -import plotly.graph_objects as go -from sklearn.neighbors import KNeighborsClassifier - -mesh_size = .02 -margin = 1 - -# We will use the iris data, which is included in px -df = px.data.iris() -X = df[['sepal_length', 'sepal_width']] -y = df.species_id - -# Create a mesh grid on which we will run our model -l_min, l_max = df.sepal_length.min() - margin, df.sepal_length.max() + margin -w_min, w_max = df.sepal_width.min() - margin, df.sepal_width.max() + margin -lrange = np.arange(l_min, l_max, mesh_size) -wrange = np.arange(w_min, w_max, mesh_size) -ll, ww = np.meshgrid(lrange, wrange) - -# Create classifier, run predictions on grid -clf = KNeighborsClassifier(15, weights='distance') -clf.fit(X, y) -Z = clf.predict(np.c_[ll.ravel(), ww.ravel()]) -Z = Z.reshape(ll.shape) -proba = clf.predict_proba(np.c_[ll.ravel(), ww.ravel()]) -proba = proba.reshape(ll.shape + (3,)) - -fig = px.scatter(df, x='sepal_length', y='sepal_width', color='species') -fig.update_traces(marker_size=10, marker_line_width=1) -fig.add_trace( - go.Heatmap( - x=lrange, - y=wrange, - z=Z, - showscale=False, - colorscale=[[0.0, 'blue'], [0.5, 'red'], [1.0, 'green']], - opacity=0.25, - customdata=proba, - hovertemplate=( - 'sepal length: %{x}
    ' - 'sepal width: %{y}
    ' - 'p(setosa): %{customdata[0]:.3f}
    ' - 'p(versicolor): %{customdata[1]:.3f}
    ' - 'p(virginica): %{customdata[2]:.3f}' - ) - ) -) -fig.show() -``` - -## 3D Classification with `px.scatter_3d` - -```python -import numpy as np -import plotly.express as px -import plotly.graph_objects as go -from sklearn.neighbors import KNeighborsClassifier -from sklearn.model_selection import train_test_split - -df = px.data.iris() -features = ["sepal_width", "sepal_length", "petal_width"] - -X = df[features] -y = df.species -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) - -# Create classifier, run predictions on grid -clf = KNeighborsClassifier(15, weights='distance') -clf.fit(X_train, y_train) -y_pred = clf.predict(X_test) -y_score = clf.predict_proba(X_test) -y_score = np.around(y_score.max(axis=1), 4) - -fig = px.scatter_3d( - X_test, - x='sepal_length', - y='sepal_width', - z='petal_width', - symbol=y_pred, - color=y_score, - labels={'symbol': 'prediction', 'color': 'score'} -) -fig.update_layout(legend=dict(x=0, y=0)) -fig.show() -``` - -## High Dimension Visualization with `px.scatter_matrix` - -If you need to visualize classifications that go beyond 3D, you can use the [scatter plot matrix](https://plot.ly/python/splom/). - -```python -import numpy as np -import plotly.express as px -import plotly.graph_objects as go -from sklearn.neighbors import KNeighborsClassifier -from sklearn.model_selection import train_test_split - -df = px.data.iris() -features = ["sepal_width", "sepal_length", "petal_width", "petal_length"] - -X = df[features] -y = df.species -X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0) - -# Create classifier, run predictions on grid -clf = KNeighborsClassifier(15, weights='distance') -clf.fit(X_train, y_train) -y_pred = clf.predict(X_test) - -fig = px.scatter_matrix(X_test, dimensions=features, color=y_pred, labels={'color': 'prediction'}) -fig.show() -``` - -### Reference - -Learn more about `px`, `go.Contour`, and `go.Heatmap` here: -* https://plot.ly/python/plotly-express/ -* https://plot.ly/python/heatmaps/ -* https://plot.ly/python/contour-plots/ -* https://plot.ly/python/3d-scatter-plots/ -* https://plot.ly/python/splom/ - -This tutorial was inspired by amazing examples from the official scikit-learn docs: -* https://scikit-learn.org/stable/auto_examples/neighbors/plot_classification.html -* https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html -* https://scikit-learn.org/stable/auto_examples/datasets/plot_iris_dataset.html \ No newline at end of file From 2890459b751507950b7761d4b96435c027de9059 Mon Sep 17 00:00:00 2001 From: Nicolas Kruchten Date: Tue, 18 Aug 2020 16:52:54 -0400 Subject: [PATCH 4/4] tweak --- _includes/posts/documentation_eg.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/_includes/posts/documentation_eg.html b/_includes/posts/documentation_eg.html index b92a03e3d..d043f9fe9 100644 --- a/_includes/posts/documentation_eg.html +++ b/_includes/posts/documentation_eg.html @@ -130,7 +130,7 @@ {%- for page in languagelist -%} {% if page.display_as == "ai_ml" %} - {% include layouts/grid-item.html %} + {% include layouts/grid-item.html %} {% endif %}