Based on notes and examples from the following tutorial: ๐
ex:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import treeAfter installing Anaconda, run:
jupyter notebookโก๏ธ This will open Jupyter in your browser.
import pandas as pd
df = pd.read_csv('vgsales.csv')
df.shape # (rows, columns)df.describe()
df.values| Shortcut | Description |
|---|---|
| H | Show all shortcuts |
| Shift + Tab | Show function documentation |
| Ctrl + / | Comment/uncomment |
Predict music genre based on:
- Age
- Gender
import pandas as pd
music_data = pd.read_csv('music.csv')
music_data.head()Typical steps:
- Remove duplicates
- Handle missing values
- Fix inconsistencies
- Drop irrelevant data
X = music_data.drop(columns=['genre'])
y = music_data['genre']from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(X, y)predictions = model.predict([[21, 1], [22, 0]])
print(predictions)Expected Output:
['HipHop', 'Dance']
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)from sklearn.metrics import accuracy_score
model.fit(X_train, y_train)
predictions = model.predict(X_test)
score = accuracy_score(y_test, predictions)
print(score)import joblib
joblib.dump(model, 'music-recommender.joblib')model = joblib.load('music-recommender.joblib')
predictions = model.predict([[21, 1]])from sklearn import tree
tree.export_graphviz(
model,
out_file='music-recommender.dot',
feature_names=['age', 'gender'],
class_names=sorted(y.unique()),
label='all',
rounded=True,
filled=True
)- Install Graphviz
- Install VSCode extension: Dot / Graphviz
- Open
.dotfile - Click Preview
The model creates a decision tree showing:
- Splits based on age & gender
- Gini impurity
- Class prediction (HipHop, Jazz, Classical, etc.)
| Concept | Explanation |
|---|---|
| Features (X) | Input variables |
| Target (y) | Output variable |
| Train/Test Split | Prevent overfitting |
| Accuracy | Model performance metric |
| Model Persistence | Save trained models |
| Decision Tree | Interpretable ML model |
- ML is a step-by-step pipeline
- Data preparation is critical
- Simple models like Decision Trees are powerful
- Always evaluate using test data
- Save models to reuse in production
- Kaggle datasets: https://www.kaggle.com
- Tutorial video: https://youtu.be/7eh4d6sabA0
When explaining ML projects:
๐ Always structure like this:
Problem โ Data โ Model โ Evaluation โ Business Impact
Here is a clean, GitHub-ready explanation you can paste directly under your code:
This function exports a trained Decision Tree model into a .dot file, which can be visualized using Graphviz.
tree.export_graphviz(
model,
out_file='music-recommender.dot',
feature_names=['age', 'gender'],
class_names=sorted(y.unique()),
label='all',
rounded=True,
filled=True
)| Parameter | Description |
|---|---|
model |
The trained Decision Tree model that you want to visualize. |
out_file='music-recommender.dot' |
Output file where the tree structure is saved. This .dot file can be rendered using Graphviz. |
feature_names=['age', 'gender'] |
Names of input features used in the model. These appear in the tree nodes to make splits understandable. |
class_names=sorted(y.unique()) |
Names of target classes (labels). y.unique() gets all unique values, and sorted() ensures consistent ordering. |
label='all' |
Displays detailed information in each node (e.g., Gini index, samples, value). |
rounded=True |
Rounds the corners of the boxes in the tree for better visual appearance. |
filled=True |
Colors the nodes based on class prediction (helps quickly interpret the model). |
-
A
.dotfile describing the tree structure -
Each node shows:
- Split condition (e.g.,
age <= 30) - Gini impurity
- Number of samples
- Class distribution
- Predicted class
- Split condition (e.g.,
age <= 30.5
gini = 0.5
samples = 10
value = [5, 3, 2]
class = HipHop
- Install Graphviz
- Open
.dotfile in VSCode - Use Graphviz preview extension