-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrincipal-Component-Analysis.py
216 lines (148 loc) · 6.9 KB
/
Principal-Component-Analysis.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
# -*- coding: utf-8 -*-
"""Principal_component_analysis.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/19juU4awg3o4cMizoO8T9sUjxlDJ5LWe2
#**Lab 11 - Data science and principal component analysis**
Enter your code in the spaces provided. Do not change any of the variable names or function names that are already provided for you. In places where we specify the name of the return value, make sure that your code produces the a value with the correct name.
"""
# Do not edit this cell.
LabID="Lab11"
try:
from graderHelp import ISGRADEPLOT
except ImportError:
ISGRADEPLOT = True
"""**Enter your name, section number, and BYU NetID**"""
# Enter your first and last names in between the quotation marks.
first_name="Drew"
last_name="Morris"
# Enter your Math 215 section number in between the quotation marks.
section_number="010"
# Enter your BYU NetID in between the quotation marks. NOT YOUR BYU ID NUMBER!
BYUNetID="morris69"
"""**Import the required packages**"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""**Problem 1**"""
u = np.array([1/np.sqrt(6),1/np.sqrt(6),2/np.sqrt(6)])
x = np.array([2,1,-3])
# This function returns the coordinate of x projected to the line spanned by u.
def projection_coordinate(u,x):
if np.shape(u) != np.shape(x):
raise ValueError("u and x are different lengths")
else:
k = np.dot(u,x)/np.dot(u,u)
v = k*u
for i in range(0,np.shape(v)[0]):
if v[i] == 0 or u[i] == 0:
continue
if v[i] != 0 and u[i] != 0:
y = v[i]/u[i]
break
return y
projection_coordinate(u,x)
"""**Problem 2**"""
w1 = np.array([1/3,2/3,2/3])
w2 = np.array([0,-1/np.sqrt(2),1/np.sqrt(2)])
Y = np.array([[1,2,3],[4,5,6],[7,8,9]])
# This function returns the coordinates of the points in X projected to the plane spanned by u1 and u2.
def projection_2D(u1,u2,X):
if np.shape(u1) != np.shape(u2):
raise ValueError("u1 and u2 are different lengths")
else:
U = np.vstack([u1,u2])
return U@X
projection_2D(w1,w2,Y)
"""**Downloading dataset**
The simplest way to load the data file into Colab is to first download it as .csv file to your local computer by clicking the link
https://drive.google.com/uc?export=download&id=1zwNTk7r46RWzuZJO7THf_n5FyCkew7Ns
This will allow you to download the data as a .csv file. In the top left corner of this screen you should see a little file folder icon. Selecting it opens a new window to the left of the notebook with three tabs: "Upload", "Refresh", and "Mount Drive". Select "Upload". This should bring up a window that allows you to select the file "Lab11data.csv" from your local machine, which will upload the file to your notebook. You will need to do this again if you decide to close your notebook and reopen it at a later time.
**Converting the dataset into arrays**
The following cell imports the data and creates three NumPy arrays. The array X_total contains a column for each surveyed individual, with one row for each of their (numerical) survey answers. The array X_neg contains the survey information of only the individuals who tested negative for cancer, while the array X_pos contains the survey information of only the individuals who tested positive for cancer. This cell also creates two vectors which represent survey data for two unknown patients, Alice and Bob.
"""
df = pd.read_csv('Lab11data.csv',header=None)
X_neg=df.loc[df[100]==0].drop(columns=100).values.transpose()
X_pos=df.loc[df[100]==1].drop(columns=100).values.transpose()
X_total=df.loc[df[100]>=0].drop(columns=100).values.transpose()
Alice=df.loc[df[100]<0].drop(columns=100).values[0,:]
Bob=df.loc[df[100]<0].drop(columns=100).values[1,:]
""" **Problem 3**"""
def covariance(X):
T = np.transpose(X)
n = np.shape(X)[1]
Y = X@T
W = (1/(n-1))*Y
return W
# Save the value of the covariance matrix you obtain in Problem 3 as the variable W.
W=covariance(X_total)
print(W)
"""**Problem 4**"""
def eigen_decomp(M):
L = np.linalg.eig(M)[0]
P = np.linalg.eig(M)[1]
return [L,P]
A = eigen_decomp(W)
L = A[0]
P = A[1]
S = L[0:3]
T = [[],[],[]]
for j in range(0,3):
for i in range(len(P)):
T[j] = T[j] + [P[i,j]]
# Save the eigenvalues and eigenvectors you produced for Problem 4 here.
L1=S[0]
L2=S[1]
L3=S[2]
u1=np.array(T[0])
u2=np.array(T[1])
u3=np.array(T[2])
print(T[0])
print(u1)
"""**Problem 5**"""
V_total = sum(L)
V_reduced = sum(L[0:2])
V_relative = V_reduced/V_total
print(V_total)
print(V_reduced)
print(V_relative)
# Save the variance values you produced for Problem 5 here.
total_variance=V_total
reduced_variance=V_reduced
relative_variance=V_relative
"""**Problem 6**"""
# Save the projected data points from Problem 6 here.
X_neg_2D = projection_2D(u1,u2,X_neg)
X_pos_2D = projection_2D(u1,u2,X_pos)
Alice_2D = projection_2D(u1,u2,Alice)
Bob_2D = projection_2D(u1,u2,Bob)
"""**Problem 7**
This function can be used to plot the various 2-dimensional data points we've found. It can accept up to four different arrays (any combination of X_neg_2D, X_pos_2D, Alice_2D, Bob_2D), and will plot the data together on a single plot.
"""
# Use this function to plot the various 2-dimensional data points we've found. You can plot all of the data at once, or one array at a time.
def plot_data(Z1=[],Z2=[],Z3=[],Z4=[]):
fig = plt.figure()
ax1 = fig.add_subplot(111)
colors = plt.cm.rainbow(np.linspace(0, 1, 10))
if len(Z1)>0:
Y1=np.reshape(Z1,(2,-1))
ax1.scatter(Y1[0,:], Y1[1,:], s=2, c='b', marker="o")
if len(Z2)>0:
Y2=np.reshape(Z2,(2,-1))
ax1.scatter(Y2[0,:], Y2[1,:], s=2, c='r', marker="o")
if len(Z3)>0:
Y3=np.reshape(Z3,(2,-1))
ax1.scatter(Y3[0,:], Y3[1,:], s=100, c='g', marker="o")
if len(Z4)>0:
Y4=np.reshape(Z4,(2,-1))
ax1.scatter(Y4[0,:], Y4[1,:], s=100, c=[colors[7]], marker="o")
plt.show()
return None
plot_data(X_neg_2D,X_pos_2D,Alice_2D,Bob_2D)
# Save the values of your predictions below. +1 indicates the individual is predicted to develop this type of cancer (testing positive), while -1 indicates they are predicted not to (testing negative).
Alice_prediction=1
Bob_prediction=-1
"""**STOP! BEFORE YOU SUBMIT THIS LAB:** Go to the "Runtime" menu at the top of this page, and select "Restart and run all". If any of the cells produce error messages, you will either need to fix the error(s) or delete the code that is causing the error(s). Then use "Restart and run all" again to see if there are any new errors. Repeat this until no new error messages show up.
**You are not ready to submit until you are able to select "Restart and run all" without any new error messages showing up. Your code will not be able to be graded if there are any error messages.**
To submit your lab for grading you must first download it to your compute as .py file. In the "File" menu select "Download .py". The resulting file can then be uploaded to http://www.math.byu.edu:30000 for grading.
"""