-
Notifications
You must be signed in to change notification settings - Fork 2
/
pca.py
234 lines (181 loc) · 6.36 KB
/
pca.py
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
# import json
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
# # Load the data from JSON file
# with open("datasets/encoder_output_vehicle_a_mse.json", "r") as f:
# data = json.load(f)
# # Assuming the data is a list of lists
# fig = plt.figure(figsize=(12, 12))
# ax = fig.add_subplot(projection="3d")
# data_points = list(data.values())
# data_matrix = np.array(data_points)
from sklearn.decomposition import PCA
# # Initialize PCA, we'll reduce to 2 dimensions for easy visualization
pca = PCA(n_components=3)
# # Apply PCA to the data
# reduced_data = pca.fit_transform(data_matrix)
# # Plot the reduced data
# ax.scatter(reduced_data[:, 0], reduced_data[:, 1], reduced_data[:, 2])
# # ax.xlabel("Principal Component 1")
# # ax.ylabel("Principal Component 2")
# # ax.title("PCA of High-Dimensional Data")
# plt.savefig("output/pca.png")
# import json
# import matplotlib.pyplot as plt
# import numpy as np
# from sklearn.decomposition import PCA
# # Load the data from JSON file
# with open("datasets/encoder_output_vehicle_a_mse.json", "r") as f:
# data = json.load(f)
# # Assuming the data is a list of lists
# fig = plt.figure(figsize=(12, 12))
# ax = fig.add_subplot(projection="3d")
# data_points = list(data.values())
# data_matrix = np.array(data_points)
# # Initialize PCA, we'll reduce to 3 dimensions
# pca = PCA(n_components=3)
# # Apply PCA to the data
# reduced_data = pca.fit_transform(data_matrix)
# # Plot the reduced data with colors based on the z-axis values
# # Use a colormap to specify the color scheme, e.g., 'viridis', 'jet', etc.
# scatter = ax.scatter(
# reduced_data[:, 0],
# reduced_data[:, 1],
# reduced_data[:, 2],
# c=reduced_data[:, 2],
# cmap="viridis",
# )
# # Adding a color bar to understand the mapping of colors
# plt.colorbar(scatter, ax=ax, label="Height (Z-axis value)")
# # Uncomment and correct these lines if you want to set labels and titles
# # ax.set_xlabel("Principal Component 1")
# # ax.set_ylabel("Principal Component 2")
# # ax.set_zlabel("Principal Component 3")
# # ax.set_title("PCA of High-Dimensional Data")
# plt.savefig("output/pca_colored.png")
# import json
# import matplotlib.pyplot as plt
# import numpy as np
# from sklearn.decomposition import PCA
# # Load the data from JSON file
# def get_matplotlib_color(number):
# """
# Returns a Matplotlib color based on the input number.
# Parameters:
# - number: int, a number between 0 and 7 inclusive.
# Returns:
# - str, a named Matplotlib color.
# """
# colors = ["blue", "green", "red", "cyan", "magenta", "yellow", "black", "white"]
# if 0 <= number <= 7:
# return colors[number]
# else:
# raise ValueError("Input number must be between 0 and 7.")
data_points = np.load("datasets/scenario_features_embeddings.npy")
# # Assuming the data is a list of lists
# fig = plt.figure(figsize=(12, 12))
# ax = fig.add_subplot(projection="3d")
# data_points = list(data.values())
data_matrix = np.array(data_points)
# # Initialize PCA, we'll reduce to 3 dimensions
pca = PCA(n_components=3)
# # Apply PCA to the data
reduced_data = pca.fit_transform(data_matrix)
# reduced_data = np.zeros(8)
# # Plot the initial state of the reduced data
# scatter = ax.scatter(
# reduced_data[:, 0],
# reduced_data[:, 1],
# reduced_data[:, 2],
# c=reduced_data[:, 2],
# cmap="viridis",
# )
# # Set labels and title
# ax.set_xlabel("Principal Component 1")
# ax.set_ylabel("Principal Component 2")
# ax.set_zlabel("Principal Component 3")
# ax.set_title("PCA of High-Dimensional Data")
# # Create a directory to save the frames
import os
# frames_dir = "pca_frames"
# os.makedirs(frames_dir, exist_ok=True)
# # Save each frame
# for angle in range(0, 360, 2):
# print(angle)
# ax.view_init(elev=10.0, azim=angle)
# filename = f"{frames_dir}/frame_{angle:03d}.png"
# plt.savefig(filename)
# print("All frames saved.")
import json
import matplotlib.pyplot as plt
import numpy as np
from sklearn.decomposition import PCA
labels = [
"Left",
"Right",
"Stationary",
"Straight",
"Straight-Left",
"Straight-Right",
"Right-U-Turn",
"Left-U-Turn",
]
colors = [
"orange", # Left
"blue", # Right
"grey", # Stationary
"black", # Straight
"yellow", # Straight-Left
"lightblue", # Straight-Right
"purple", # Right-U-Turn
"red", # Left-U-Turn (replacing white with purple for better visibility)
]
# Step 1: Define the color selection function
def get_matplotlib_color(number):
colors = [
"orange", # Left
"blue", # Right
"grey", # Stationary
"black", # Straight
"yellow", # Straight-Left
"lightblue", # Straight-Right
"purple", # Right-U-Turn
"red", # Left-U-Turn (replacing white with purple for better visibility)
]
if 0 <= number <= 7:
return colors[number]
else:
raise ValueError("Input number must be between 0 and 7.")
# Assuming `number_list` is your list of numbers corresponding to the points
number_list = np.load("datasets/scenario_features_embeddings.npy")
print(number_list[:5])
# number_list = [your list of numbers here] # Replace this with your actual list of numbers
# Generate a list of colors for each point
# point_colors = [get_matplotlib_color(number) for number in number_list]
# Assuming `reduced_data` contains your PCA-transformed data
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(projection="3d")
# Step 3: Plot using the generated colors
# c = point_colors
scatter = ax.scatter(reduced_data[:, 0], reduced_data[:, 1], reduced_data[:, 2])
# Set labels and title (optional, for better understanding of the plot)
ax.set_xlabel("Principal Component 1")
ax.set_ylabel("Principal Component 2")
ax.set_zlabel("Principal Component 3")
ax.set_title("PCA of High-Dimensional Data")
# plt.savefig("output/clustered.png")
legend_handles = [
Line2D([0], [0], color=color, marker="o", linestyle="", markersize=10, label=label)
for color, label in zip(colors, labels)
]
plt.legend(handles=legend_handles, title="Trajectory Bucket")
frames_dir = "pca_frames_cluster"
os.makedirs(frames_dir, exist_ok=True)
# Save each frame
for angle in range(0, 360, 2):
print(angle)
ax.view_init(elev=10.0, azim=angle)
filename = f"{frames_dir}/frame_{angle:03d}.png"
plt.savefig(filename)
print("All frames saved.")