noshot 1.0.0__py3-none-any.whl → 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. noshot/data/ML TS XAI/ML/Main/1. EDA-PCA (Balance Scale Dataset).ipynb +139 -0
  2. noshot/data/ML TS XAI/ML/Main/1. EDA-PCA (Rice Dataset).ipynb +181 -0
  3. noshot/data/ML TS XAI/ML/Main/10. HMM Veterbi.ipynb +228 -0
  4. noshot/data/ML TS XAI/ML/Main/2. KNN (Balance Scale Dataset).ipynb +117 -0
  5. noshot/data/ML TS XAI/ML/Main/2. KNN (Iris Dataset).ipynb +165 -0
  6. noshot/data/ML TS XAI/ML/Main/2. KNN (Sobar-72 Dataset).ipynb +251 -0
  7. noshot/data/ML TS XAI/ML/Main/3. LDA (Balance Scale Dataset).ipynb +78 -0
  8. noshot/data/ML TS XAI/ML/Main/3. LDA (NPHA Doctor Visits Dataset).ipynb +114 -0
  9. noshot/data/ML TS XAI/ML/Main/4. Linear Regression (Machine Dataset).ipynb +115 -0
  10. noshot/data/ML TS XAI/ML/Main/4. Linear Regression (Real Estate Dataset).ipynb +159 -0
  11. noshot/data/ML TS XAI/{XAI/XAI 2/Exp-3 (EDA-loan).ipynb → ML/Main/5. Logistic Regression (Magic04 Dataset).ipynb } +53 -74
  12. noshot/data/ML TS XAI/ML/Main/5. Logistic Regression (Wine Dataset).ipynb +112 -0
  13. noshot/data/ML TS XAI/ML/Main/6. Naive Bayes Classifier (Agaricus Lepiota Dataset).ipynb +153 -0
  14. noshot/data/ML TS XAI/ML/Main/6. Naive Bayes Classifier (Wine Dataset).ipynb +89 -0
  15. noshot/data/ML TS XAI/ML/Main/7. SVM (Rice Dataset).ipynb +208 -0
  16. noshot/data/ML TS XAI/ML/Main/8. FeedForward NN (Sobar72 Dataset).ipynb +260 -0
  17. noshot/data/ML TS XAI/ML/Main/9. CNN (Cifar10 Dataset).ipynb +238 -0
  18. noshot/data/ML TS XAI/ML/Main/data/agaricus-lepiota.data +8124 -0
  19. noshot/data/ML TS XAI/ML/Main/data/balance-scale.txt +625 -0
  20. noshot/data/ML TS XAI/ML/Main/data/doctor-visits.csv +715 -0
  21. noshot/data/ML TS XAI/ML/Main/data/iris.csv +151 -0
  22. noshot/data/ML TS XAI/ML/Main/data/machine-data.csv +210 -0
  23. noshot/data/ML TS XAI/ML/Main/data/magic04.data +19020 -0
  24. noshot/data/ML TS XAI/ML/Main/data/real-estate.xlsx +0 -0
  25. noshot/data/ML TS XAI/ML/Main/data/rice.arff +3826 -0
  26. noshot/data/ML TS XAI/ML/Main/data/sobar-72.csv +73 -0
  27. noshot/data/ML TS XAI/ML/Main/data/wine-dataset.csv +179 -0
  28. noshot/data/ML TS XAI/ML/Other Codes.ipynb +158 -0
  29. noshot/data/ML TS XAI/ML/Rolls Royce AllinOne.ipynb +691 -0
  30. {noshot-1.0.0.dist-info → noshot-3.0.0.dist-info}/METADATA +1 -1
  31. noshot-3.0.0.dist-info/RECORD +38 -0
  32. {noshot-1.0.0.dist-info → noshot-3.0.0.dist-info}/WHEEL +1 -1
  33. noshot/data/ML TS XAI/TS/10. Seasonal ARIMA Forecasting.ipynb +0 -246
  34. noshot/data/ML TS XAI/TS/11. Multivariate ARIMA Forecasting.ipynb +0 -228
  35. noshot/data/ML TS XAI/TS/6. ACF PACF.ipynb +0 -77
  36. noshot/data/ML TS XAI/TS/7. Differencing.ipynb +0 -167
  37. noshot/data/ML TS XAI/TS/8. ARMA Forecasting.ipynb +0 -197
  38. noshot/data/ML TS XAI/TS/9. ARIMA Forecasting.ipynb +0 -220
  39. noshot/data/ML TS XAI/XAI/XAI 1/EDA2_chipsdatset.ipynb +0 -633
  40. noshot/data/ML TS XAI/XAI/XAI 1/EDA_IRISH_8thjan.ipynb +0 -326
  41. noshot/data/ML TS XAI/XAI/XAI 1/XAI_EX1 MODEL BIAS (FINAL).ipynb +0 -487
  42. noshot/data/ML TS XAI/XAI/XAI 1/complete_guide_to_eda_on_text_data.ipynb +0 -845
  43. noshot/data/ML TS XAI/XAI/XAI 1/deepchecksframeworks.ipynb +0 -100
  44. noshot/data/ML TS XAI/XAI/XAI 1/deepexplainers (mnist).ipynb +0 -90
  45. noshot/data/ML TS XAI/XAI/XAI 1/guidedbackpropagation.ipynb +0 -203
  46. noshot/data/ML TS XAI/XAI/XAI 1/updated_image_EDA1_with_LRP.ipynb +0 -3998
  47. noshot/data/ML TS XAI/XAI/XAI 1/zebrastripes.ipynb +0 -271
  48. noshot/data/ML TS XAI/XAI/XAI 2/EXP_5.ipynb +0 -1545
  49. noshot/data/ML TS XAI/XAI/XAI 2/Exp-3 (EDA-movie).ipynb +0 -229
  50. noshot/data/ML TS XAI/XAI/XAI 2/Exp-4(Flower dataset).ipynb +0 -237
  51. noshot/data/ML TS XAI/XAI/XAI 2/Exp-4.ipynb +0 -241
  52. noshot/data/ML TS XAI/XAI/XAI 2/Exp_2.ipynb +0 -352
  53. noshot/data/ML TS XAI/XAI/XAI 2/Exp_7.ipynb +0 -110
  54. noshot/data/ML TS XAI/XAI/XAI 2/FeatureImportance_SensitivityAnalysis.ipynb +0 -708
  55. noshot-1.0.0.dist-info/RECORD +0 -32
  56. {noshot-1.0.0.dist-info → noshot-3.0.0.dist-info}/licenses/LICENSE.txt +0 -0
  57. {noshot-1.0.0.dist-info → noshot-3.0.0.dist-info}/top_level.txt +0 -0
@@ -1,487 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": null,
6
- "id": "9b1b1eea",
7
- "metadata": {
8
- "id": "68d8b49b",
9
- "outputId": "e3f005bc-713f-4dad-9714-d981f49af033"
10
- },
11
- "outputs": [],
12
- "source": [
13
- "//imbalanced Data data set\n",
14
- "import matplotlib.pyplot as plt\n",
15
- "from sklearn.datasets import make_classification\n",
16
- "from imblearn.over_sampling import SMOTE\n",
17
- "from collections import Counter\n",
18
- "from sklearn.naive_bayes import GaussianNB # Importing Naive Bayes\n",
19
- "from sklearn.model_selection import train_test_split\n",
20
- "from sklearn.metrics import classification_report, confusion_matrix, ConfusionMatrixDisplay\n",
21
- "import seaborn as sns\n",
22
- "\n",
23
- "# Generate imbalanced dataset , Synthetic Minority Over-sampling Technique\n",
24
- "X, y = make_classification(n_samples=1000, n_features=10, n_classes=2,\n",
25
- " class_sep=2, weights=[0.9, 0.1], random_state=42)\n",
26
- "\n",
27
- "# Display class distribution\n",
28
- "print(\"Original class distribution:\", Counter(y))\n",
29
- "\n",
30
- "# Plot the class distribution\n",
31
- "plt.figure(figsize=(6,4))\n",
32
- "plt.bar(['Class 0', 'Class 1'], [Counter(y)[0], Counter(y)[1]], color=['blue', 'orange'])\n",
33
- "plt.title('Original Class Distribution')\n",
34
- "plt.ylabel('Frequency')\n",
35
- "plt.show()\n",
36
- "\n",
37
- "# Apply SMOTE (Synthetic Minority Over-sampling Technique) for oversampling\n",
38
- "smote = SMOTE(random_state=42)\n",
39
- "X_res, y_res = smote.fit_resample(X, y)\n",
40
- "\n",
41
- "# Display new class distribution\n",
42
- "print(\"Resampled class distribution:\", Counter(y_res))\n",
43
- "\n",
44
- "# Plot the resampled class distribution\n",
45
- "plt.figure(figsize=(6,4))\n",
46
- "plt.bar(['Class 0', 'Class 1'], [Counter(y_res)[0], Counter(y_res)[1]], color=['blue', 'orange'])\n",
47
- "plt.title('Resampled Class Distribution (SMOTE)')\n",
48
- "plt.ylabel('Frequency')\n",
49
- "plt.show()\n",
50
- "\n",
51
- "# Train and evaluate a Naive Bayes classifier on the resampled data\n",
52
- "X_train, X_test, y_train, y_test = train_test_split(X_res, y_res, test_size=0.3, random_state=42)\n",
53
- "\n",
54
- "# Using Naive Bayes Classifier\n",
55
- "clf = GaussianNB()\n",
56
- "clf.fit(X_train, y_train)\n",
57
- "y_pred_resampled = clf.predict(X_test)\n",
58
- "\n",
59
- "# Evaluate the model on the resampled dataset\n",
60
- "print(\"Classification report on resampled data:\")\n",
61
- "print(classification_report(y_test, y_pred_resampled))\n",
62
- "\n",
63
- "# Confusion Matrix for resampled data\n",
64
- "cm_resampled = confusion_matrix(y_test, y_pred_resampled)\n",
65
- "disp = ConfusionMatrixDisplay(confusion_matrix=cm_resampled, display_labels=['Class 0', 'Class 1'])\n",
66
- "disp.plot(cmap='Blues')\n",
67
- "plt.title(\"Confusion Matrix - Resampled Data\")\n",
68
- "plt.show()\n",
69
- "\n",
70
- "# Now, evaluate the model on the original imbalanced data\n",
71
- "X_train_imbalanced, X_test_imbalanced, y_train_imbalanced, y_test_imbalanced = train_test_split(X, y, test_size=0.3, random_state=42)\n",
72
- "\n",
73
- "# Train the Naive Bayes Classifier on imbalanced data\n",
74
- "clf.fit(X_train_imbalanced, y_train_imbalanced)\n",
75
- "y_pred_imbalanced = clf.predict(X_test_imbalanced)\n",
76
- "\n",
77
- "# Evaluate the model on the original imbalanced dataset\n",
78
- "print(\"Classification report on imbalanced data:\")\n",
79
- "print(classification_report(y_test_imbalanced, y_pred_imbalanced))\n",
80
- "\n",
81
- "# Confusion Matrix for imbalanced data\n",
82
- "cm_imbalanced = confusion_matrix(y_test_imbalanced, y_pred_imbalanced)\n",
83
- "disp_imbalanced = ConfusionMatrixDisplay(confusion_matrix=cm_imbalanced, display_labels=['Class 0', 'Class 1'])\n",
84
- "disp_imbalanced.plot(cmap='Blues')\n",
85
- "plt.title(\"Confusion Matrix - Imbalanced Data\")\n",
86
- "plt.show()\n",
87
- "\n",
88
- "# You can compare metrics like precision, recall, and F1-score to see how much improvement SMOTE brings\n"
89
- ]
90
- },
91
- {
92
- "cell_type": "code",
93
- "execution_count": null,
94
- "id": "8fbfd688",
95
- "metadata": {
96
- "colab": {
97
- "base_uri": "https://localhost:8080/",
98
- "height": 564
99
- },
100
- "id": "yNchFpnR3EBH",
101
- "outputId": "b8484e77-c0f0-4626-bc0f-c9e17fe6b51f"
102
- },
103
- "outputs": [],
104
- "source": [
105
- "import numpy as np\n",
106
- "import matplotlib.pyplot as plt\n",
107
- "from sklearn.linear_model import LinearRegression\n",
108
- "from sklearn.model_selection import train_test_split\n",
109
- "\n",
110
- "# Generate data with a linear relationship (y = 2X + 1)\n",
111
- "np.random.seed(42)\n",
112
- "X = np.linspace(0, 10, 100)\n",
113
- "y = 2 * X + 1 # True underlying function\n",
114
- "\n",
115
- "# Add some noise to the data\n",
116
- "noise = np.random.normal(0, 2, X.shape)\n",
117
- "y_noisy = y + noise\n",
118
- "\n",
119
- "# Introduce outliers\n",
120
- "X_outliers = np.array([2, 4, 6, 8])\n",
121
- "y_outliers = np.array([25, 30, 28, 35]) # Outliers with large values\n",
122
- "X_combined = np.concatenate((X, X_outliers))\n",
123
- "y_combined = np.concatenate((y_noisy, y_outliers))\n",
124
- "\n",
125
- "# Split the data into training and test sets\n",
126
- "X_train, X_test, y_train, y_test = train_test_split(X_combined, y_combined, test_size=0.2, random_state=42)\n",
127
- "\n",
128
- "# Reshape data to fit into linear regression model\n",
129
- "X_train = X_train.reshape(-1, 1)\n",
130
- "X_test = X_test.reshape(-1, 1)\n",
131
- "\n",
132
- "# Fit the linear regression model\n",
133
- "model = LinearRegression()\n",
134
- "model.fit(X_train, y_train)\n",
135
- "\n",
136
- "# Predict on both training and testing data\n",
137
- "y_train_pred = model.predict(X_train)\n",
138
- "y_test_pred = model.predict(X_test)\n",
139
- "\n",
140
- "# Plot the results\n",
141
- "plt.figure(figsize=(10, 6))\n",
142
- "plt.scatter(X_train, y_train, color='blue', label='Training data')\n",
143
- "plt.scatter(X_test, y_test, color='green', label='Test data')\n",
144
- "plt.plot(X_train, y_train_pred, color='red', label='Fitted line (with outliers)')\n",
145
- "plt.plot(X, y, color='black', label='True line (y = 2X + 1)', linestyle='--')\n",
146
- "plt.legend()\n",
147
- "plt.xlabel('X')\n",
148
- "plt.ylabel('y')\n",
149
- "plt.title('Linear Regression with Outliers')\n",
150
- "plt.show()\n"
151
- ]
152
- },
153
- {
154
- "cell_type": "markdown",
155
- "id": "f22d745d",
156
- "metadata": {
157
- "id": "u0VEh-1S4GyO"
158
- },
159
- "source": [
160
- "The blue dots represent the training data, which includes both the normal data and the outliers.\n",
161
- "The green dots represent the test data.\n",
162
- "The red line is the fitted line from the linear regression model. Notice how it is significantly influenced by the outliers, pulling the line away from the true underlying relationship (the black dashed line).\n",
163
- "The black dashed line is the true relationship y = 2X + 1."
164
- ]
165
- },
166
- {
167
- "cell_type": "code",
168
- "execution_count": null,
169
- "id": "2efa5ff9",
170
- "metadata": {
171
- "colab": {
172
- "base_uri": "https://localhost:8080/",
173
- "height": 585
174
- },
175
- "id": "44a87f9d",
176
- "outputId": "b89d8054-ee86-4a7f-cf38-a4489bcae2e7"
177
- },
178
- "outputs": [],
179
- "source": [
180
- "import numpy as np\n",
181
- "import matplotlib.pyplot as plt\n",
182
- "from sklearn.naive_bayes import GaussianNB\n",
183
- "from sklearn.model_selection import train_test_split\n",
184
- "from sklearn.metrics import accuracy_score\n",
185
- "\n",
186
- "# Step 1: Generate synthetic data (2 features, binary target)\n",
187
- "np.random.seed(42)\n",
188
- "\n",
189
- "# Create 100 samples with two features\n",
190
- "X = np.random.randn(100, 2)\n",
191
- "\n",
192
- "# Assign labels: 0 for class 0, 1 for class 1\n",
193
- "y = (X[:, 0] + X[:, 1] > 0).astype(int)\n",
194
- "\n",
195
- "# Step 2: Introduce noise in the data (adding random noise)\n",
196
- "X_noisy = X + np.random.normal(0, 1, X.shape) # Adding noise with mean 0 and std 1\n",
197
- "\n",
198
- "# Step 3: Split the data into training and test sets\n",
199
- "X_train, X_test, y_train, y_test = train_test_split(X_noisy, y, test_size=0.3, random_state=42)\n",
200
- "\n",
201
- "# Step 4: Apply Naive Bayes classifier\n",
202
- "model = GaussianNB()\n",
203
- "model.fit(X_train, y_train)\n",
204
- "\n",
205
- "# Step 5: Make predictions\n",
206
- "y_pred = model.predict(X_test)\n",
207
- "\n",
208
- "# Step 6: Evaluate performance\n",
209
- "accuracy = accuracy_score(y_test, y_pred)\n",
210
- "\n",
211
- "# Step 7: Visualize the noisy data and decision boundary\n",
212
- "plt.figure(figsize=(8, 6))\n",
213
- "plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap='coolwarm', marker='o', label='Train data')\n",
214
- "plt.scatter(X_test[:, 0], X_test[:, 1], c=y_test, cmap='coolwarm', marker='x', label='Test data')\n",
215
- "\n",
216
- "# Plot decision boundary\n",
217
- "x_min, x_max = X_noisy[:, 0].min() - 1, X_noisy[:, 0].max() + 1\n",
218
- "y_min, y_max = X_noisy[:, 1].min() - 1, X_noisy[:, 1].max() + 1\n",
219
- "xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))\n",
220
- "Z = model.predict(np.c_[xx.ravel(), yy.ravel()])\n",
221
- "Z = Z.reshape(xx.shape)\n",
222
- "\n",
223
- "plt.contourf(xx, yy, Z, alpha=0.3)\n",
224
- "plt.title(f'Naive Bayes Classifier with Noisy Data\\nAccuracy: {accuracy:.2f}')\n",
225
- "plt.xlabel('Feature 1')\n",
226
- "plt.ylabel('Feature 2')\n",
227
- "plt.legend()\n",
228
- "plt.show()\n"
229
- ]
230
- },
231
- {
232
- "cell_type": "code",
233
- "execution_count": null,
234
- "id": "f68e2206",
235
- "metadata": {
236
- "colab": {
237
- "base_uri": "https://localhost:8080/",
238
- "height": 503
239
- },
240
- "id": "55dcbd50",
241
- "outputId": "31a071d1-6f09-4aed-cc5c-12d8e638eb92",
242
- "scrolled": true
243
- },
244
- "outputs": [],
245
- "source": [
246
- "import numpy as np\n",
247
- "import matplotlib.pyplot as plt\n",
248
- "from sklearn.linear_model import LogisticRegression\n",
249
- "from sklearn.metrics import accuracy_score, log_loss\n",
250
- "from scipy.stats import entropy\n",
251
- "\n",
252
- "# Step 1: Generate synthetic data (initial dataset)\n",
253
- "np.random.seed(42)\n",
254
- "n_samples = 500\n",
255
- "X1 = np.random.normal(0, 1, n_samples) # Feature 1\n",
256
- "X2 = np.random.normal(0, 1, n_samples) # Feature 2\n",
257
- "X = np.column_stack((X1, X2))\n",
258
- "y = (X1 + X2 > 0).astype(int) # Binary target\n",
259
- "\n",
260
- "# Step 2: Fit logistic regression on the initial data\n",
261
- "model = LogisticRegression()\n",
262
- "model.fit(X, y)\n",
263
- "\n",
264
- "# Step 3: Simulate drift (change the distribution of features)\n",
265
- "X1_drifted = np.random.normal(1, 1, n_samples) # Shift mean from 0 to 1\n",
266
- "X2_drifted = np.random.normal(1, 1, n_samples) # Shift mean from 0 to 1\n",
267
- "X_drifted = np.column_stack((X1_drifted, X2_drifted))\n",
268
- "y_drifted = (X1_drifted + X2_drifted > 0).astype(int) # New labels based on drifted data\n",
269
- "\n",
270
- "# Step 4: Detect drift using KL divergence\n",
271
- "def kl_divergence(p, q, bins=10):\n",
272
- " \"\"\"Calculate KL divergence between two distributions.\"\"\"\n",
273
- " p_hist, _ = np.histogram(p, bins=bins, density=True)\n",
274
- " q_hist, _ = np.histogram(q, bins=bins, density=True)\n",
275
- " p_hist += 1e-10 # Avoid division by zero\n",
276
- " q_hist += 1e-10\n",
277
- " return entropy(p_hist, q_hist)\n",
278
- "\n",
279
- "# Calculate KL divergence for each feature\n",
280
- "kl_X1 = kl_divergence(X1, X1_drifted)\n",
281
- "kl_X2 = kl_divergence(X2, X2_drifted)\n",
282
- "\n",
283
- "# Step 5: Evaluate model performance on drifted data\n",
284
- "y_pred_drifted = model.predict(X_drifted)\n",
285
- "accuracy_drifted = accuracy_score(y_drifted, y_pred_drifted)\n",
286
- "log_loss_drifted = log_loss(y_drifted, model.predict_proba(X_drifted))\n",
287
- "\n",
288
- "# Step 6: Visualization\n",
289
- "plt.figure(figsize=(12, 5))\n",
290
- "\n",
291
- "# Plot original and drifted distributions\n",
292
- "plt.subplot(1, 2, 1)\n",
293
- "plt.hist(X1, bins=20, alpha=0.6, label=\"Feature 1 (original)\", color=\"blue\")\n",
294
- "plt.hist(X1_drifted, bins=20, alpha=0.6, label=\"Feature 1 (drifted)\", color=\"orange\")\n",
295
- "plt.title(f\"KL Divergence for Feature 1: {kl_X1:.4f}\")\n",
296
- "plt.legend()\n",
297
- "\n",
298
- "plt.subplot(1, 2, 2)\n",
299
- "plt.hist(X2, bins=20, alpha=0.6, label=\"Feature 2 (original)\", color=\"blue\")\n",
300
- "plt.hist(X2_drifted, bins=20, alpha=0.6, label=\"Feature 2 (drifted)\", color=\"orange\")\n",
301
- "plt.title(f\"KL Divergence for Feature 2: {kl_X2:.4f}\")\n",
302
- "plt.legend()\n",
303
- "\n",
304
- "plt.show()\n",
305
- "\n",
306
- "# Step 7: Print performance metrics\n",
307
- "print(f\"Model accuracy on drifted data: {accuracy_drifted:.4f}\")\n",
308
- "print(f\"Log loss on drifted data: {log_loss_drifted:.4f}\")\n"
309
- ]
310
- },
311
- {
312
- "cell_type": "code",
313
- "execution_count": null,
314
- "id": "6e8bdb48",
315
- "metadata": {},
316
- "outputs": [],
317
- "source": [
318
- "import pandas as pd\n",
319
- "import numpy as np\n",
320
- "from sklearn.model_selection import train_test_split\n",
321
- "from sklearn.linear_model import LogisticRegression\n",
322
- "from sklearn.metrics import classification_report\n",
323
- "\n",
324
- "# Simulated dataset\n",
325
- "data = pd.DataFrame({\n",
326
- " 'Income': [30000, 45000, 60000, 80000, 20000, 50000],\n",
327
- " 'CreditScore': [600, 650, 700, 750, 550, 680],\n",
328
- " 'Gender': [0, 1, 0, 1, 0, 1], # 0: Male, 1: Female\n",
329
- " 'Approved': [0, 1, 1, 1, 0, 1]\n",
330
- "})\n",
331
- "\n",
332
- "X = data[['Income', 'CreditScore', 'Gender']]\n",
333
- "y = data['Approved']\n",
334
- "\n",
335
- "# Train-test split\n",
336
- "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
337
- "\n",
338
- "# Logistic Regression model\n",
339
- "model = LogisticRegression()\n",
340
- "model.fit(X_train, y_train)\n",
341
- "y_pred = model.predict(X_test)\n",
342
- "\n",
343
- "# Display results\n",
344
- "print(\"Classification Report:\\n\", classification_report(y_test, y_pred))\n",
345
- "\n",
346
- "# Identifying bias in coefficients\n",
347
- "print(\"Model Coefficients:\", model.coef_)\n"
348
- ]
349
- },
350
- {
351
- "cell_type": "code",
352
- "execution_count": null,
353
- "id": "f877d16e",
354
- "metadata": {
355
- "id": "0EVGKJ9mJ5nS"
356
- },
357
- "outputs": [],
358
- "source": [
359
- "import numpy as np\n",
360
- "import torch\n",
361
- "import torch.nn as nn\n",
362
- "import torch.optim as optim\n",
363
- "from sklearn.model_selection import train_test_split\n",
364
- "from sklearn.metrics import accuracy_score\n",
365
- "import cv2\n",
366
- "import matplotlib.pyplot as plt\n",
367
- "\n",
368
- "# Function to add noise to an image\n",
369
- "def add_noise(image):\n",
370
- " noise = np.random.normal(0, 0.1, image.shape)\n",
371
- " noisy_image = image + noise\n",
372
- " return np.clip(noisy_image, 0, 1)\n",
373
- "\n",
374
- "# Generate a simple dataset of images\n",
375
- "def generate_dataset(image_path, num_samples=100):\n",
376
- " # Load and preprocess the original image\n",
377
- " original_image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n",
378
- " original_image = cv2.resize(original_image, (64, 64)) # Resize for simplicity\n",
379
- " original_image = original_image / 255.0 # Normalize to [0, 1]\n",
380
- "\n",
381
- " # Create dataset\n",
382
- " images = []\n",
383
- " labels = [] # 0 for original, 1 for noisy\n",
384
- "\n",
385
- " for _ in range(num_samples // 2):\n",
386
- " # Add original image (class 0)\n",
387
- " images.append(original_image.flatten()) # Flatten the image\n",
388
- " labels.append(0)\n",
389
- "\n",
390
- " # Add noisy version (class 1)\n",
391
- " noisy_image = add_noise(original_image)\n",
392
- " images.append(noisy_image.flatten())\n",
393
- " labels.append(1)\n",
394
- "\n",
395
- " return np.array(images), np.array(labels)\n",
396
- "\n",
397
- "# Define a simple deep learning model\n",
398
- "class SimpleNN(nn.Module):\n",
399
- " def __init__(self, input_size):\n",
400
- " super(SimpleNN, self).__init__()\n",
401
- " self.fc1 = nn.Linear(input_size, 128)\n",
402
- " self.fc2 = nn.Linear(128, 64)\n",
403
- " self.fc3 = nn.Linear(64, 2) # Two classes: Original and Noisy\n",
404
- " self.relu = nn.ReLU()\n",
405
- "\n",
406
- " def forward(self, x):\n",
407
- " x = self.relu(self.fc1(x))\n",
408
- " x = self.relu(self.fc2(x))\n",
409
- " x = self.fc3(x)\n",
410
- " return x\n",
411
- "\n",
412
- "# Generate dataset\n",
413
- "image_path = 'image.jpg' # Replace with your image file\n",
414
- "X, y = generate_dataset(image_path, num_samples=200)\n",
415
- "\n",
416
- "# Split into training and test sets\n",
417
- "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
418
- "\n",
419
- "# Convert data to PyTorch tensors\n",
420
- "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
421
- "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
422
- "y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n",
423
- "y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n",
424
- "\n",
425
- "# Define model, loss function, and optimizer\n",
426
- "input_size = X_train.shape[1]\n",
427
- "model = SimpleNN(input_size)\n",
428
- "criterion = nn.CrossEntropyLoss()\n",
429
- "optimizer = optim.Adam(model.parameters(), lr=0.001)\n",
430
- "\n",
431
- "# Train the model\n",
432
- "epochs = 20\n",
433
- "for epoch in range(epochs):\n",
434
- " # Forward pass\n",
435
- " outputs = model(X_train_tensor)\n",
436
- " loss = criterion(outputs, y_train_tensor)\n",
437
- "\n",
438
- " # Backward pass and optimization\n",
439
- " optimizer.zero_grad()\n",
440
- " loss.backward()\n",
441
- " optimizer.step()\n",
442
- "\n",
443
- " print(f\"Epoch {epoch + 1}/{epochs}, Loss: {loss.item():.4f}\")\n",
444
- "\n",
445
- "# Evaluate the model\n",
446
- "with torch.no_grad():\n",
447
- " y_pred = model(X_test_tensor)\n",
448
- " y_pred_classes = torch.argmax(y_pred, dim=1).numpy()\n",
449
- " accuracy = accuracy_score(y_test, y_pred_classes)\n",
450
- " print(f\"Model Accuracy: {accuracy * 100:.2f}%\")\n",
451
- "\n",
452
- "# Visualize a test image with prediction\n",
453
- "test_image = X_test[0].reshape(64, 64)\n",
454
- "prediction = y_pred_classes[0]\n",
455
- "\n",
456
- "plt.imshow(test_image, cmap='gray')\n",
457
- "plt.title(f\"Predicted: {'Noisy' if prediction == 1 else 'Original'}\")\n",
458
- "plt.axis('off')\n",
459
- "plt.show()\n"
460
- ]
461
- }
462
- ],
463
- "metadata": {
464
- "colab": {
465
- "provenance": []
466
- },
467
- "kernelspec": {
468
- "display_name": "Python 3 (ipykernel)",
469
- "language": "python",
470
- "name": "python3"
471
- },
472
- "language_info": {
473
- "codemirror_mode": {
474
- "name": "ipython",
475
- "version": 3
476
- },
477
- "file_extension": ".py",
478
- "mimetype": "text/x-python",
479
- "name": "python",
480
- "nbconvert_exporter": "python",
481
- "pygments_lexer": "ipython3",
482
- "version": "3.12.4"
483
- }
484
- },
485
- "nbformat": 4,
486
- "nbformat_minor": 5
487
- }