From 7cc394250c39fc1596e76cd82d776f7c3bda645e Mon Sep 17 00:00:00 2001 From: benj3542 <s200431@student.dtu.dk> Date: Mon, 20 Mar 2023 14:11:30 +0100 Subject: [PATCH] 3D pca code --- .DS_Store | Bin 6148 -> 6148 bytes FeatureEstimation.py | 1 + PCA.py | 53 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 PCA.py diff --git a/.DS_Store b/.DS_Store index bc975d8d2b78991fad68a23c0ac2ab94d094180f..d6e37f5c6de2c7fc3b8f1c47f7e5b3a22889276e 100644 GIT binary patch delta 16 XcmZoMXffEZj)~dG!eH}8reIM3FYN_1 delta 16 XcmZoMXffEZj)~dCz+&@8reIM3FZBgB diff --git a/FeatureEstimation.py b/FeatureEstimation.py index 4c599d4..814c531 100644 --- a/FeatureEstimation.py +++ b/FeatureEstimation.py @@ -35,6 +35,7 @@ the different parts easier (Default shortcut: Ctrl + Shift + O) # Set working directory +import numpy as np import os wkdir = "/home/s200431" os.chdir(wkdir) diff --git a/PCA.py b/PCA.py new file mode 100644 index 0000000..48dabfb --- /dev/null +++ b/PCA.py @@ -0,0 +1,53 @@ +from sklearn import decomposition +from sklearn.preprocessing import StandardScaler + +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D +import numpy as np + + +def PCA(X, y, n_components): + fig = plt.figure(1, figsize=(4, 3)) + plt.clf() + + ax = fig.add_subplot(111, projection="3d", elev=48, azim=134) + ax.set_position([0, 0, 0.95, 1]) + + # Standardize the data + scaler = StandardScaler() + X = scaler.fit_transform(X) + + pca = decomposition.PCA(n_components=n_components) + pca.fit(X) + X = pca.transform(X) + + for name, label in [("CTRL", 0), ("PTSD", 1)]: + ax.text3D( + X[y == label, 0].mean(), + X[y == label, 1].mean(), + X[y == label, 2].mean(), + name, + horizontalalignment="center", + bbox=dict(alpha=0.5, edgecolor="w", facecolor="w"), + ) + + ax.scatter( + X[:, 0], + X[:, 1], + X[:, 2], + c=y, + cmap=plt.cm.nipy_spectral, + edgecolor="k", + ) + + ax.xaxis.set_ticklabels([]) + ax.yaxis.set_ticklabels([]) + ax.zaxis.set_ticklabels([]) + + plt.show() + + # Save plot + Feature_savepath = "./Figures/" + plt.savefig(Feature_savepath + "PCA_3D.png", dpi=300) + + return "PCA was complete without errors - check the plot in your chosen path" -- GitLab