<jupyter_start><jupyter_text>Note that in the data, "Sales" column is of factor datatype. We need to change this to numeric in order to use it in our analysis.<jupyter_code># changing "Sales" column to numeric datatype
data$Sales <- as.numeric(as.character(data$Sales))
class(data$Sales)
# converting the data into stationery data
data_differenced = diff(data$Sales, differences = 1)
head(data_differenced)
# creating a supervised dataset 
data_lagged = c(rep(NA, 1), data_differenced[1:(length(data_differenced)-1)])
data_preprocessed = as.data.frame(cbind(data_lagged,data_differenced))
colnames(data_preprocessed) <- c( paste0('x-', 1), 'x')
data_preprocessed[is.na(data_preprocessed)] <- 0
head(data_preprocessed)
# splitting the data into training and testing sets
N = nrow(data_preprocessed)
n = round(N *0.7, digits = 0)
train = data_preprocessed[1:n, ]
test  = data_preprocessed[(n+1):N,]
print("Training data snapshot :")
head(train)

print("Testing data snapshot :")
head(test)
# normalizing the data within the scale of the activation function
scaling_data = function(train, test, feature_range = c(0, 1)) {
  x = train
  fr_min = feature_range[1]
  fr_max = feature_range[2]
  std_train = ((x - min(x) ) / (max(x) - min(x)  ))
  std_test  = ((test - min(x) ) / (max(x) - min(x)  ))
  
  scaled_train = std_train *(fr_max -fr_min) + fr_min
  scaled_test = std_test *(fr_max -fr_min) + fr_min
  
  return( list(scaled_train = as.vector(scaled_train), scaled_test = as.vector(scaled_test) ,scaler= c(min =min(x), max = max(x))) )
  
}


Scaled = scaling_data(train, test, c(-1, 1))

y_train = Scaled$scaled_train[, 2]
x_train = Scaled$scaled_train[, 1]

y_test = Scaled$scaled_test[, 2]
x_test = Scaled$scaled_test[, 1]

# inverse-transform function to revert the predicted values to the original scale
invert_scaling = function(scaled, scaler, feature_range = c(0, 1)){
  min = scaler[1]
  max = scaler[2]
  t = length(scaled)
  mins = feature_range[1]
  maxs = feature_range[2]
  inverted_dfs = numeric(t)
  
  for( i in 1:t){
    X = (scaled[i]- mins)/(maxs - mins)
    rawValues = X *(max - min) + min
    inverted_dfs[i] <- rawValues
  }
  return(inverted_dfs)
}
# Reshaping the input to 3-dimensional
dim(x_train) <- c(length(x_train), 1, 1)

# specifying required arguments
batch_size = 1               
units = 1                     

# defining the model 
model <- keras_model_sequential() 
model%>%
  layer_gru(units, batch_input_shape = c(batch_size, dim(x_train)[2], dim(x_train)[3]), stateful= TRUE)%>%
  layer_dense(units = 1)
summary(model)
# compiling the model
model %>% compile(
  loss = 'mean_squared_error',
  optimizer = optimizer_adam( lr= 0.01, decay = 1e-6 ),  
  metrics = c('accuracy')
)
# training the model
for(i in 1:50 ){
  model %>% fit(x_train, y_train, epochs=1, batch_size=batch_size, verbose=1, shuffle=FALSE)
  model %>% reset_states()
}
# predicting the values for the test dataset
scaler = Scaled$scaler

predictions = vector()

for(i in 1:length(x_test)){
     X = x_test[i]
     dim(X) = c(1,1,1)
     yhat = model %>% predict(X, batch_size=batch_size)
     # invert scaling
     yhat = invert_scaling(yhat, scaler,  c(-1, 1))
     # invert differencing
     yhat  = yhat + data$Sales[(n+i)]
     # store
     predictions[i] <- yhat
}
predictions<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup