Great! You've already connected to your SQL database and loaded the data into a pandas DataFrame. Now, let's proceed with the remaining steps. We'll work through each objective one by one, providing code and explanations.
Objective 2: Turn the problem into a binary classification problem
We need to categorize the 'Y house price of unit area' column into two categories to create a binary target variable. Let's define:
- Category 0: House price per unit area ≤ 40
- Category 1: House price per unit area > 40
Here's how you can do it:
# Categorize 'Y house price of unit area' into binary categories
df['Price_Category'] = df['Y house price of unit area'].apply(lambda x: 0 if x <= 40 else 1)
# Display the first few rows to verify
print(df[['Y house price of unit area', 'Price_Category']].head())
Check the class distribution:
# Count the occurrences of each class
class_counts = df['Price_Category'].value_counts()
print("Class distribution:")
print(class_counts)
Objective 3: Split the data into training and test sets
First, we need to separate the features (X) and the target variable (y).
# Define feature columns
feature_cols = [
'X1 transaction date', 'X2 house age', 'X3 distance to the nearest MRT station',
'X4 number of convenience stores', 'X5 latitude', 'X6 longitude'
]
# Features and target variable
X = df[feature_cols]
y = df['Price_Category']
Split the dataset:
from sklearn.model_selection import train_test_split
# Split the dataset into training (75%) and test sets (25%)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
The stratify=y parameter ensures that the class distribution is the same in both training and test sets.
Objective 4: Train a logistic regression and a decision tree classification model and evaluate
First, let's check if the class distribution is balanced.
# Check the class distribution in the training set
train_class_counts = y_train.value_counts()
print("Training set class distribution:")
print(train_class_counts)
If the distribution is imbalanced, accuracy might not be the best metric. Instead, we should focus on metrics like precision, recall, and F1-score.
Train the models:
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
# Initialize the models
logreg = LogisticRegression(random_state=42)
dtree = DecisionTreeClassifier(random_state=42)
# Train the Logistic Regression model
logreg.fit(X_train, y_train)
# Train the Decision Tree model
dtree.fit(X_train, y_train)
Objective 5: Evaluate your model against the test set
Make predictions on the test set:
# Predict using Logistic Regression
y_pred_logreg = logreg.predict(X_test)
# Predict using Decision Tree
y_pred_dtree = dtree.predict(X_test)
Evaluate the models:
from sklearn.metrics import classification_report, confusion_matrix
# Logistic Regression evaluation
print("Logistic Regression Classification Report:")
print(classification_report(y_test, y_pred_logreg))
print("Logistic Regression Confusion Matrix:")
print(confusion_matrix(y_test, y_pred_logreg))
# Decision Tree evaluation
print("Decision Tree Classification Report:")
print(classification_report(y_test, y_pred_dtree))
print("Decision Tree Confusion Matrix:")
print(confusion_matrix(y_test, y_pred_dtree))
Which evaluation measure should be used?
Given that the class distribution might be imbalanced, metrics such as precision, recall, and F1-score are more informative than accuracy. Also, using the ROC Curve and AUC (Area Under the Curve) provides a good measure of how well the model distinguishes between the two classes.
Objective 6: Create a ROC Curve comparing the two algorithms
Compute predicted probabilities:
from sklearn.metrics import roc_curve, auc
# Predicted probabilities for Logistic Regression
y_prob_logreg = logreg.predict_proba(X_test)[:, 1]
# Predicted probabilities for Decision Tree
y_prob_dtree = dtree.predict_proba(X_test)[:, 1]
Compute ROC curves and AUC scores:
# ROC curve and AUC for Logistic Regression
fpr_logreg, tpr_logreg, _ = roc_curve(y_test, y_prob_logreg)
roc_auc_logreg = auc(fpr_logreg, tpr_logreg)
# ROC curve and AUC for Decision Tree
fpr_dtree, tpr_dtree, _ = roc_curve(y_test, y_prob_dtree)
roc_auc_dtree = auc(fpr_dtree, tpr_dtree)
Plot the ROC curves:
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
plt.plot(fpr_logreg, tpr_logreg, color='blue',
label=f'Logistic Regression (AUC = {roc_auc_logreg:.2f})')
plt.plot(fpr_dtree, tpr_dtree, color='green',
label=f'Decision Tree (AUC = {roc_auc_dtree:.2f})')
plt.plot([0, 1], [0, 1], color='red', linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve Comparison')
plt.legend(loc='lower right')
plt.show()
Describe your observations:
- AUC Score: The Area Under the Curve (AUC) score indicates the ability of the model to distinguish between the two classes. A higher AUC value means better performance.
- ROC Curve Shape: The closer the ROC curve follows the left-hand border and then the top border of the ROC space, the better the model.
- By comparing the AUC scores and the ROC curves, you can determine which model performs better.
Example Observations:
- If the Logistic Regression model has an AUC of 0.85 and the Decision Tree model has an AUC of 0.80, then Logistic Regression performs better in distinguishing between the two classes.
- The ROC curves visually confirm that the Logistic Regression model has higher true positive rates at the same false positive rates compared to the Decision Tree model.
Complete Code
Here's the complete code combining all the steps:
import pandas as pd
import urllib
from sqlalchemy import create_engine
# Database connection parameters
server = 'MUNIBLAPTOP'
database = 'RealEstate'
driver = 'ODBC Driver 17 for SQL Server'
# Connection string
params = urllib.parse.quote_plus(
f'DRIVER={driver};SERVER={server};DATABASE={database};Trusted_Connection=yes'
)
# SQLAlchemy engine
engine = create_engine(f"mssql+pyodbc:///?odbc_connect={params}")
# SQL query to import data into pandas DataFrame
query = "SELECT * FROM RealEstateData"
df = pd.read_sql(query, engine)
# Objective 2: Binary classification
df['Price_Category'] = df['Y house price of unit area'].apply(lambda x: 0 if x <= 40 else 1)
# Objective 3: Split data
feature_cols = [
'X1 transaction date', 'X2 house age', 'X3 distance to the nearest MRT station',
'X4 number of convenience stores', 'X5 latitude', 'X6 longitude'
]
X = df[feature_cols]
y = df['Price_Category']
# Split the dataset
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
# Objective 4: Training models
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
logreg = LogisticRegression(random_state=42)
dtree = DecisionTreeClassifier(random_state=42)
logreg.fit(X_train, y_train)
dtree.fit(X_train, y_train)
# Objective 5: Evaluation
from sklearn.metrics import classification_report, confusion_matrix, roc_curve, auc
y_pred_logreg = logreg.predict(X_test)
y_pred_dtree = dtree.predict(X_test)
print("Logistic Regression Classification Report:")
print(classification_report(y_test, y_pred_logreg))
print("Decision Tree Classification Report:")
print(classification_report(y_test, y_pred_dtree))
# Objective 6: ROC Curve
y_prob_logreg = logreg.predict_proba(X_test)[:, 1]
y_prob_dtree = dtree.predict_proba(X_test)[:, 1]
fpr_logreg, tpr_logreg, _ = roc_curve(y_test, y_prob_logreg)
roc_auc_logreg = auc(fpr_logreg, tpr_logreg)
fpr_dtree, tpr_dtree, _ = roc_curve(y_test, y_prob_dtree)
roc_auc_dtree = auc(fpr_dtree, tpr_dtree)
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 6))
plt.plot(fpr_logreg, tpr_logreg, color='blue',
label=f'Logistic Regression (AUC = {roc_auc_logreg:.2f})')
plt.plot(fpr_dtree, tpr_dtree, color='green',
label=f'Decision Tree (AUC = {roc_auc_dtree:.2f})')
plt.plot([0, 1], [0, 1], color='red', linestyle='--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC Curve Comparison')
plt.legend(loc='lower right')
plt.show()
Remember to import all necessary libraries at the beginning of your notebook.
Conclusion
By following these steps, you've:
- Turned the problem into a binary classification problem by categorizing the target variable.
- Split the data into training and test sets while maintaining the class distribution.
- Trained two models: Logistic Regression and Decision Tree.
- Evaluated the models using appropriate metrics considering the class distribution.
- Plotted ROC curves to compare the models' performance.
Feel free to adjust the threshold or experiment with other classification algorithms to see if you can improve the model performance.