Python Decision Tree for Weather Classification – Beginner Guide

Beginner Friendly Guide | From Zero to Results

1. Basic Python Words You Need to Know

Word Meaning Simple Explanation
pandas Data Library Like Excel inside Python. Used to open and work with tables.
pd Nickname for pandas Short name so we don’t type “pandas” every time.
df DataFrame Your table / spreadsheet in Python.
read_csv() Open CSV file Loads your city-weather.csv file.

2. Complete Code (Copy-Paste in Jupyter)

import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import confusion_matrix, accuracy_score
import seaborn as sns
import matplotlib.pyplot as plt

# Load data
df = pd.read_csv('city-weather.csv')

# Prepare data
data = df.copy()
le = LabelEncoder()
data['city_name'] = le.fit_transform(data['city_name'])
data['weather_category'] = le.fit_transform(data['weather_category'])

# Features and Target
X = data.drop(['weather_category', 'date'], axis=1)
y = data['weather_category']

# Split and Train
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

model = DecisionTreeClassifier(criterion='entropy', max_depth=6, random_state=42)
model.fit(X_train, y_train)

y_pred = model.predict(X_test)

print("Accuracy:", round(accuracy_score(y_test, y_pred)*100, 2), "%")
print("Confusion Matrix:")
print(confusion_matrix(y_test, y_pred))

3. What is a Decision Tree?

A Decision Tree is like a game of 20 Questions. The computer asks yes/no questions about temperature, humidity, wind, etc., and finally predicts the weather category.

4. Results Meaning

  • Accuracy: How many predictions were correct (e.g., 85% = very good for this kind of data).
  • Confusion Matrix: Shows how many times the model was right or wrong for each weather type.

Tip: Run the code step by step in Jupyter Notebook. Start small and understand each part.

Done with KNIME, Excel, SQL, PowerBI — now learning Python too! Great job! 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top