Path: blob/master/Part 9 - Dimension Reduction/Principal Component Analysis/pca.R
1336 views
# PCA12# Importing the dataset3dataset = read.csv('Wine.csv')45# Splitting the dataset into the Training set and Test set6# install.packages('caTools')7library(caTools)8set.seed(123)9split = sample.split(dataset$Customer_Segment, SplitRatio = 0.8)10training_set = subset(dataset, split == TRUE)11test_set = subset(dataset, split == FALSE)1213# Feature Scaling14training_set[-14] = scale(training_set[-14])15test_set[-14] = scale(test_set[-14])1617# Applying PCA18# install.packages('caret')19library(caret)20# install.packages('e1071')21library(e1071)22pca = preProcess(x = training_set[-14], method = 'pca', pcaComp = 2)23training_set = predict(pca, training_set)24training_set = training_set[c(2, 3, 1)]25test_set = predict(pca, test_set)26test_set = test_set[c(2, 3, 1)]2728# Fitting SVM to the Training set29# install.packages('e1071')30library(e1071)31classifier = svm(formula = Customer_Segment ~ .,32data = training_set,33type = 'C-classification',34kernel = 'linear')3536# Predicting the Test set results37y_pred = predict(classifier, newdata = test_set[-3])3839# Making the Confusion Matrix40cm = table(test_set[, 3], y_pred)4142# Visualising the Training set results43library(ElemStatLearn)44set = training_set45X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)46X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)47grid_set = expand.grid(X1, X2)48colnames(grid_set) = c('PC1', 'PC2')49y_grid = predict(classifier, newdata = grid_set)50plot(set[, -3],51main = 'SVM (Training set)',52xlab = 'PC1', ylab = 'PC2',53xlim = range(X1), ylim = range(X2))54contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)55points(grid_set, pch = '.', col = ifelse(y_grid == 2, 'deepskyblue', ifelse(y_grid == 1, 'springgreen3', 'tomato')))56points(set, pch = 21, bg = ifelse(set[, 3] == 2, 'blue3', ifelse(set[, 3] == 1, 'green4', 'red3')))5758# Visualising the Test set results59library(ElemStatLearn)60set = test_set61X1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)62X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01)63grid_set = expand.grid(X1, X2)64colnames(grid_set) = c('PC1', 'PC2')65y_grid = predict(classifier, newdata = grid_set)66plot(set[, -3], main = 'SVM (Test set)',67xlab = 'PC1', ylab = 'PC2',68xlim = range(X1), ylim = range(X2))69contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE)70points(grid_set, pch = '.', col = ifelse(y_grid == 2, 'deepskyblue', ifelse(y_grid == 1, 'springgreen3', 'tomato')))71points(set, pch = 21, bg = ifelse(set[, 3] == 2, 'blue3', ifelse(set[, 3] == 1, 'green4', 'red3')))7273