Loading
Loading
Despite its name, Logistic Regression is a classification algorithm. It's the foundation of all modern classification models.
Logistic Regression applies the sigmoid function to convert any number into a probability between 0 and 1:
Ï(z) = 1 / (1 + e^(-z))
If Ï(z) ⥠0.5 â Class 1; otherwise â Class 0.
| Application | Priority | Reason | |-------------|---------|--------| | Cancer detection | High Recall | Don't miss sick patients | | Spam filtering | High Precision | Don't delete important emails | | Fraud detection | Both | Both errors are costly |
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import (accuracy_score, precision_score,
recall_score, f1_score,
confusion_matrix, classification_report)
print("=" * 55)
print("Logistic Regression: ÙØŽÙ Ø§ÙØšØ±Ùد اÙÙ
زعج")
print("=" * 55)
# âââââââââââââââââââââââââââââââââââââââââ
# ØšÙØ§Ùات Ù
ØµØ·ÙØ¹Ø© ÙÙØšØ±Ùد Ø§ÙØ¥ÙÙØªØ±ÙÙÙ
# âââââââââââââââââââââââââââââââââââââââââ
np.random.seed(42)
n = 1000
# Ù
ÙØ²Ø§Øª تÙ
ÙÙØ² Ø§ÙØšØ±Ùد اÙÙ
زعج
has_free_word = np.random.binomial(1, 0.6, n) # ÙÙÙ
Ø© "Ù
جاÙÙ"
num_links = np.random.poisson(3, n) # عدد Ø§ÙØ±Ùاؚط
caps_ratio = np.random.beta(2, 5, n) # ÙØ³ØšØ© Ø§ÙØ£ØØ±Ù اÙÙØšÙرة
sender_known = np.random.binomial(1, 0.7, n) # اÙÙ
رس٠Ù
عرÙÙØ
email_length = np.random.normal(300, 150, n) # Ø·ÙÙ Ø§ÙØ±Ø³Ø§ÙØ©
# spam = Ø¯Ø§ÙØ© ÙÙÙ
ÙØ²Ø§Øª
spam_score = (1.5 * has_free_word + 0.3 * num_links
+ 2.0 * caps_ratio - 2.5 * sender_known
+ np.random.normal(0, 0.5, n))
is_spam = (spam_score > 0.2).astype(int)
print(f"ÙØ³ØšØ© Ø§ÙØšØ±Ùد اÙÙ
زعج: {is_spam.mean():.1%}")
df = pd.DataFrame({
"has_free_word": has_free_word,
"num_links": num_links,
"caps_ratio": caps_ratio,
"sender_known": sender_known,
"email_length": email_length,
"is_spam": is_spam
})
# âââââââââââââââââââââââââââââââââââââââââ
# ØªØØ¶Ùر ÙØªØ¯Ø±ÙØš
# âââââââââââââââââââââââââââââââââââââââââ
features = ["has_free_word", "num_links", "caps_ratio",
"sender_known", "email_length"]
X = df[features]
y = df["is_spam"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
scaler = StandardScaler()
X_train_s = scaler.fit_transform(X_train)
X_test_s = scaler.transform(X_test)
model = LogisticRegression(random_state=42)
model.fit(X_train_s, y_train)
# âââââââââââââââââââââââââââââââââââââââââ
# Ø§ÙØªÙÙÙÙ
اÙÙØ§Ù
Ù
# âââââââââââââââââââââââââââââââââââââââââ
y_pred = model.predict(X_test_s)
y_prob = model.predict_proba(X_test_s)[:, 1] # Ø§ØØªÙ
ا٠ÙÙÙÙ spam
print("\n" + "=" * 55)
print("ÙØªØ§ØŠØ¬ Ø§ÙØªÙÙÙÙ
:")
print(f" Accuracy = {accuracy_score(y_test, y_pred):.3f}")
print(f" Precision = {precision_score(y_test, y_pred):.3f}")
print(f" Recall = {recall_score(y_test, y_pred):.3f}")
print(f" F1 Score = {f1_score(y_test, y_pred):.3f}")
print("\nConfusion Matrix:")
cm = confusion_matrix(y_test, y_pred)
print(f" TN={cm[0,0]} FP={cm[0,1]}")
print(f" FN={cm[1,0]} TP={cm[1,1]}")
print("\nØªÙØ±Ùر Ù
ÙØµÙ:")
print(classification_report(y_test, y_pred,
target_names=["ØÙÙÙÙ", "Ù
زعج"]))
# âââââââââââââââââââââââââââââââââââââââââ
# Ø£ÙÙ
ÙØ© اÙÙ
ÙØ²Ø§Øª
# âââââââââââââââââââââââââââââââââââââââââ
coef_df = pd.DataFrame({
"feature": features,
"coefficient": model.coef_[0]
}).sort_values("coefficient", ascending=False)
print("Ø£ÙÙ
ÙØ© اÙÙ
ÙØ²Ø§Øª:")
for _, row in coef_df.iterrows():
bar = "â" * int(abs(row["coefficient"]) * 5)
sign = "+" if row["coefficient"] > 0 else "-"
print(f" {row['feature']:15s}: {sign}{abs(row['coefficient']):.2f} {bar}")