In this project, I will be performing an unsupervised Dimensionality Reduction of Data of on the car sales records taken from Norway car inporter and Distributor company.

Dimensionality reduction is a technique in data analysis and machine learning that involves reducing the number of features or variables in a dataset while preserving its essential information. The goal is to simplify the dataset (reducing high dimensional data in to small dimension), making it more manageable and easier to work with, while retaining its important patterns and relationships.

1 Installing and Importing Libraries

# Set the CRAN mirror
options(repos = c(CRAN = "https://cran.rstudio.com"))
# Install the package
install.packages("ggplot2")
## Installing package into 'C:/Users/asus/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'ggplot2' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\asus\AppData\Local\Temp\RtmpAT7ywR\downloaded_packages

2 Loading the Data

New_car_sales<-read.csv("C:/Users/asus/Desktop/Data Science/Unsupervised Learning/Unsupervised learning_R projects/Dimension_Reduction_Project/norway_new_car_sales_by_month.csv")
head(New_car_sales)
##   Year Month Quantity Quantity_YoY Import Import_YoY Used Used_YoY Avg_CO2
## 1 2007     1    12685         5227   2276        257   NA       NA     152
## 2 2007     2     9793         2448   1992        -89   NA       NA     156
## 3 2007     3    11264         1445   2626         45   NA       NA     159
## 4 2007     4     8854          504   2220       -130   NA       NA     160
## 5 2007     5    12007         1592   2881          7   NA       NA     160
## 6 2007     6    11083         1545   3038         23   NA       NA     161
##   Bensin_Co2 Diesel_Co2 Quantity_Diesel Diesel_Share Diesel_Share_LY
## 1        155        152           10072         79.4            52.5
## 2        159        155            7222         73.7            47.4
## 3        161        158            7965         70.7            48.1
## 4        165        158            6116         69.1            48.4
## 5        163        159            8519         71.0            49.1
## 6        163        160            8290         74.8            49.5
##   Quantity_Hybrid Quantity_Electric Import_Electric
## 1              NA                NA              NA
## 2              NA                NA              NA
## 3              NA                NA              NA
## 4              NA                NA              NA
## 5              NA                NA              NA
## 6              NA                NA              NA

3 Data Cleaning

since the Original data I took from the Car company has some NA values(as seen on the dataset), It needs to be cleaned to avoid any empty datas which cause trouble in our analysis.

New_car_sales <- New_car_sales[, !(names(New_car_sales) %in% c("Used","Used_YoY","Quantity_Hybrid", "Quantity_Electric","Import_Electric"))]
head(New_car_sales)
##   Year Month Quantity Quantity_YoY Import Import_YoY Avg_CO2 Bensin_Co2
## 1 2007     1    12685         5227   2276        257     152        155
## 2 2007     2     9793         2448   1992        -89     156        159
## 3 2007     3    11264         1445   2626         45     159        161
## 4 2007     4     8854          504   2220       -130     160        165
## 5 2007     5    12007         1592   2881          7     160        163
## 6 2007     6    11083         1545   3038         23     161        163
##   Diesel_Co2 Quantity_Diesel Diesel_Share Diesel_Share_LY
## 1        152           10072         79.4            52.5
## 2        155            7222         73.7            47.4
## 3        158            7965         70.7            48.1
## 4        158            6116         69.1            48.4
## 5        159            8519         71.0            49.1
## 6        160            8290         74.8            49.5
ncol(New_car_sales)
## [1] 12
class(New_car_sales)
## [1] "data.frame"
rows_with_na <- sum(!complete.cases(New_car_sales))
print(rows_with_na)
## [1] 0

4 Dimension Reduction

There are different types of Dimension reduction Methods depending on the data types on which the reduction is going to be done. These are Principal Component Analysis (PCA), t-Distributed Stochastic Neighbor Embedding (t-SNE)… Since my data set is numerical and most of the variables have linear relationship, PCA is the most suitable for this case. but my intention is not the result but the methode, so I am going to use both the methods and see their functionality.

4.1 Method 1: Principal Component Analysis (PCA)

Before doing PCA, we have to standardize our data is to ensure that all features contribute equally to the computation of principal components.

install.packages("ggfortify")
## Installing package into 'C:/Users/asus/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'ggfortify' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\asus\AppData\Local\Temp\RtmpAT7ywR\downloaded_packages
library(ggfortify)
## Loading required package: ggplot2
# Standardize the data
scaled_data <- scale(New_car_sales)
# Perform PCA
PCA_result <- prcomp(scaled_data[,c("Quantity","Diesel_Share","Avg_CO2")], center = TRUE, scale. = TRUE)
fortified_pca <- fortify(PCA_result)

4.1.1 Graphical Representation of the reduced data set

library(ggplot2)
ggplot(fortified_pca, aes(x = PC1, y = PC2, z = PC3)) +
  geom_point(aes(color = Avg_CO2)) +
  labs(title = "PCA Scatter Plot (3 Components)", x = "Total Number of Car Sold", y = "Diesel Share", z = "Avg CO2")

As we see from the Scatter Plot, the points at the right side are more of light blue color which indicates that they have the same attributes(Average CO2). that means, the more car sold the more the there is more CO2 Emission. Which indicates that our dimension reduction makes sense logically. There is also the points at the left sides shows some similar properties, they have similar average CO2 Emission. this method groups data s that have the attributes. as a conclusion we can say that No matter what the year is or (other attributes) the Number of car sold and Diesel share has direct relation ship to the Increase of C02 Emission. This Method allows us to Analyse the data by decreasing the number of features to the most influenced ones.

4.1.2 3D Scatter Plot of the reduced data set

library(scatterplot3d)

# Assuming Avg_CO2 is a variable in your data frame
fortified_pca$Avg_CO2 <- fortified_pca$Avg_CO2

# Set up colors based on the Avg_CO2 values
colors <- colorRampPalette(c("blue", "green", "red"))(length(unique(fortified_pca$Avg_CO2)))

# Create the 3D scatter plot
scatterplot3d(
  fortified_pca$PC1,
  fortified_pca$PC2,
  fortified_pca$PC3,
  color = colors[as.factor(fortified_pca$Avg_CO2)],
  main = "PCA 3D Scatter Plot",
  xlab = "Total Number of Car Sold",
  ylab = "Diesel Share",
  zlab = "Avg CO2",
  #angle = 45,  # Adjust the viewing angle
  #theta = 60,  # Adjust rotation around z-axis
  #phi = 30 
)

4.2 Methode 2: t-Distributed Stochastic Neighbor Embedding (t-SNE)

t-SNE is a nonlinear technique used for visualization. Mostly this method is used for the data set which has variables which posses non-linear relationship between themselves. It preserves the local relationships between data points, making it effective for creating low-dimensional visualizations of high-dimensional data.

install.packages("Rtsne")
## Installing package into 'C:/Users/asus/AppData/Local/R/win-library/4.3'
## (as 'lib' is unspecified)
## package 'Rtsne' successfully unpacked and MD5 sums checked
## 
## The downloaded binary packages are in
##  C:\Users\asus\AppData\Local\Temp\RtmpAT7ywR\downloaded_packages
install.packages("ggplot2")
## Warning: package 'ggplot2' is in use and will not be installed
library(Rtsne)
library(ggplot2)
library(scatterplot3d)
# Avg_CO2 is the column I want to use for coloring
Avg_CO2 <- New_car_sales$Avg_CO2
# Perform t-SNE
tsne_result <- Rtsne(New_car_sales[, c("Quantity","Avg_CO2","Diesel_Share")],dims = 3)
# Create a data frame with the t-SNE results and the 'Avg_CO2' column
tsne_data <- data.frame(X = tsne_result$Y[, 1], Y = tsne_result$Y[, 2],Z = tsne_result$Y[, 3], Avg_CO2 = as.factor(Avg_CO2))

4.2.1 Graphical Representation of the reduced data set

# Visualize t-SNE results with color-coded points
ggplot(tsne_data, aes(x = X, y = Z, color = Avg_CO2)) +
  geom_point() +
  ggtitle("t-SNE Visualization with Color-Coded Points by Year",
          )+
  labs(
    x = "Total Number of Car Sold",
    y = "Diesel Share",
   
  )

As we see from the Graph, the points at the left side shows Low number of car sold relates to small number of Diesel_Share and small average CO2 Emission. they share the same property, look at the color they are the group of yellow. on the other hand(at the right side), there are a group of points(data’s) that have high Number of car sold and High Diesel_Share. when we look at the color they have the same color indicating they have the same number of CO2 Emission.

4.2.2 3D Scatter Plot of the reduced data set

scatterplot3d(tsne_data$X, tsne_data$Y, tsne_data$Z, color=as.numeric(tsne_data$Avg_CO2), 
              pch=16, main="3D t-SNE Visualization with Color-Coded Points by Avg_CO2",
                  xlab = "Total Number of Car Sold",
  ylab = "Diesel Share",
  zlab = "Avg CO2")

lets generalize the functionality of the method, This method groups data depending on the the attributes we want to analyse while considering other attributes(variables) of the real data. without reducing the dimension it is impossible for us to analyse and work with the data since the raw data has many(in my case,18) variables(attributes).