File size: 23,455 Bytes
d00d87c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "-dt9JrHpxRNH"
   },
   "source": [
    "### Data Preprocessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Collecting opencv-python\n",
      "  Downloading opencv-python-4.10.0.84.tar.gz (95.1 MB)\n",
      "\u001b[2K     \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m95.1/95.1 MB\u001b[0m \u001b[31m6.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m:00:01\u001b[0m00:01\u001b[0m\n",
      "\u001b[?25h  Installing build dependencies ... \u001b[?25ldone\n",
      "\u001b[?25h  Getting requirements to build wheel ... \u001b[?25ldone\n",
      "\u001b[?25h  Preparing metadata (pyproject.toml) ... \u001b[?25ldone\n",
      "\u001b[?25hRequirement already satisfied: numpy>=1.17.0 in /Users/nhradek/Library/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages (from opencv-python) (1.24.2)\n",
      "Building wheels for collected packages: opencv-python\n",
      "  Building wheel for opencv-python (pyproject.toml) ... \u001b[?25l/"
     ]
    }
   ],
   "source": [
    "!pip3 install opencv-python"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "dHy-E-RQlDoj",
    "tags": []
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import cv2\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.manifold import TSNE\n",
    "from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold\n",
    "from sklearn.metrics import accuracy_score, f1_score, confusion_matrix\n",
    "from sklearn.neighbors import KNeighborsClassifier\n",
    "from xgboost import XGBClassifier\n",
    "from sklearn.decomposition import PCA\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.decomposition import PCA\n",
    "from scipy.spatial import distance\n",
    "from collections import Counter\n",
    "import seaborn as sns\n",
    "import joblib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "60Rkg6uR5oyS",
    "tags": []
   },
   "outputs": [],
   "source": [
    "# Evaluate classifiers\n",
    "def evaluate_classifier(y_true, y_pred, classifier_name):\n",
    "    acc = accuracy_score(y_true, y_pred)\n",
    "    f1 = f1_score(y_true, y_pred)\n",
    "    cm = confusion_matrix(y_true, y_pred)\n",
    "    print(f\"{classifier_name} - Accuracy: {acc:.4f}, F1 Score: {f1:.4f}\")\n",
    "    print(f\"Confusion Matrix:\\n{cm}\\n\")\n",
    "\n",
    "    plt.figure(figsize=(8, 6))\n",
    "    sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Real Photo', 'CGI'], yticklabels=['Real Photo', 'CGI'])\n",
    "    plt.title(f'Confusion Matrix for {classifier_name}')\n",
    "    plt.xlabel('Predicted Labels')\n",
    "    plt.ylabel('True Labels')\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "oIsM1ilT5cQC",
    "tags": []
   },
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from PIL import Image\n",
    "from scipy.fftpack import fft2\n",
    "from tensorflow.keras.models import load_model, Model\n",
    "\n",
    "# Function to apply Fourier transform\n",
    "def apply_fourier_transform(image):\n",
    "    image = np.array(image)\n",
    "    fft_image = fft2(image)\n",
    "    return np.abs(fft_image)\n",
    "\n",
    "# Function to preprocess image\n",
    "def preprocess_image(image_path):\n",
    "    try:\n",
    "      image = Image.open(image_path).convert('L')\n",
    "      image = image.resize((256, 256))\n",
    "      image = apply_fourier_transform(image)\n",
    "      image = np.expand_dims(image, axis=-1)  # Expand dimensions to match model input shape\n",
    "      image = np.expand_dims(image, axis=0)   # Expand to add batch dimension\n",
    "      return image\n",
    "    except Exception as e:\n",
    "        print(f\"Error processing image {image_path}: {e}\")\n",
    "        return None\n",
    "\n",
    "# Function to load embedding model and calculate embeddings\n",
    "def calculate_embeddings(image_path, model_path='embedding_modelv2.keras'):\n",
    "    # Load the trained model\n",
    "    model = load_model(model_path)\n",
    "\n",
    "    # Remove the final classification layer to get embeddings\n",
    "    embedding_model = Model(inputs=model.input, outputs=model.output)\n",
    "\n",
    "    # Preprocess the image\n",
    "    preprocessed_image = preprocess_image(image_path)\n",
    "\n",
    "    # Calculate embeddings\n",
    "    embeddings = embedding_model.predict(preprocessed_image)\n",
    "\n",
    "    return embeddings\n",
    "\n",
    "\n",
    "def calculate_embeddings_folder(folder_path, model_path='embedding_modelv2.keras'):\n",
    "  embeddings = []\n",
    "  labels = []\n",
    "  for filename in os.listdir(folder_path):\n",
    "    if filename.endswith(\".jpg\") or filename.endswith(\".png\"):\n",
    "      image_path = os.path.join(folder_path, filename)\n",
    "      embedding = calculate_embeddings(image_path, model_path)\n",
    "      embeddings.append(embedding)\n",
    "      if \"CGI\" in folder_path:\n",
    "        labels.append(1)\n",
    "      else:\n",
    "        labels.append(0)\n",
    "  return embeddings, labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1lzKxl_gJUEg",
    "tags": []
   },
   "outputs": [],
   "source": [
    "embeddings = np.load('embeddings.npy')\n",
    "labels = np.load('labels.npy')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "12-KegWL3ZZh",
    "tags": []
   },
   "outputs": [],
   "source": [
    "X_train, X_test, y_train, y_test = train_test_split(embeddings, labels, test_size=0.2, random_state=42, stratify=labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8YY8_59Lmb1N"
   },
   "outputs": [],
   "source": [
    "X_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "fSosG_aU3o67"
   },
   "outputs": [],
   "source": [
    "xgb_clf = XGBClassifier(use_label_encoder=False, eval_metric='logloss', early_stopping_rounds=10)\n",
    "xgb_clf.fit(X_train, y_train, eval_set=[(X_test, y_test)], verbose=False)\n",
    "y_pred_xgb = xgb_clf.predict(X_test)\n",
    "evaluate_classifier(y_test, y_pred_xgb, \"XGBoost Classifier\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "YLhckFv8JYK0"
   },
   "outputs": [],
   "source": [
    "from sklearn.neural_network import MLPClassifier as MLP\n",
    "from sklearn.svm import SVC"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "MXsnZFDXlNrT"
   },
   "outputs": [],
   "source": [
    "# Naive random classifier\n",
    "class RandomClassifier:\n",
    "    def fit(self, X, y):\n",
    "        pass\n",
    "\n",
    "    def predict(self, X):\n",
    "        return np.random.choice([0, 1], size=X.shape[0])\n",
    "\n",
    "class MeanClassifier:\n",
    "    def fit(self, X, y):\n",
    "        self.mean_0 = np.mean(X[y == 0], axis=0) if np.any(y == 0) else None\n",
    "        self.mean_1 = np.mean(X[y == 1], axis=0) if np.any(y == 1) else None\n",
    "\n",
    "    def predict(self, X):\n",
    "        preds = []\n",
    "        for x in X:\n",
    "            dist_0 = distance.euclidean(x, self.mean_0) if self.mean_0 is not None else np.inf\n",
    "            dist_1 = distance.euclidean(x, self.mean_1) if self.mean_1 is not None else np.inf\n",
    "            preds.append(1 if dist_1 < dist_0 else 0)\n",
    "        return np.array(preds)\n",
    "\n",
    "    def predict_proba(self, X):\n",
    "      # An implementation of probability prediction which uses a softmax function to determine the probability of each class based on the distance to the mean for each prototype\n",
    "      preds = []\n",
    "      for x in X:\n",
    "        dist_0 = distance.euclidean(x, self.mean_0) if self.mean_0 is not None else np\n",
    "        dist_1 = distance.euclidean(x, self.mean_1) if self.mean_1 is not None else np.inf\n",
    "        prob_0 = np.exp(-dist_0) / (np.exp(-dist_0) + np.exp(-dist_1))\n",
    "        prob_1 = np.exp(-dist_1) / (np.exp(-dist_0) + np.exp(-dist_1))\n",
    "        preds.append([prob_0, prob_1])\n",
    "      return np.array(preds)\n",
    "\n",
    "    def mean_distance(self, x):\n",
    "      dist_mean_0 = distance.euclidean(x, self.mean_0) if self.mean_0 is not None else np.inf\n",
    "      dist_mean_1 = distance.euclidean(x, self.mean_1) if self.mean_1 is not None else np.inf\n",
    "      return dist_mean_0, dist_mean_1\n",
    "\n",
    "# Initialize classifiers\n",
    "random_clf = RandomClassifier()\n",
    "mean_clf = MeanClassifier()\n",
    "knn_clf = KNeighborsClassifier(n_neighbors=10)\n",
    "rf_clf = RandomForestClassifier(max_depth=10, random_state=42)\n",
    "mlp_clf = MLP(hidden_layer_sizes=(128,), max_iter=1000, random_state=42)\n",
    "svc_clf = SVC()\n",
    "\n",
    "# Train classifiers\n",
    "random_clf.fit(X_train, y_train)\n",
    "mean_clf.fit(X_train, y_train)\n",
    "knn_clf.fit(X_train, y_train)\n",
    "#xgb_clf.fit(X_train, y_train, eval_set=[(X_test, y_test)], verbose=False)\n",
    "rf_clf.fit(X_train, y_train)\n",
    "mlp_clf.fit(X_train, y_train)\n",
    "svc_clf.fit(X_train, y_train)\n",
    "\n",
    "# Make predictions\n",
    "y_pred_random = random_clf.predict(X_test)\n",
    "y_pred_mean = mean_clf.predict(X_test)\n",
    "y_pred_knn = knn_clf.predict(X_test)\n",
    "#y_pred_xgb = xgb_clf.predict(X_test)\n",
    "y_pred_rf = rf_clf.predict(X_test)\n",
    "y_pred_mlp = mlp_clf.predict(X_test)\n",
    "y_pred_svc = svc_clf.predict(X_test)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "sJ52bzdJmDvn"
   },
   "outputs": [],
   "source": [
    "evaluate_classifier(y_test, y_pred_random, \"Random Classifier\")\n",
    "evaluate_classifier(y_test, y_pred_mean, \"Mean Classifier\")\n",
    "evaluate_classifier(y_test, y_pred_knn, \"KNN Classifier\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "DqyF_6STHW7o"
   },
   "outputs": [],
   "source": [
    "evaluate_classifier(y_test, y_pred_xgb, \"XGBoost Classifier\")\n",
    "evaluate_classifier(y_test, y_pred_rf, \"Random Forest Classifier\")\n",
    "evaluate_classifier(y_test, y_pred_svc, \"SVC Classifier\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "QfrAONS-DLau"
   },
   "outputs": [],
   "source": [
    "evaluate_classifier(y_test, y_pred_mlp, \"MLP Classifier\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "awoV0KS8_3Bi"
   },
   "outputs": [],
   "source": [
    "test_filename = \"neytiri.png\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ddV4s5IUAaCc"
   },
   "outputs": [],
   "source": [
    "test_embeddings = calculate_embeddings(test_filename, model_path='embedding_modelv2.keras')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9yEk_X2rEH4K"
   },
   "outputs": [],
   "source": [
    "def print_prob(model, image_path):\n",
    "    test_embeddings = calculate_embeddings(image_path, model_path='embedding_modelv2.keras')\n",
    "    probs = model.predict_proba(test_embeddings)\n",
    "    print(f\"Real Photo Probability: {probs[0][0]:.4f}\")\n",
    "    print(f\"CGI Probability: {probs[0][1]:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "yD2JCKyJROb6"
   },
   "outputs": [],
   "source": [
    "print_prob(mlp_clf, test_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "A7Nu_ABnRpT8"
   },
   "outputs": [],
   "source": [
    "print_prob(mean_clf, test_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "AFJJuPG6Rpdz"
   },
   "outputs": [],
   "source": [
    "print_prob(xgb_clf, test_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Wil3P5JcRYNX"
   },
   "outputs": [],
   "source": [
    "print_prob(rf_clf, test_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "14O37IoKZCEW"
   },
   "outputs": [],
   "source": [
    "print_prob(knn_clf, test_filename)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "gi5Vdf-bQElG"
   },
   "outputs": [],
   "source": [
    "dist = np.round(mean_clf.mean_distance(test_embeddings[0]), 2)\n",
    "print(f\"Dist to real mean {dist[0]}\")\n",
    "print(f\"Dist to CGI mean {dist[1]}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "3RkM68Li8Kh0"
   },
   "outputs": [],
   "source": [
    "def embedding_distance(image_path_1, image_path_2):\n",
    "    embedding_1 = calculate_embeddings(image_path_1)\n",
    "    embedding_2 = calculate_embeddings(image_path_2)\n",
    "    distance = np.linalg.norm(embedding_1 - embedding_2)\n",
    "    return distance"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "x5GprsHRwkEX"
   },
   "source": [
    "## Visualizing Feature Space"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "oDx-07WfOd-2"
   },
   "outputs": [],
   "source": [
    "# prompt: How can I plot embeddings on a t-SNE scatter plot and colored by the label? A label of 1 should be \"CGI\" in the legend and 0 should be \"Real Photo\"\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "# Apply t-SNE\n",
    "tsne = TSNE(n_components=2, random_state=42)\n",
    "embeddings_2d = tsne.fit_transform(embeddings)\n",
    "\n",
    "# Plot the embeddings\n",
    "plt.figure(figsize=(10, 7))\n",
    "sns.scatterplot(\n",
    "    x=embeddings_2d[:, 0],\n",
    "    y=embeddings_2d[:, 1],\n",
    "    hue=['CGI' if label == 1 else 'Real Photo' for label in labels],  # Map labels to strings\n",
    "    palette=sns.color_palette(\"hsv\", 2),\n",
    "    legend=\"full\"\n",
    ")\n",
    "plt.title(\"t-SNE of Image Embeddings\")\n",
    "plt.xlabel(\"t-SNE component 1\")\n",
    "plt.ylabel(\"t-SNE component 2\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "BKyYu-8won0l"
   },
   "outputs": [],
   "source": [
    "# prompt: Can you write a function that visualizes the embeddings using t-sne with the labels but allows a parameter which is an image path and preprocesses the image and calculates the embeddings and plots this embedding as well?\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "def visualize_embeddings_with_new_image(image_path, embeddings, labels):\n",
    "  \"\"\"\n",
    "  Visualizes embeddings using t-SNE, including a new image's embedding.\n",
    "\n",
    "  Args:\n",
    "    image_path: Path to the new image.\n",
    "    embeddings: Existing embeddings.\n",
    "    labels: Corresponding labels for existing embeddings.\n",
    "  \"\"\"\n",
    "\n",
    "  # Calculate embedding for the new image\n",
    "  new_embedding = calculate_embeddings(image_path, model_path='embedding_modelv2.keras')\n",
    "\n",
    "  # Append new embedding and label to existing data\n",
    "  all_embeddings = np.concatenate((embeddings, new_embedding), axis=0)\n",
    "  all_labels = np.concatenate((labels, [2]), axis=0)  # Assuming 2 is a new label for the new image\n",
    "\n",
    "  # Apply t-SNE\n",
    "  tsne = TSNE(n_components=2, random_state=42)\n",
    "  embeddings_2d = tsne.fit_transform(all_embeddings)\n",
    "\n",
    "  # Plot the embeddings\n",
    "  plt.figure(figsize=(10, 7))\n",
    "  sns.scatterplot(\n",
    "      x=embeddings_2d[:-1, 0],  # Plot existing embeddings\n",
    "      y=embeddings_2d[:-1, 1],\n",
    "      hue=['CGI' if label == 1 else 'Real Photo' for label in all_labels[:-1]],\n",
    "      palette=sns.color_palette(\"hsv\", 2),\n",
    "      legend=\"full\"\n",
    "  )\n",
    "\n",
    "  # Plot the new image's embedding\n",
    "  plt.scatter(\n",
    "      x=embeddings_2d[-1, 0],\n",
    "      y=embeddings_2d[-1, 1],\n",
    "      color='black',\n",
    "      marker='*',\n",
    "      s=200,\n",
    "      label='New Image'\n",
    "  )\n",
    "\n",
    "  plt.title(\"t-SNE of Image Embeddings with New Image\")\n",
    "  plt.xlabel(\"t-SNE component 1\")\n",
    "  plt.ylabel(\"t-SNE component 2\")\n",
    "  plt.legend()\n",
    "  plt.show()\n",
    "\n",
    "# Example usage:\n",
    "# visualize_embeddings_with_new_image(\"path/to/your/new/image.jpg\", embeddings, labels)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "v6jrK3Auo-eM"
   },
   "outputs": [],
   "source": [
    "visualize_embeddings_with_new_image(\"neytiri.png\", embeddings, labels)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "JokVT8QNCOCm"
   },
   "source": [
    "### Testing Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "QzkDffzBDGce"
   },
   "outputs": [],
   "source": [
    "!unzip Validation.zip"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "UkuPOZXKCNd5"
   },
   "outputs": [],
   "source": [
    "cgi_val_images, cgi_val_labels = calculate_embeddings_folder('Validation/CGI')\n",
    "photo_val_images, photo_val_labels = calculate_embeddings_folder('Validation/Photo')\n",
    "\n",
    "print(f\"CGI shape {np.array(cgi_val_images).shape}\")\n",
    "print(f\"Photo shape {np.array(photo_val_images).shape}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "pUE8siFEDF0h"
   },
   "outputs": [],
   "source": [
    "# prompt: Can you test the validation images and labels against the XGB, Mean, and KNN classifiers?\n",
    "\n",
    "import numpy as np\n",
    "# Combine validation data\n",
    "X_val = np.concatenate((cgi_val_images, photo_val_images), axis=0)\n",
    "y_val = np.concatenate((cgi_val_labels, photo_val_labels), axis=0)\n",
    "\n",
    "# Reshape validation data to match model input\n",
    "X_val = X_val.reshape(X_val.shape[0], -1)\n",
    "\n",
    "# Predict using classifiers\n",
    "y_pred_xgb_val = xgb_clf.predict(X_val)\n",
    "y_pred_mean_val = mean_clf.predict(X_val)\n",
    "y_pred_knn_val = knn_clf.predict(X_val)\n",
    "y_pred_svc_val = svc_clf.predict(X_val)\n",
    "y_pred_rf_val = rf_clf.predict(X_val)\n",
    "y_pred_mlp_val = mlp_clf.predict(X_val)\n",
    "\n",
    "# Evaluate classifiers on validation set\n",
    "evaluate_classifier(y_val, y_pred_xgb_val, \"XGBoost Classifier (Validation)\")\n",
    "evaluate_classifier(y_val, y_pred_mean_val, \"Mean Classifier (Validation)\")\n",
    "evaluate_classifier(y_val, y_pred_knn_val, \"KNN Classifier (Validation)\")\n",
    "evaluate_classifier(y_val, y_pred_svc_val, \"SVC Classifier (Validation)\")\n",
    "evaluate_classifier(y_val, y_pred_rf_val, \"Random Forest Classifier (Validation)\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "KFvqq8di5QnS"
   },
   "source": [
    "### Old Preprocessing"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5-M_iFWC5SOk"
   },
   "outputs": [],
   "source": [
    "# Function to load and preprocess images\n",
    "def load_images(folder, label):\n",
    "    images = []\n",
    "    labels = []\n",
    "    for filename in os.listdir(folder):\n",
    "        if filename.endswith(\".jpg\") or filename.endswith(\".png\") or filename.endswith(\".jpeg\"):\n",
    "            img = cv2.imread(os.path.join(folder, filename), cv2.IMREAD_GRAYSCALE)\n",
    "            if img is not None:\n",
    "                img = cv2.resize(img, (256, 256))\n",
    "                images.append(img)\n",
    "                labels.append(label)\n",
    "    return images, labels\n",
    "\n",
    "pca = PCA(n_components=128)\n",
    "# Function to perform Fourier transform and extract features\n",
    "def extract_features(images):\n",
    "    features = []\n",
    "    for img in images:\n",
    "        f_transform = np.fft.fft2(img)\n",
    "        f_shift = np.fft.fftshift(f_transform)\n",
    "        magnitude_spectrum = 20 * np.log(np.abs(f_shift))\n",
    "        features.append(magnitude_spectrum.flatten())\n",
    "    features = pca.fit_transform(features)\n",
    "    return np.array(features)\n",
    "\n",
    "# Load and preprocess images from both folders\n",
    "cgi_images, cgi_labels = load_images('CGI', 1)  # 1 for CGI\n",
    "photo_images, photo_labels = load_images('Photo', 0)  # 0 for Real Photo\n",
    "\n",
    "min_length = min(len(cgi_images), len(photo_images))\n",
    "cgi_images = cgi_images[:min_length]\n",
    "cgi_labels = cgi_labels[:min_length]\n",
    "photo_images = photo_images[:min_length]\n",
    "photo_labels = photo_labels[:min_length]\n",
    "\n",
    "# Combine datasets\n",
    "images = cgi_images + photo_images\n",
    "labels = cgi_labels + photo_labels\n",
    "\n",
    "print(f\"Number of CGI images: {len(cgi_images)}\")\n",
    "print(f\"Number of Photo images: {len(photo_images)}\")\n",
    "\n",
    "# Extract features\n",
    "features = extract_features(images)\n",
    "\n",
    "# Encode labels\n",
    "labels = np.array(labels)\n",
    "\n",
    "# Split data into training and testing sets\n",
    "X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42, stratify=labels)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "yAqmOxpp-iin"
   },
   "outputs": [],
   "source": [
    "X_train.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "Dm1lretJBbKs"
   },
   "outputs": [],
   "source": [
    "embeddings.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "TlumN_GMBg_F"
   },
   "outputs": [],
   "source": [
    "X_test.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8Fq0dUzHtHeQ"
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "colab": {
   "machine_shape": "hm",
   "private_outputs": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.16"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}