This week we'll talk about how to implement ML on Rails using torch.rb, torchtext-ruby, and gruff in detail.

Changes in procedure this week:
- Dumping of maximum word size (can be found on #1 of the blog post series)

Creating Dataset

Before we start how we created a custom dataset using SerpApi engines, let me clarify one point. Google Local Pack Results are given or taken the same kind as Google Local Results.

Former shows itself in the organic search results page (without using any extra parameters). But they represent the same thing. Their key fields are also the same. So we can train a model for classifying ingredients of Google Local Results, and then use it for Google Local Pack Results.

We decided to use a rake function to create our custom datasets. For that we’ll use a preset JSON file we will parse and then fill using SerpApi.

  "local_results": {
    "title": [],
    "place_id_search": [],
    "thumbnail": [],
    "rating": [],
    "reviews": [],
    "type": [],
    "phone": [],
    "address": [],
    "hours": [],
    "price": [],
    "description": [],
    "place_id": [],
    "lsig": []
  "queries": [
  "params": "engine=google&tbm=lcl",
  "query_parameter": "q"

local_results here represents the type of results, all the keys within it are different keys we extract in Google Local Results.
queries is a set of queries to create the dataset. In this case it contains famous restaurants and coffeehouses in US.
params are relevant parameters in a normal SerpApi Search.
query_parameter represents the parameter key to be used in the search.

Rake command will use the path of the JSON file as an argument to fill it with the relevant data. Each result we get from SerpApi will be checked if its key names are the same with key names within the JSON and then it’ll be added inside the dataset.

Here is an example for Google Local Result and Playground link for the example:

Image of Examples

Loading the Data

We need to create some class variables to be used within the custom data loader and pass some of them to the trainer.

    def initialize(json_file_path)
      @@all_letters = []
      @@data =
      @@data.split('').each {|letter| (@@all_letters << letter) unless @@all_letters.include? letter}
      @@n_letters = @@all_letters.size

@@all_letters is filled with each unique character within the JSON file. This is helpful for creating an index for different kinds of data which we will come in a second.
@@data is the JSON hash of the file we read.
@@n_letters is our dictionary size. It’ll be the size of every unique character used to create our results.

We also need a way to get back our dictionary, and dictionary size in the training module:

    def self.declare_dictionary
      return @@all_letters, @@n_letters

In order to avoid reading and writing issues with special characters, we need to transform them to Unicode:

    def self.to_unicode string
      I18n.transliterate string

We need only the necessary parts we want to extract from @@data to work with it:

    def self.read_from_json
      data = JSON.parse(@@data)
      data = data[data.keys.first]

Each letter needs to be indexed within the dictionary (or alphabet, I use them interchangeably in this context) before we to transform them into tensors.

    def self.letter_to_index letter
      letter = to_unicode(letter)
      @@all_letters.find_index letter
Sorry for the quality of handwriting :)

From there we make tensors out of them with the size (1 x @@n_letters):

    def self.letter_to_tensor letter
      tensor = Torch.zeros(1, @@n_letters)
      tensor[0][letter_to_index(letter)] = 1

Thus each word will be consisting of letter tensors:

    def self.word_to_tensor word
      tensor = Torch.zeros(word.size, 1, @@n_letters)
      word.split('').each_with_index do |letter, index|
        tensor[index][0][letter_to_index(letter)] = 1

Creating The Model

Initialize our model within a class:

    def initialize input_size, hidden_size, output_size
      @hidden_size = hidden_size
      @i2h = + hidden_size, hidden_size)
      @i2o = + hidden_size, output_size)
      @softmax = 1)

We feed the input_size which is …, hidden_size which is …, output_size which is … in our case.

@i2h represents Input to Hidden
@i2o represents Input to Output
@softmax here is the logarithm of softmax function in mathematics. Softmax is a probability distribution. In our case it’ll be the probability distribution of different keys within the SerpApi local results. Key with highest probability will be given as an output.

Here's the visualization of the model:

We need a way to forward the input data within the model.

    def forward input, hidden
      combined = [input, hidden], dim:1)
      hidden =
      output =
      output =
      return output, hidden

We also need a way to initialize hidden layer zero tensor to be filled within the flow.

    def init_hidden
      Torch.zeros(1, @hidden_size)

IV - Training The Model

There are necessary things we must define first. I’ll explain them in detail on next week’s blog post alongside some other details we will conclude. But simply put;

@n_epochs → Number of iterations a.k.a epochs
@print_every → At which rate do we want to print the current situation of the model on the terminal.
@plot_every → At which rate do we want to plot the progress to a graph.
@learning_rate → Learning rate is responsible for the adjustment of weights within a machine learning model. In other words. It needs to be adjusted optimally.

Let me give a semantic example on learning rate:

Let’s assume you are teaching someone how to read. You taught the person the word Scraper, Skipper, Metamorphosis, and Pneumonoultramicroscopicsilicovolcanoconiosis (yes, a real word in English Language), alongside some other words. If you show Scraper, and ask him what this is;

  • If he tells you it is Scraper it is a good learning rate.
    It might tell you that is is something else until it learns. But you’ll recognize a sweet spot of failures, and you’ll still have a hope that this person will learn how to speak.

  • If he tells you it is Skipper it is a low learning rate.
    This means the person is lost in details. Too many similar letters will mean same word to this person.

  • If he tells you it is Metamorphosis, it is a high learning rate.
    The gap in differentiating words is too high for this person. This person is a deductive person now.

  • If he tells you it is Pneumonoultramicroscopicsilicovolcanoconiosis, it is a very high learning rate.
    No way he’s gonna learn.

@n_categories → Number of categories, number of different keys in our case

@n_hidden → Size of Hidden layer. It could be tweaked to get different results. Also you may have different sets of hidden layers in front of each other with different sizes to get different results.

@net → Our Model

@optimizer → Stochiastic Gradient Descent function that is useful for adjusting weights between nodes to come up with an optimized model. Each iteration with positive outcome, match of inputted value, and outputted key in our case, will increase the model’s leniency to go from there given the input is similar, and each iteration with the negative outcome will decrease the model’s leniency to go from there given the input is dissimilar. With enough iteration, model will be optimized.

@criterion → Negative Log Likelihood is a function we use to determine the loss of a model. Loss is useful to observe the optimization of the model throughout different epochs.

  @n_epochs = 1000
  @print_every = 1000
  @plot_every = 1
  @learning_rate = 0.005
  @start = "ml/google/local_pack/data/local_pack_en-us.json"
  @all_letters, @n_letters = DataTools.declare_dictionary
  @data = DataTools.read_from_json
  @all_categories = @data.keys
  @n_categories = @data.keys.size
  @n_hidden = 128

  @net =, @n_hidden, @n_categories)
  @optimizer =, lr: @learning_rate)
  @criterion =
  @current_loss = 0
  @all_losses = []

Now that we declared our necessary variables, let’s take a look at other functions we need.

This function is responsible for giving the highest possible output and its index within all categories:

  def self.category_from_output output
    top_n, top_i = Torch.topk(, 1)
    category_i = top_i[0].item
    return @all_categories[category_i], category_i

This function is responsible for picking a random value from an array:

  def self.random_choice arr
    max = arr.size - 1

This function is responsible for creating random training pairs. It picks a random category (key names in our case), picks a random word from that category, translates both of them into tensors and returns it. You can consider it as creating a random pop-quiz for the model.

  def self.random_training_pair
    category = random_choice(@all_categories)
    word = random_choice(@data[category])
    category_tensor = Torch.tensor([@all_categories.index(category)],dtype: :long)
    word_tensor = DataTools.word_to_tensor word
    return category, word, category_tensor, word_tensor

This function is responsible for one epoch of training. It takes the category tensor and word tensor we created randomly, initiates a hidden layer, zeroes out the gradients (to keep it in buffers instead of overwriting), and then calls each letter tensor of the word tensor within the model. Output from that interaction is then used for measuring the loss of the epoch. Backward propagation is activated to accumulate buffers and then single optimization step is taken. Predicted output and the loss of the epoch are returned.

  def self.train category_tensor, word_tensor
    hidden = @net.init_hidden


    (0..word_tensor.size.first-1).each do |index|
      @output, hidden =[index], hidden)
    loss =, category_tensor)

    return @output,

We also need a way to measure time for the overall process. It seems unimportant. But the training time of the model is truly one of the key features in scaling it.

  def self.time_since since
    now =
    seconds = now - since
    minutes = (seconds / 60).floor
    seconds = seconds - (minutes * 60)
    "#{minutes} minutes #{seconds} seconds"

This next part is the brain of our training process where the data is trained. We train the model @n_epochs times. To calculate success rate, we’ll pass total_passed variable which’ll increase with each positive outcome.

At each epoch, we create a random training pair, train the model one time, get the current loss of our model, and check if the prediction is correct. Success rate will be created to measure the success of the model with the state of prediction. We’ll print the results at every @print_every. We’ll plot at every @plot_every to plot loss over epochs, and success rate over epochs.

  def self.iterate_epochs
    total_passed = 0
    success_rates = []
    (1..(@n_epochs+1)).each do |epoch|
      category, word, category_tensor, word_tensor = random_training_pair
      output, loss = train category_tensor, word_tensor
      @current_loss = @current_loss + loss

      guess, guess_i = category_from_output output
      state = guess == category ? "Passed" : "Failed"

      if state == "Passed"
        total_passed = total_passed + 1
      success_rate = 100*(total_passed.to_f / epoch.to_f).round(6)

      if epoch % @print_every == 0
        puts "\n |Epoch: #{epoch} |\n "\
             "|Progress: %#{((epoch.to_f / @n_epochs.to_f).round(6))*100} |\n "\
             "|Time: #{time_since(@start)} |\n "\
             "|Loss: #{loss} |\n "\
             "|Guessed Value: #{word} |\n "\
             "|Guessed Field: #{guess} |\n "\
             "|Status: #{state} |\n "\
             "|Success Rate: %#{success_rate} |\n"\

      if epoch % @plot_every == 0
        @all_losses.append(@current_loss / @plot_every)
        @current_loss = 0

    plot_line_loss =
    plot_line_loss.title = "Loss over #{@n_epochs} Epochs (At Every #{@plot_every} Epoch)" :Loss, @all_losses

    plot_line_sr =
    plot_line_sr.title = "Succress Rate(%) over #{@n_epochs} Epochs (At Every #{@plot_every} Epoch)" :Success, success_rates

We’ll also need to save the current state of the model to a file in order to use it:

  def self.save_model, "ml/google/local_pack/predict_value/trained_models/rnn_value_predictor.pth")

Example Results

Note that the results here are not conclusive. This is a model trained with 1000 epochs (fairly low). Thus, these results are only to show the functionality of the implementation.

Here is an example of a printed result:

 |Epoch: 1000 |
 |Progress: %100.0 |
 |Time: 0 minutes 5.2206950187683105 seconds |
 |Loss: 2.568265676498413 |
 |Guessed Value: Permanently closed |
 |Guessed Field: title |
 |Status: Failed |
 |Success Rate: %27.900000000000002 |

Here is an example of Success Rate over Epochs:

As you can see, with enough training, it seems like it can get to a state where it’ll predict overwhelming majority of the inputs correctly.

Here is an example of Loss over Epochs:

As you can see, low level of training is exposing oscillation within the loss. However trend seems to be healthy.


I am grateful for the incredible support I took from SerpApi team in crucial parts of the implementation. Also, I’m grateful for the creator and maintainer of gems we used to make this possible, and PyTorch for their incredible documentation.

Next week, I’ll go deeper into the explanations of the model, make some tweaks in it, and share the comparative results. Thanks for reading.