Created
October 21, 2019 22:02
-
-
Save gregyjames/e63d9d542db51be8101a300d194c336a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Perceptron <- function(data, learningRate) { | |
#Make the weights vector with 0s for each data coloumn | |
w <- c(rep(0, ncol(data) -1)) | |
#The number of rows in the dataframe | |
n <- nrow(data) | |
#Get the labels from the dataframe | |
label <- data[ , 1] | |
#Get the data from from the dataframe | |
obs <- data[ , 2:ncol(data)] | |
#We start assuming that the data is misclassifies | |
misclassfied <- TRUE | |
#Store the epoc count | |
epoc <- 0 | |
#Vector to store the predicted values | |
predictedV <- c(rep(0, n)) | |
#Store the average error for each Epoc | |
avgErr <- 0 | |
while (misclassfied) { | |
#Store the sum or errors for each Epoc | |
sumErr <- 0 | |
#Assume that the data isn't misclassified | |
misclassfied <- FALSE | |
for (i in 1:n) { | |
#Get the predicted value from the Classify function (WeightsxData columns) | |
predicted <- Classify(as.numeric(obs[i , ]), w)[1,1] | |
#Store the predicted value in the vector | |
predictedV[i] = predicted | |
#If we miss classified the observaion | |
if(predicted != label[i]){ | |
misclassfied = TRUE | |
#Calculate how we should update the weight vector | |
change <- (learningRate * (label[i] - predicted)) * obs[i , ] | |
#Update the weight vector | |
w <- w + as.numeric(change) | |
#Add this error for the total sum of errors for this epoc | |
sumErr <- sumErr + (abs(label[i] - predictedV[i])) | |
} | |
} | |
#Calculate the average error for all epocs | |
avgErr <- (avgErr + (sumErr/n))/2 | |
#Update the number of Epocs | |
epoc <- epoc + 1 | |
} | |
#Print the average error and the number of EPOCS | |
print(paste("Avg Error rate per epoc: ", as.character(avgErr))) | |
print(paste("EPOC: ", as.character(epoc))) | |
#Return the weight vector | |
return(w) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment