Skip to content

Instantly share code, notes, and snippets.

@otobrglez
Last active April 2, 2024 17:51

Revisions

  1. otobrglez revised this gist Aug 7, 2020. 1 changed file with 3 additions and 3 deletions.
    6 changes: 3 additions & 3 deletions jaccard_recommendation.rb
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,6 @@
    #!/usr/bin/env ruby

    # Please read http://otobrglez.opalab.com for more information about this code.
    # Simple Recommendation Engine in Ruby
    # Visit: http://otobrglez.opalab.com
    # Author: Oto Brglez <otobrglez@gmail.com>

    class Book < Struct.new(:title)

  2. otobrglez created this gist Mar 24, 2014.
    67 changes: 67 additions & 0 deletions jaccard_recommendation.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,67 @@
    #!/usr/bin/env ruby

    # Please read http://otobrglez.opalab.com for more information about this code.

    class Book < Struct.new(:title)

    def words
    @words ||= self.title.gsub(/[a-zA-Z]{3,}/).map(&:downcase).uniq.sort
    end

    end

    class BookRecommender

    def initialize book, books
    @book, @books = book, books
    end

    def recommendations
    @books.map! do |this_book|
    this_book.define_singleton_method(:jaccard_index) do @jaccard_index; end

    this_book.define_singleton_method("jaccard_index=") do |index|
    @jaccard_index = index || 0.0
    end

    intersection = (@book.words & this_book.words).size
    union = (@book.words | this_book.words).size

    this_book.jaccard_index = (intersection.to_f / union.to_f) rescue 0.0
    this_book

    end.sort_by { |book| 1 - book.jaccard_index }

    end

    end


    # Usage

    # Load books from this file
    BOOKS = DATA.read.split("\n").map { |l| Book.new(l) }

    # Create initial book
    this_book = Book.new("Ruby programming language")

    # Load recommender
    recommender = BookRecommender.new(this_book, BOOKS)

    # Find recommendations
    recommended_books = recommender.recommendations

    # Show books that match the most
    recommended_books.each do |book|
    puts "#{book.title} (#{'%.2f' % book.jaccard_index})"
    end


    __END__
    Finding the best language for the job
    Could Ruby save the day
    Python will rock your world
    Is Ruby better than Python
    Programming in Ruby is fun
    Python to the moon
    Programming languages of the future