import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
df = pd.read_csv("weather.csv")
X_features = df.drop("Play", axis=1)
y_target = df["Play"]
Machine-learning algorithms generally need numerical representations for the features.
So we need to convert:
into numerical columns.
We will use a built-in pandas function called: pd.get_dummies()
X_encoded = pd.get_dummies(X_features)
X_encoded
### This process is called one-hot encoding.
What happened to Windy? Windy contains:
model = DecisionTreeClassifier(
criterion="gini",
random_state=42 ## The important point is that we use a fixed value so that we can reproduce the same result.
)
CART classification trees commonly use Gini impurity to select splits.
So the model will use Gini impurity when deciding how to split the data.
model.fit(X_encoded, y_target)
new_data = pd.DataFrame([{
"Outlook": "Sunny",
"Temperature": "Cool",
"Humidity": "High",
"Windy": False
}])
Remember, our model was trained using:
X_encoded
Therefore, the new data must have the same feature columns.
new_data_encoded = pd.get_dummies(new_data)
new_data_encoded = new_data_encoded.reindex(
columns=X_encoded.columns,
fill_value=0
)
prediction = model.predict(new_data_encoded)
print("Prediction:", prediction[0])
plt.figure(figsize=(18, 10))
plot_tree(
model,
feature_names=X_encoded.columns,
class_names=model.classes_,
filled=True,
fontsize=14
)
plt.show()
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import plot_tree
# 1. Load dataset
df = pd.read_csv("weather.csv")
print("Dataset:")
print(df)
# 2. Separate features and target
X = df.drop("Play", axis=1)
y = df["Play"]
# 3. Convert categorical data into numbers
X_encoded = pd.get_dummies(X)
print("\nEncoded Features:")
print(X_encoded)
# 4. Create CART decision tree
model = DecisionTreeClassifier(
criterion="gini",
random_state=42
)
# 5. Train the model
model.fit(X_encoded, y)
# 6. Display tree information
print("\nTree Depth:", model.get_depth())
print("Number of Leaves:", model.get_n_leaves())
# 7. New data
new_data = pd.DataFrame([{
"Outlook": "Sunny",
"Temperature": "Cool",
"Humidity": "High",
"Windy": False
}])
# 8. Encode new data
new_data_encoded = pd.get_dummies(new_data)
new_data_encoded = new_data_encoded.reindex(
columns=X_encoded.columns,
fill_value=0
)
# 9. Prediction
prediction = model.predict(new_data_encoded)
print("\nPrediction:", prediction[0])
# 10. Prediction probability
probability = model.predict_proba(new_data_encoded)
print("Probability:", probability)
# 11. Visualize tree
plt.figure(figsize=(18, 10))
plot_tree(
model,
feature_names=X_encoded.columns,
class_names=model.classes_,
filled=True,
fontsize=14
)
plt.show()