File size: 5,582 Bytes
47f1575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 🌸 TP-3 : Classification Iris — Introduction au ML\n",
    "\n",
    "**Objectif** : Classifier les iris en 3 espèces à partir de 4 features.\n",
    "\n",
    "**Dataset** : [Iris Flower Dataset](https://www.kaggle.com/datasets/uciml/iris)\n",
    "\n",
    "**Compétences** :\n",
    "- Classification multi-classe\n",
    "- Visualisation avec PCA\n",
    "- Frontières de décision\n",
    "- Comparaison d'algorithmes"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split, cross_val_score\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from sklearn.svm import SVC\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n",
    "\n",
    "sns.set_style('whitegrid')\n",
    "print(\"✅ Bibliothèques importées !\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Chargement des données\n",
    "iris = load_iris()\n",
    "X = iris.data\n",
    "y = iris.target\n",
    "feature_names = iris.feature_names\n",
    "target_names = iris.target_names\n",
    "\n",
    "# Création d'un DataFrame\n",
    "df = pd.DataFrame(X, columns=feature_names)\n",
    "df['species'] = [target_names[i] for i in y]\n",
    "\n",
    "print(f\"📊 Dimensions : {df.shape}\")\n",
    "print(f\"\\n🌸 Espèces : {target_names}\")\n",
    "df.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pairplot pour visualiser les relations\n",
    "sns.pairplot(df, hue='species', palette='viridis', height=2.5)\n",
    "plt.suptitle('Pairplot du dataset Iris', y=1.02, fontsize=14)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Split et normalisation\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X, y, test_size=0.2, random_state=42, stratify=y\n",
    ")\n",
    "\n",
    "scaler = StandardScaler()\n",
    "X_train_scaled = scaler.fit_transform(X_train)\n",
    "X_test_scaled = scaler.transform(X_test)\n",
    "\n",
    "print(f\"Train : {X_train.shape[0]} échantillons\")\n",
    "print(f\"Test : {X_test.shape[0]} échantillons\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Comparaison des modèles\n",
    "models = {\n",
    "    'KNN': KNeighborsClassifier(n_neighbors=5),\n",
    "    'SVM': SVC(kernel='rbf', random_state=42),\n",
    "    'Decision Tree': DecisionTreeClassifier(random_state=42),\n",
    "    'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42)\n",
    "}\n",
    "\n",
    "results = {}\n",
    "for name, model in models.items():\n",
    "    model.fit(X_train_scaled, y_train)\n",
    "    y_pred = model.predict(X_test_scaled)\n",
    "    accuracy = accuracy_score(y_test, y_pred)\n",
    "    results[name] = accuracy\n",
    "    print(f\"{name:15} : {accuracy:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Visualisation avec PCA (2D)\n",
    "pca = PCA(n_components=2)\n",
    "X_pca = pca.fit_transform(X_scaled := StandardScaler().fit_transform(X))\n",
    "\n",
    "plt.figure(figsize=(10, 6))\n",
    "colors = ['red', 'green', 'blue']\n",
    "for i, target_name in enumerate(target_names):\n",
    "    plt.scatter(X_pca[y == i, 0], X_pca[y == i, 1], \n",
    "               c=colors[i], label=target_name, alpha=0.7, s=50)\n",
    "plt.xlabel(f'PC1 ({pca.explained_variance_ratio_[0]:.2%})')\n",
    "plt.ylabel(f'PC2 ({pca.explained_variance_ratio_[1]:.2%})')\n",
    "plt.title('Dataset Iris - Projection PCA')\n",
    "plt.legend()\n",
    "plt.show()\n",
    "\n",
    "print(f\"Variance expliquée : {pca.explained_variance_ratio_.sum():.2%}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Matrice de confusion pour le meilleur modèle\n",
    "best_model = SVC(kernel='rbf', random_state=42)\n",
    "best_model.fit(X_train_scaled, y_train)\n",
    "y_pred = best_model.predict(X_test_scaled)\n",
    "\n",
    "cm = confusion_matrix(y_test, y_pred)\n",
    "\n",
    "plt.figure(figsize=(8, 6))\n",
    "sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',\n",
    "            xticklabels=target_names, yticklabels=target_names)\n",
    "plt.title('Matrice de confusion - SVM')\n",
    "plt.ylabel('Vrai label')\n",
    "plt.xlabel('Prédiction')\n",
    "plt.show()\n",
    "\n",
    "print(classification_report(y_test, y_pred, target_names=target_names))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.8.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}