To evaluate car by classification task using deep neural network in R
library(keras)
Load the necessary libraries
Load the data set
Convert the categorical variables to equivalent numeric classes
Split the data set as train set and test set
Initialize the keras sequential model
Build the model with input layers,hidden layers and output layer as per the data size along with the activation function(here 6 I/P layer with relu activation and 4 O/P layer with softmax activation)
Compile the model with required loss,metrics and optimizer(here loss=categorical_crossentropy,optimizer=adam,metrics=accuracy)
Fit the model using the train set
Predict using the test set
Evaluate the metrics
library(caret)
library(keras)
data=read.csv(‘/…/car.csv’)
#Convert categorical data into numeric class
data$buying=factor(data$buying,labels=c(0:3))
data$maint=factor(data$maint,labels=c(0:3))
data$doors=factor(data$doors,label=c(0:3))
data$persons=factor(data$persons,label=c(0:2))
data$lug_boot=factor(data$lug_boot,label=c(0:2))
data$safety=factor(data$safety,label=c(0:2))
data$Class=factor(data$Class,label=c(0:3))
View(data)
#To Split 70% of data as training data
smp_size train_ind #Train set
train_data<-data[train_ind,]
xtrain=train_data[,1:6]
ytrain=train_data$Class
#Test set
test=data[-train_ind,]
xtest=test[,1:6]
ytest=test$Class
#converting the target variable to once hot encoded vectors using keras inbuilt function
train_y<-to_categorical(ytrain)
test_y #defining a keras sequential model
model %
layer_dense(units = 30, input_shape = 6 )%>%
layer_activation(activation = ‘relu’) %>%
layer_dense(units = 4)%>%
layer_activation(activation= “softmax”)
#compiling the defined model with metric = accuracy and optimiser as adam.
model %>% compile(
loss = ‘categorical_crossentropy’,
optimizer = ‘Adam’,
metrics = ‘accuracy’
)
#Summary of the model
summary(model)
#fitting the model on the training dataset
model %>% fit(as.matrix(xtrain), train_y, epochs = 100,batch_size=10)
#Predict using the Test data
yt=predict_classes(model,as.matrix(xtest))
loss_and_metrics % evaluate(as.matrix(xtest), test_y)
print(loss_and_metrics)
cat(“The confusion matrix is \n”)
print(confusionMatrix(as.factor(yt),as.factor(ytest)))