-
Notifications
You must be signed in to change notification settings - Fork 2
/
principal_component_analysis (pca).py
143 lines (89 loc) · 4.37 KB
/
principal_component_analysis (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
##############################################################################
# IMPORT REQUIRED PACKAGES
##############################################################################
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.utils import shuffle
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
##############################################################################
# IMPORT SAMPLE DATA
##############################################################################
# import
data_for_model = pd.read_csv("data/sample_data_pca.csv")
# drop uneccessary columns
data_for_model.drop("user_id", axis = 1, inplace = True)
# shuffle data
data_for_model = shuffle(data_for_model, random_state = 42)
# class balance
data_for_model["purchased_album"].value_counts(normalize = True)
##############################################################################
# DEAL WITH MISSING VALUES
##############################################################################
data_for_model.isna().sum().sum()
data_for_model.dropna(how = "any", inplace = True)
##############################################################################
# SPLIT INPUT VARIABLES & OUTPUT VARIABLES
##############################################################################
X = data_for_model.drop(["purchased_album"], axis = 1)
y = data_for_model["purchased_album"]
##############################################################################
# SPLIT OUT TRAINING & TEST SETS
##############################################################################
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42, stratify = y)
##############################################################################
# FEATURE SCALING
##############################################################################
scale_standard = StandardScaler()
X_train = scale_standard.fit_transform(X_train)
X_test = scale_standard.transform(X_test)
##############################################################################
# APPLY PCA
##############################################################################
# instantiate & fit
pca = PCA(n_components = None, random_state = 42)
pca.fit(X_train)
# extract the explained variance across components
explained_variance = pca.explained_variance_ratio_
explained_variance_cumulative = pca.explained_variance_ratio_.cumsum()
##############################################################################
# PLOT THE EXPLAINED VARIANCES ACROSS COMPONENTS
##############################################################################
# create a list for number of components
num_vars_list = list(range(1,101))
plt.figure(figsize=(15,10))
# plot the variance explained by each component
plt.subplot(2,1,1)
plt.bar(num_vars_list, explained_variance)
plt.title("Variance across Principal Components")
plt.xlabel("Number of Components")
plt.ylabel("% Variance")
plt.tight_layout()
# plot the cumulative variance
plt.subplot(2,1,2)
plt.plot(num_vars_list, explained_variance_cumulative)
plt.title("cumulative Variance across Principal Components")
plt.xlabel("Number of Components")
plt.ylabel("Cumulative % Variance")
plt.tight_layout()
plt.show()
##############################################################################
# APPLY PCA WITH SELECTED NUMBER OF COMPONENTS
##############################################################################
pca = PCA(n_components = 0.75, random_state = 42)
X_train = pca.fit_transform(X_train)
X_test = pca.transform(X_test)
pca.n_components_
##############################################################################
# APPLY PCA WITH SELECTED NUMBER OF COMPONENTS
##############################################################################
clf = RandomForestClassifier(random_state = 42)
clf.fit(X_train, y_train)
##############################################################################
# ASSESS MODEL ACCURACY
##############################################################################
y_pred_class = clf.predict(X_test)
accuracy_score(y_test, y_pred_class)