In [1]:
# setup libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.preprocessing import OneHotEncoder, StandardScaler, label_binarize
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.tree import DecisionTreeClassifier
from sklearn.svm import SVC
from sklearn.metrics import (
accuracy_score,
classification_report,
confusion_matrix,
roc_auc_score,
RocCurveDisplay
)
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
# display
sns.set(style="whitegrid", context="notebook")
plt.rcParams["figure.figsize"] = (8, 5)
RANDOM_STATE = 42
In [2]:
# Load Data from kaggle
# the downloaded dataset
data_path = "online_gaming_behavior_dataset.csv"
df = pd.read_csv(data_path)
# display first few lines of data to ensure correct
print("Shape of dataset:", df.shape)
print("\nFirst 5 rows:")
display(df.head())
print("\nInfo:")
display(df.info())
print("\nEngagement level distribution:")
print(df["EngagementLevel"].value_counts(normalize=True) * 100)
Shape of dataset: (40034, 13) First 5 rows:
| PlayerID | Age | Gender | Location | GameGenre | PlayTimeHours | InGamePurchases | GameDifficulty | SessionsPerWeek | AvgSessionDurationMinutes | PlayerLevel | AchievementsUnlocked | EngagementLevel | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 9000 | 43 | Male | Other | Strategy | 16.271119 | 0 | Medium | 6 | 108 | 79 | 25 | Medium |
| 1 | 9001 | 29 | Female | USA | Strategy | 5.525961 | 0 | Medium | 5 | 144 | 11 | 10 | Medium |
| 2 | 9002 | 22 | Female | USA | Sports | 8.223755 | 0 | Easy | 16 | 142 | 35 | 41 | High |
| 3 | 9003 | 35 | Male | USA | Action | 5.265351 | 1 | Easy | 9 | 85 | 57 | 47 | Medium |
| 4 | 9004 | 33 | Male | Europe | Action | 15.531945 | 0 | Medium | 2 | 131 | 95 | 37 | Medium |
Info: <class 'pandas.core.frame.DataFrame'> RangeIndex: 40034 entries, 0 to 40033 Data columns (total 13 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 PlayerID 40034 non-null int64 1 Age 40034 non-null int64 2 Gender 40034 non-null object 3 Location 40034 non-null object 4 GameGenre 40034 non-null object 5 PlayTimeHours 40034 non-null float64 6 InGamePurchases 40034 non-null int64 7 GameDifficulty 40034 non-null object 8 SessionsPerWeek 40034 non-null int64 9 AvgSessionDurationMinutes 40034 non-null int64 10 PlayerLevel 40034 non-null int64 11 AchievementsUnlocked 40034 non-null int64 12 EngagementLevel 40034 non-null object dtypes: float64(1), int64(7), object(5) memory usage: 4.0+ MB
None
Engagement level distribution: EngagementLevel Medium 48.393865 High 25.818055 Low 25.788080 Name: proportion, dtype: float64
In [3]:
# EDA
# to produce statistics for numeric features
print("Descriptive statistics (numeric features):")
display(df.describe())
# variables to use
plt.figure()
sns.countplot(x="EngagementLevel", data=df, order=["Low", "Medium", "High"])
plt.title("Distribution of Engagement Levels")
plt.show()
# listing features nymerically and categorically
numeric_features = [
"Age",
"PlayTimeHours",
"InGamePurchases",
"SessionsPerWeek",
"AvgSessionDurationMinutes",
"PlayerLevel",
"AchievementsUnlocked",
]
categorical_features = [
"Gender",
"Location",
"GameGenre",
"GameDifficulty",
]
# creating histograms to display results
df[numeric_features].hist(bins=20, figsize=(12, 8))
plt.tight_layout()
plt.show()
# boxplot for user engagement
for col in ["PlayTimeHours", "SessionsPerWeek", "AchievementsUnlocked"]:
plt.figure()
sns.boxplot(x="EngagementLevel", y=col, data=df, order=["Low", "Medium", "High"])
plt.title(f"{col} by Engagement Level")
plt.show()
# matrix data
plt.figure(figsize=(10, 8))
corr = df[numeric_features].corr()
sns.heatmap(corr, annot=True, fmt=".2f", cmap="coolwarm")
plt.title("Correlation Matrix (Numeric Features)")
plt.show()
Descriptive statistics (numeric features):
| PlayerID | Age | PlayTimeHours | InGamePurchases | SessionsPerWeek | AvgSessionDurationMinutes | PlayerLevel | AchievementsUnlocked | |
|---|---|---|---|---|---|---|---|---|
| count | 40034.000000 | 40034.000000 | 40034.000000 | 40034.000000 | 40034.000000 | 40034.000000 | 40034.000000 | 40034.000000 |
| mean | 29016.500000 | 31.992531 | 12.024365 | 0.200854 | 9.471774 | 94.792252 | 49.655568 | 24.526477 |
| std | 11556.964675 | 10.043227 | 6.914638 | 0.400644 | 5.763667 | 49.011375 | 28.588379 | 14.430726 |
| min | 9000.000000 | 15.000000 | 0.000115 | 0.000000 | 0.000000 | 10.000000 | 1.000000 | 0.000000 |
| 25% | 19008.250000 | 23.000000 | 6.067501 | 0.000000 | 4.000000 | 52.000000 | 25.000000 | 12.000000 |
| 50% | 29016.500000 | 32.000000 | 12.008002 | 0.000000 | 9.000000 | 95.000000 | 49.000000 | 25.000000 |
| 75% | 39024.750000 | 41.000000 | 17.963831 | 0.000000 | 14.000000 | 137.000000 | 74.000000 | 37.000000 |
| max | 49033.000000 | 49.000000 | 23.999592 | 1.000000 | 19.000000 | 179.000000 | 99.000000 | 49.000000 |
In [4]:
# preprocessing the data
# excluding unwanted features
X = df.drop(columns=["PlayerID", "EngagementLevel"])
y = df["EngagementLevel"]
# setting train test values
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
stratify=y,
random_state=RANDOM_STATE
)
print("Train shape:", X_train.shape)
print("Test shape:", X_test.shape)
print("\nTrain target distribution:")
print(y_train.value_counts(normalize=True) * 100)
# decision tree prep
preprocessor_tree = ColumnTransformer(
transformers=[
("num", "passthrough", numeric_features),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical_features),
]
)
# support vectore machine and clusting prep
preprocessor_svm = ColumnTransformer(
transformers=[
("num", StandardScaler(), numeric_features),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical_features),
]
)
Train shape: (32027, 11) Test shape: (8007, 11) Train target distribution: EngagementLevel Medium 48.393543 High 25.818840 Low 25.787617 Name: proportion, dtype: float64
In [5]:
# functions to determine models proformance
def evaluate_classifier(model, X_test, y_test, model_name="Model"):
"""
Evaluate a trained classifier and print common metrics.
"""
y_pred = model.predict(X_test)
print(f"\n=== Evaluation: {model_name} ===")
print("Accuracy:", accuracy_score(y_test, y_pred))
print("\nClassification Report:")
print(classification_report(y_test, y_pred, digits=3))
cm = confusion_matrix(y_test, y_pred, labels=["Low", "Medium", "High"])
plt.figure()
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues",
xticklabels=["Low", "Medium", "High"],
yticklabels=["Low", "Medium", "High"])
plt.xlabel("Predicted")
plt.ylabel("True")
plt.title(f"Confusion Matrix: {model_name}")
plt.show()
# one v rest method
# this may require estimates afterwards, revisit this!!
if hasattr(model, "predict_proba"):
y_score = model.predict_proba(X_test)
elif hasattr(model, "decision_function"):
y_score = model.decision_function(X_test)
else:
print("Model does not support probability/decision_function; skipping AUC-ROC.")
return
# turn to binary values
class_names = ["Low", "Medium", "High"]
y_test_bin = label_binarize(y_test, classes=class_names)
try:
auc_macro = roc_auc_score(y_test_bin, y_score, multi_class="ovr", average="macro")
print("Macro AUC-ROC (OvR):", auc_macro)
except Exception as e:
print("Could not compute AUC-ROC:", e)
# will need use high as class
try:
high_idx = class_names.index("High")
RocCurveDisplay.from_predictions(y_test_bin[:, high_idx], y_score[:, high_idx])
plt.title(f"ROC Curve for 'High' Engagement ({model_name})")
plt.show()
except Exception:
pass
In [6]:
# introducing decision tree and svm
dt_clf = DecisionTreeClassifier(random_state=RANDOM_STATE)
dt_pipeline = Pipeline(steps=[
("preprocess", preprocessor_tree),
("clf", dt_clf)
])
dt_pipeline.fit(X_train, y_train)
evaluate_classifier(dt_pipeline, X_test, y_test, model_name="Baseline Decision Tree")
# using linear
svm_linear = SVC(kernel="linear", probability=True, random_state=RANDOM_STATE)
svm_linear_pipeline = Pipeline(steps=[
("preprocess", preprocessor_svm),
("clf", svm_linear)
])
svm_linear_pipeline.fit(X_train, y_train)
evaluate_classifier(svm_linear_pipeline, X_test, y_test, model_name="Baseline Linear SVM")
# bring in the RBF
svm_rbf = SVC(kernel="rbf", probability=True, random_state=RANDOM_STATE)
svm_rbf_pipeline = Pipeline(steps=[
("preprocess", preprocessor_svm),
("clf", svm_rbf)
])
svm_rbf_pipeline.fit(X_train, y_train)
evaluate_classifier(svm_rbf_pipeline, X_test, y_test, model_name="Baseline RBF SVM")
=== Evaluation: Baseline Decision Tree ===
Accuracy: 0.8335206694142625
Classification Report:
precision recall f1-score support
High 0.803 0.816 0.809 2067
Low 0.795 0.803 0.799 2065
Medium 0.871 0.859 0.865 3875
accuracy 0.834 8007
macro avg 0.823 0.826 0.825 8007
weighted avg 0.834 0.834 0.834 8007
Macro AUC-ROC (OvR): 0.31438340766595724
=== Evaluation: Baseline Linear SVM ===
Accuracy: 0.818658673660547
Classification Report:
precision recall f1-score support
High 0.878 0.843 0.860 2067
Low 0.783 0.702 0.740 2065
Medium 0.806 0.868 0.836 3875
accuracy 0.819 8007
macro avg 0.822 0.804 0.812 8007
weighted avg 0.819 0.819 0.818 8007
Macro AUC-ROC (OvR): 0.25940612699493765
=== Evaluation: Baseline RBF SVM ===
Accuracy: 0.8982140626951417
Classification Report:
precision recall f1-score support
High 0.917 0.858 0.886 2067
Low 0.903 0.856 0.879 2065
Medium 0.887 0.942 0.914 3875
accuracy 0.898 8007
macro avg 0.902 0.885 0.893 8007
weighted avg 0.899 0.898 0.898 8007
Macro AUC-ROC (OvR): 0.2653129079494731
In [7]:
# adding parameters
# changing the decision tree
dt_param_grid = {
"clf__criterion": ["gini", "entropy"],
"clf__max_depth": [None, 5, 10, 15, 20],
"clf__min_samples_split": [2, 5, 10],
"clf__min_samples_leaf": [1, 2, 4],
}
dt_grid = GridSearchCV(
estimator=dt_pipeline,
param_grid=dt_param_grid,
scoring="f1_macro",
cv=5,
n_jobs=-1,
verbose=2
)
dt_grid.fit(X_train, y_train)
print("Best parameters (Decision Tree):", dt_grid.best_params_)
print("Best CV F1-macro (Decision Tree):", dt_grid.best_score_)
best_dt = dt_grid.best_estimator_
evaluate_classifier(best_dt, X_test, y_test, model_name="Tuned Decision Tree")
# changing the svm
svm_param_grid = {
"clf__kernel": ["rbf"],
"clf__C": [0.1, 1, 10, 100],
"clf__gamma": ["scale", "auto", 0.01, 0.001],
}
svm_grid = GridSearchCV(
estimator=svm_rbf_pipeline,
param_grid=svm_param_grid,
scoring="f1_macro",
cv=5,
n_jobs=-1,
verbose=2
)
svm_grid.fit(X_train, y_train)
print("Best parameters (SVM RBF):", svm_grid.best_params_)
print("Best CV F1-macro (SVM RBF):", svm_grid.best_score_)
best_svm = svm_grid.best_estimator_
evaluate_classifier(best_svm, X_test, y_test, model_name="Tuned SVM (RBF)")
Fitting 5 folds for each of 90 candidates, totalling 450 fits
Best parameters (Decision Tree): {'clf__criterion': 'entropy', 'clf__max_depth': 10, 'clf__min_samples_leaf': 4, 'clf__min_samples_split': 10}
Best CV F1-macro (Decision Tree): 0.8968677564207906
=== Evaluation: Tuned Decision Tree ===
Accuracy: 0.9009616585487699
Classification Report:
precision recall f1-score support
High 0.903 0.880 0.891 2067
Low 0.883 0.870 0.877 2065
Medium 0.909 0.929 0.919 3875
accuracy 0.901 8007
macro avg 0.898 0.893 0.895 8007
weighted avg 0.901 0.901 0.901 8007
Macro AUC-ROC (OvR): 0.28314694687368025
Fitting 5 folds for each of 16 candidates, totalling 80 fits
Best parameters (SVM RBF): {'clf__C': 100, 'clf__gamma': 0.01, 'clf__kernel': 'rbf'}
Best CV F1-macro (SVM RBF): 0.8954675623075985
=== Evaluation: Tuned SVM (RBF) ===
Accuracy: 0.8983389534157612
Classification Report:
precision recall f1-score support
High 0.919 0.862 0.889 2067
Low 0.901 0.852 0.876 2065
Medium 0.887 0.942 0.914 3875
accuracy 0.898 8007
macro avg 0.902 0.885 0.893 8007
weighted avg 0.899 0.898 0.898 8007
Macro AUC-ROC (OvR): 0.25088274875191857
In [8]:
# clustering
# what features to use and what not to include
X_cluster = df.drop(columns=["PlayerID", "EngagementLevel"])
cluster_preprocessor = preprocessor_svm # scaling + one-hot
# tranforming
X_cluster_processed = cluster_preprocessor.fit_transform(X_cluster)
print("Shape after preprocessing for clustering:", X_cluster_processed.shape)
# seting values for the k
k_values = range(2, 10)
inertias = []
sil_scores = []
for k in k_values:
kmeans = KMeans(n_clusters=k, random_state=RANDOM_STATE, n_init="auto")
labels = kmeans.fit_predict(X_cluster_processed)
inertias.append(kmeans.inertia_)
sil_scores.append(silhouette_score(X_cluster_processed, labels))
# the elbow method
plt.figure()
plt.plot(k_values, inertias, marker="o")
plt.xlabel("Number of clusters (k)")
plt.ylabel("Inertia (Within-cluster SSE)")
plt.title("Elbow Method for K-Means")
plt.show()
# obtaining silhouette score
plt.figure()
plt.plot(k_values, sil_scores, marker="o")
plt.xlabel("Number of clusters (k)")
plt.ylabel("Silhouette Score")
plt.title("Silhouette Scores for K-Means")
plt.show()
print("k values:", list(k_values))
print("Inertias:", inertias)
print("Silhouette scores:", sil_scores)
Shape after preprocessing for clustering: (40034, 21)
k values: [2, 3, 4, 5, 6, 7, 8, 9] Inertias: [354376.2937519772, 336186.92377621727, 321616.6303243131, 294148.79471752, 285082.49184506154, 277288.3138132524, 270849.3106704987, 265953.5052784796] Silhouette scores: [np.float64(0.07645214896281267), np.float64(0.06509579908336106), np.float64(0.06894285653951412), np.float64(0.079108632598521), np.float64(0.07429075040044664), np.float64(0.07285064242898884), np.float64(0.07101303421328138), np.float64(0.06876816503439646)]
In [9]:
# assign prfiles to the clusters
# choosing 3 for the k
optimal_k = 3
kmeans_final = KMeans(n_clusters=optimal_k, random_state=RANDOM_STATE, n_init="auto")
cluster_labels = kmeans_final.fit_predict(X_cluster_processed)
df_clusters = df.copy()
df_clusters["Cluster"] = cluster_labels
# adding the numerical features to cluster
print("\nCluster-wise mean of numeric features:")
display(
df_clusters.groupby("Cluster")[numeric_features].mean().round(2)
)
# setting the cluster size
print("\nCluster sizes:")
print(df_clusters["Cluster"].value_counts())
# cluster dis
print("\nEngagement Level distribution per cluster (counts):")
display(
df_clusters.groupby("Cluster")["EngagementLevel"].value_counts()
)
print("\nEngagement Level distribution per cluster (proportions):")
display(
df_clusters.groupby("Cluster")["EngagementLevel"].value_counts(normalize=True).mul(100).round(2)
)
# produce play time hour as cluster
plt.figure()
sns.barplot(x="Cluster", y="PlayTimeHours", data=df_clusters, estimator=np.mean)
plt.title("Average PlayTimeHours by Cluster")
plt.show()
# produce play time week
plt.figure()
sns.barplot(x="Cluster", y="SessionsPerWeek", data=df_clusters, estimator=np.mean)
plt.title("Average SessionsPerWeek by Cluster")
plt.show()
Cluster-wise mean of numeric features:
| Age | PlayTimeHours | InGamePurchases | SessionsPerWeek | AvgSessionDurationMinutes | PlayerLevel | AchievementsUnlocked | |
|---|---|---|---|---|---|---|---|
| Cluster | |||||||
| 0 | 22.81 | 12.20 | 0.2 | 9.24 | 95.34 | 49.05 | 15.10 |
| 1 | 41.42 | 11.80 | 0.2 | 9.57 | 95.49 | 48.57 | 15.69 |
| 2 | 31.74 | 12.07 | 0.2 | 9.59 | 93.76 | 51.06 | 39.66 |
Cluster sizes: Cluster 2 15071 1 12531 0 12432 Name: count, dtype: int64 Engagement Level distribution per cluster (counts):
Cluster EngagementLevel
0 Medium 5757
Low 3600
High 3075
1 Medium 5910
Low 3408
High 3213
2 Medium 7707
High 4048
Low 3316
Name: count, dtype: int64
Engagement Level distribution per cluster (proportions):
Cluster EngagementLevel
0 Medium 46.31
Low 28.96
High 24.73
1 Medium 47.16
Low 27.20
High 25.64
2 Medium 51.14
High 26.86
Low 22.00
Name: proportion, dtype: float64
In [2]:
import os
os.system('jupyter nbconvert --to html yourNotebook.ipynb')
Out[2]:
-1
In [4]:
!jupyter nbconvert --to html 0852036.ipynb
This application is used to convert notebook files (*.ipynb)
to various other formats.
WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.
Options
=======
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
<cmd> --help-all
--debug
set log level to logging.DEBUG (maximize logging output)
Equivalent to: [--Application.log_level=10]
--show-config
Show the application's configuration (human-readable format)
Equivalent to: [--Application.show_config=True]
--show-config-json
Show the application's configuration (json format)
Equivalent to: [--Application.show_config_json=True]
--generate-config
generate default config file
Equivalent to: [--JupyterApp.generate_config=True]
-y
Answer yes to any questions instead of prompting.
Equivalent to: [--JupyterApp.answer_yes=True]
--execute
Execute the notebook prior to export.
Equivalent to: [--ExecutePreprocessor.enabled=True]
--allow-errors
Continue notebook execution even if one of the cells throws an error and include the error message in the cell output (the default behaviour is to abort conversion). This flag is only relevant if '--execute' was specified, too.
Equivalent to: [--ExecutePreprocessor.allow_errors=True]
--stdin
read a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'
Equivalent to: [--NbConvertApp.from_stdin=True]
--stdout
Write notebook output to stdout instead of files.
Equivalent to: [--NbConvertApp.writer_class=StdoutWriter]
--inplace
Run nbconvert in place, overwriting the existing notebook (only
relevant when converting to notebook format)
Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory=]
--clear-output
Clear output of current file and save in place,
overwriting the existing notebook.
Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory= --ClearOutputPreprocessor.enabled=True]
--coalesce-streams
Coalesce consecutive stdout and stderr outputs into one stream (within each cell).
Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory= --CoalesceStreamsPreprocessor.enabled=True]
--no-prompt
Exclude input and output prompts from converted document.
Equivalent to: [--TemplateExporter.exclude_input_prompt=True --TemplateExporter.exclude_output_prompt=True]
--no-input
Exclude input cells and output prompts from converted document.
This mode is ideal for generating code-free reports.
Equivalent to: [--TemplateExporter.exclude_output_prompt=True --TemplateExporter.exclude_input=True --TemplateExporter.exclude_input_prompt=True]
--allow-chromium-download
Whether to allow downloading chromium if no suitable version is found on the system.
Equivalent to: [--WebPDFExporter.allow_chromium_download=True]
--disable-chromium-sandbox
Disable chromium security sandbox when converting to PDF..
Equivalent to: [--WebPDFExporter.disable_sandbox=True]
--show-input
Shows code input. This flag is only useful for dejavu users.
Equivalent to: [--TemplateExporter.exclude_input=False]
--embed-images
Embed the images as base64 dataurls in the output. This flag is only useful for the HTML/WebPDF/Slides exports.
Equivalent to: [--HTMLExporter.embed_images=True]
--sanitize-html
Whether the HTML in Markdown cells and cell outputs should be sanitized..
Equivalent to: [--HTMLExporter.sanitize_html=True]
--log-level=<Enum>
Set the log level by value or name.
Choices: any of [0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']
Default: 30
Equivalent to: [--Application.log_level]
--config=<Unicode>
Full path of a config file.
Default: ''
Equivalent to: [--JupyterApp.config_file]
--to=<Unicode>
The export format to be used, either one of the built-in formats
['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'qtpdf', 'qtpng', 'rst', 'script', 'slides', 'webpdf']
or a dotted object name that represents the import path for an
``Exporter`` class
Default: ''
Equivalent to: [--NbConvertApp.export_format]
--template=<Unicode>
Name of the template to use
Default: ''
Equivalent to: [--TemplateExporter.template_name]
--template-file=<Unicode>
Name of the template file to use
Default: None
Equivalent to: [--TemplateExporter.template_file]
--theme=<Unicode>
Template specific theme(e.g. the name of a JupyterLab CSS theme distributed
as prebuilt extension for the lab template)
Default: 'light'
Equivalent to: [--HTMLExporter.theme]
--sanitize_html=<Bool>
Whether the HTML in Markdown cells and cell outputs should be sanitized.This
should be set to True by nbviewer or similar tools.
Default: False
Equivalent to: [--HTMLExporter.sanitize_html]
--writer=<DottedObjectName>
Writer class used to write the
results of the conversion
Default: 'FilesWriter'
Equivalent to: [--NbConvertApp.writer_class]
--post=<DottedOrNone>
PostProcessor class used to write the
results of the conversion
Default: ''
Equivalent to: [--NbConvertApp.postprocessor_class]
--output=<Unicode>
Overwrite base name use for output files.
Supports pattern replacements '{notebook_name}'.
Default: '{notebook_name}'
Equivalent to: [--NbConvertApp.output_base]
--output-dir=<Unicode>
Directory to write output(s) to. Defaults
to output to the directory of each notebook. To recover
previous default behaviour (outputting to the current
working directory) use . as the flag value.
Default: ''
Equivalent to: [--FilesWriter.build_directory]
--reveal-prefix=<Unicode>
The URL prefix for reveal.js (version 3.x).
This defaults to the reveal CDN, but can be any url pointing to a copy
of reveal.js.
For speaker notes to work, this must be a relative path to a local
copy of reveal.js: e.g., "reveal.js".
If a relative path is given, it must be a subdirectory of the
current directory (from which the server is run).
See the usage documentation
(https://nbconvert.readthedocs.io/en/latest/usage.html#reveal-js-html-slideshow)
for more details.
Default: ''
Equivalent to: [--SlidesExporter.reveal_url_prefix]
--nbformat=<Enum>
The nbformat version to write.
Use this to downgrade notebooks.
Choices: any of [1, 2, 3, 4]
Default: 4
Equivalent to: [--NotebookExporter.nbformat_version]
Examples
--------
The simplest way to use nbconvert is
> jupyter nbconvert mynotebook.ipynb --to html
Options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'qtpdf', 'qtpng', 'rst', 'script', 'slides', 'webpdf'].
> jupyter nbconvert --to latex mynotebook.ipynb
Both HTML and LaTeX support multiple output templates. LaTeX includes
'base', 'article' and 'report'. HTML includes 'basic', 'lab' and
'classic'. You can specify the flavor of the format used.
> jupyter nbconvert --to html --template lab mynotebook.ipynb
You can also pipe the output to stdout, rather than a file
> jupyter nbconvert mynotebook.ipynb --stdout
PDF is generated via latex
> jupyter nbconvert mynotebook.ipynb --to pdf
You can get (and serve) a Reveal.js-powered slideshow
> jupyter nbconvert myslides.ipynb --to slides --post serve
Multiple notebooks can be given at the command line in a couple of
different ways:
> jupyter nbconvert notebook*.ipynb
> jupyter nbconvert notebook1.ipynb notebook2.ipynb
or you can specify the notebooks list in a config file, containing::
c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
> jupyter nbconvert --config mycfg.py
To see all available configurables, use `--help-all`.
[NbConvertApp] WARNING | pattern '0852036.ipynb' matched no files
In [5]:
!jupyter nbconvert 0852036.ipynb --to html
This application is used to convert notebook files (*.ipynb)
to various other formats.
WARNING: THE COMMANDLINE INTERFACE MAY CHANGE IN FUTURE RELEASES.
Options
=======
The options below are convenience aliases to configurable class-options,
as listed in the "Equivalent to" description-line of the aliases.
To see all configurable class-options for some <cmd>, use:
<cmd> --help-all
--debug
set log level to logging.DEBUG (maximize logging output)
Equivalent to: [--Application.log_level=10]
--show-config
Show the application's configuration (human-readable format)
Equivalent to: [--Application.show_config=True]
--show-config-json
Show the application's configuration (json format)
Equivalent to: [--Application.show_config_json=True]
--generate-config
generate default config file
Equivalent to: [--JupyterApp.generate_config=True]
-y
Answer yes to any questions instead of prompting.
Equivalent to: [--JupyterApp.answer_yes=True]
--execute
Execute the notebook prior to export.
Equivalent to: [--ExecutePreprocessor.enabled=True]
--allow-errors
Continue notebook execution even if one of the cells throws an error and include the error message in the cell output (the default behaviour is to abort conversion). This flag is only relevant if '--execute' was specified, too.
Equivalent to: [--ExecutePreprocessor.allow_errors=True]
--stdin
read a single notebook file from stdin. Write the resulting notebook with default basename 'notebook.*'
Equivalent to: [--NbConvertApp.from_stdin=True]
--stdout
Write notebook output to stdout instead of files.
Equivalent to: [--NbConvertApp.writer_class=StdoutWriter]
--inplace
Run nbconvert in place, overwriting the existing notebook (only
relevant when converting to notebook format)
Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory=]
--clear-output
Clear output of current file and save in place,
overwriting the existing notebook.
Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory= --ClearOutputPreprocessor.enabled=True]
--coalesce-streams
Coalesce consecutive stdout and stderr outputs into one stream (within each cell).
Equivalent to: [--NbConvertApp.use_output_suffix=False --NbConvertApp.export_format=notebook --FilesWriter.build_directory= --CoalesceStreamsPreprocessor.enabled=True]
--no-prompt
Exclude input and output prompts from converted document.
Equivalent to: [--TemplateExporter.exclude_input_prompt=True --TemplateExporter.exclude_output_prompt=True]
--no-input
Exclude input cells and output prompts from converted document.
This mode is ideal for generating code-free reports.
Equivalent to: [--TemplateExporter.exclude_output_prompt=True --TemplateExporter.exclude_input=True --TemplateExporter.exclude_input_prompt=True]
--allow-chromium-download
Whether to allow downloading chromium if no suitable version is found on the system.
Equivalent to: [--WebPDFExporter.allow_chromium_download=True]
--disable-chromium-sandbox
Disable chromium security sandbox when converting to PDF..
Equivalent to: [--WebPDFExporter.disable_sandbox=True]
--show-input
Shows code input. This flag is only useful for dejavu users.
Equivalent to: [--TemplateExporter.exclude_input=False]
--embed-images
Embed the images as base64 dataurls in the output. This flag is only useful for the HTML/WebPDF/Slides exports.
Equivalent to: [--HTMLExporter.embed_images=True]
--sanitize-html
Whether the HTML in Markdown cells and cell outputs should be sanitized..
Equivalent to: [--HTMLExporter.sanitize_html=True]
--log-level=<Enum>
Set the log level by value or name.
Choices: any of [0, 10, 20, 30, 40, 50, 'DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL']
Default: 30
Equivalent to: [--Application.log_level]
--config=<Unicode>
Full path of a config file.
Default: ''
Equivalent to: [--JupyterApp.config_file]
--to=<Unicode>
The export format to be used, either one of the built-in formats
['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'qtpdf', 'qtpng', 'rst', 'script', 'slides', 'webpdf']
or a dotted object name that represents the import path for an
``Exporter`` class
Default: ''
Equivalent to: [--NbConvertApp.export_format]
--template=<Unicode>
Name of the template to use
Default: ''
Equivalent to: [--TemplateExporter.template_name]
--template-file=<Unicode>
Name of the template file to use
Default: None
Equivalent to: [--TemplateExporter.template_file]
--theme=<Unicode>
Template specific theme(e.g. the name of a JupyterLab CSS theme distributed
as prebuilt extension for the lab template)
Default: 'light'
Equivalent to: [--HTMLExporter.theme]
--sanitize_html=<Bool>
Whether the HTML in Markdown cells and cell outputs should be sanitized.This
should be set to True by nbviewer or similar tools.
Default: False
Equivalent to: [--HTMLExporter.sanitize_html]
--writer=<DottedObjectName>
Writer class used to write the
results of the conversion
Default: 'FilesWriter'
Equivalent to: [--NbConvertApp.writer_class]
--post=<DottedOrNone>
PostProcessor class used to write the
results of the conversion
Default: ''
Equivalent to: [--NbConvertApp.postprocessor_class]
--output=<Unicode>
Overwrite base name use for output files.
Supports pattern replacements '{notebook_name}'.
Default: '{notebook_name}'
Equivalent to: [--NbConvertApp.output_base]
--output-dir=<Unicode>
Directory to write output(s) to. Defaults
to output to the directory of each notebook. To recover
previous default behaviour (outputting to the current
working directory) use . as the flag value.
Default: ''
Equivalent to: [--FilesWriter.build_directory]
--reveal-prefix=<Unicode>
The URL prefix for reveal.js (version 3.x).
This defaults to the reveal CDN, but can be any url pointing to a copy
of reveal.js.
For speaker notes to work, this must be a relative path to a local
copy of reveal.js: e.g., "reveal.js".
If a relative path is given, it must be a subdirectory of the
current directory (from which the server is run).
See the usage documentation
(https://nbconvert.readthedocs.io/en/latest/usage.html#reveal-js-html-slideshow)
for more details.
Default: ''
Equivalent to: [--SlidesExporter.reveal_url_prefix]
--nbformat=<Enum>
The nbformat version to write.
Use this to downgrade notebooks.
Choices: any of [1, 2, 3, 4]
Default: 4
Equivalent to: [--NotebookExporter.nbformat_version]
Examples
--------
The simplest way to use nbconvert is
> jupyter nbconvert mynotebook.ipynb --to html
Options include ['asciidoc', 'custom', 'html', 'latex', 'markdown', 'notebook', 'pdf', 'python', 'qtpdf', 'qtpng', 'rst', 'script', 'slides', 'webpdf'].
> jupyter nbconvert --to latex mynotebook.ipynb
Both HTML and LaTeX support multiple output templates. LaTeX includes
'base', 'article' and 'report'. HTML includes 'basic', 'lab' and
'classic'. You can specify the flavor of the format used.
> jupyter nbconvert --to html --template lab mynotebook.ipynb
You can also pipe the output to stdout, rather than a file
> jupyter nbconvert mynotebook.ipynb --stdout
PDF is generated via latex
> jupyter nbconvert mynotebook.ipynb --to pdf
You can get (and serve) a Reveal.js-powered slideshow
> jupyter nbconvert myslides.ipynb --to slides --post serve
Multiple notebooks can be given at the command line in a couple of
different ways:
> jupyter nbconvert notebook*.ipynb
> jupyter nbconvert notebook1.ipynb notebook2.ipynb
or you can specify the notebooks list in a config file, containing::
c.NbConvertApp.notebooks = ["my_notebook.ipynb"]
> jupyter nbconvert --config mycfg.py
To see all available configurables, use `--help-all`.
[NbConvertApp] WARNING | pattern '0852036.ipynb' matched no files
In [6]:
!jupyter nbconvert 0852036 --to html
[NbConvertApp] Converting notebook 0852036 to html [NbConvertApp] WARNING | Alternative text is missing on 20 image(s). [NbConvertApp] Writing 1237393 bytes to 085203.html
In [ ]: