-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathACP.py
135 lines (92 loc) · 2.26 KB
/
ACP.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
#we have a matrix Z (n x p) with n people and p character
import numpy as np
import matplotlib as mp
from numpy import linalg as la
import decimal
"Create the scalars which enable to centerize Z "
def Center(Z):
n = len(Z);
A = Z;
p = 1.0/n;
X = np.zeros(n);
for j in range(0, n):
sum = 0.0;
for i in range(0, n):
sum += p * Z[i][j];
X[j] = sum;
return X;
"compute variance"
def Variance(Z):
n = len(Z);
X = Center(Z);
S = np.zeros(n, dtype=np.dtype(decimal.Decimal));
for j in range (0, n):
sum = 0.0;
for i in range(0,n):
sum += (Z[i][j] - X[j])
S[j] = np.sqrt(sum);
return S
def Centerize(Z):
A = Z;
n = len(Z);
X = Center(Z);
for j in range (0, n):
for i in range (0, n):
A[i][j] -= X[j]
return A
def Reduce(Z):
n = len(Z);
A = Z;
X = Variance(Z);
for i in range(0,n):
for j in range (0, n):
A[i][j] = A[i][j]/X[j];
return A;
def ACP(Z):
tmp = Centerize(Z);
#tmp = Reduce(tmp);
a = np.shape(tmp)[0];
b = np.shape(tmp)[1];
#SVD decomposition
U, A, V = np.linalg.svd(tmp);
S = np.zeros((a, b));
mini = min(a, b);
S[:mini, :mini ]= np.diag(A);
#Factorial coord of peoples (Scores)
Xi = np.dot(U, S);
#Factorial coord of variables (loadings)
Phi = np.dot(V, np.transpose(S));
return Xi, Phi, A;
#Test
Z = [[1,2,3,4,5],[1,2,3,4,5],[6,7,8,9,10],[2,4,3,5,8]];
print Z;
print "Center(Z): "
print Center(Z);
print "Variance(Z): "
print Variance(Z);
print "Centerize(Z): "
print Centerize(Z);
U, S, V = np.linalg.svd(Z, full_matrices=False);
print U;
print S;
print V;
print "Xi"
print ACP(Z)[0]
print "Phi"
print ACP(Z)[1]
print "A"
print ACP(Z)[2]
Xi = ACP(Z)[0];
Phi = ACP(Z)[1];
#X = [row[1] for row in Xi]
#Y = [row[1] for row in Phi]
n = np.shape(Z)[0];
X = np.zeros(n);
for i in range (0, n):
X[i] = i+1;
import matplotlib.pyplot as plt
plt.plot(X, ACP(Z)[2], 'ro')
plt.plot( ACP(Z)[0], 'bo')
plt.plot( ACP(Z)[1], 'go')
plt.axis([-(n+2), n+2, -10, 10])
plt.show()