-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpca.py
More file actions
54 lines (39 loc) · 1.24 KB
/
Copy pathpca.py
File metadata and controls
54 lines (39 loc) · 1.24 KB
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
# -*- coding: utf-8 -*-
# @Date : 2020/5/24
# @Author: Luokun
# @Email : olooook@outlook.com
import sys
from os.path import dirname, abspath
import numpy as np
import matplotlib.pyplot as plt
sys.path.append(dirname(dirname(abspath(__file__))))
def test_pca():
from models.pca import PCA
x = np.random.randn(3, 200, 2)
x[1] += np.array([-2, 0])
x[2] += np.array([2, 0])
scale = np.diag([1.2, .6]) # 缩放矩阵
theta = np.pi / 4 # 逆时针旋转45°
rotate = np.array([
[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)]
]) # 旋转矩阵
x = x.reshape(-1, 2)
x = x @ scale @ rotate.T
plot_scatter(x.reshape(3, -1, 2), 'Before PCA')
# 不降维
x_2d = PCA(2).transform(x)
plot_scatter(x_2d.reshape(3, -1, 2), 'PCA 2D')
# 降为1维
x_1d = PCA(1).transform(x)
plot_scatter(np.concatenate([x_1d.reshape(3, -1, 1), np.zeros([3, 200, 1])], axis=-1), 'PCA 1D')
def plot_scatter(xys, title):
plt.figure(figsize=[8, 8])
for xy, color in zip(xys, ['r', 'g', 'b']):
plt.scatter(xy[:, 0], xy[:, 1], color=color, marker='.')
plt.xlim(-5, 5)
plt.ylim(-5, 5)
plt.title(title)
plt.show()
if __name__ == '__main__':
test_pca()