Предобработка и загрузка данных

На данном этапе работы были сделаны:

*Корреляционный анализ

Цель: Выявление закономерностей в данных, который были использованы при построении систем content-based и collaborative filtering.

Конечно, не все гипотезы оправдали надежды, но были выявлены интересные факты почти в каждой части разведывательного анализа.

Количественные распределения

 Мы решили обратить особенное внимание на переменные, которые являются типичными для данного датасета, в частности, на распределение комиксов на печатные и электронные издания.

 Не трудно заметить, что абсолютное большинство комиксов печатные

 Рассмотрим, есть ли содержательная закономерность в распределении электронных книг в зависимости от года.

 Как мы видим из графика, изображенного выше, электронные издания наблюдаются без какой-ли закономерности. Однако мы можем отметить, что достаточно большое количество комиксов электронного формата занесены в датасет без указания года издания.

 Важным фактором при выборе литературы является язык написания. Из данного распределения количеств книг, написанных на различных языках, можно заметить, что более 2/3 всех книг написаны на английском языке.

goodread_comics %>% count(language_code) %>% ggplot(aes(reorder(language_code, n), n, fill = reorder(language_code, n))) + geom_bar(stat='identity') + coord_flip()+ guides(fill = FALSE)

 Давайте посмотрим, есть ли разлчичия в средних рейтингах книг, написанных на разных языках:

Во-первых, сделаем это с помощью аналога теста ANOVA для неномрально распределенных выборок - тест Краскела-Уоллиса. Заметим, что различия значимы по двум выборкам(joined_df, goodread_comics)

kruskal_test(average_rating~as.factor(language_code), data = goodread_comics)
## 
##  Asymptotic Kruskal-Wallis Test
## 
## data:  average_rating by
##   as.factor(language_code) (, ara, cze, en-CA, en-GB, en-US, eng, fre, ind, ita, jpn, spa)
## chi-squared = 41.557, df = 11, p-value = 1.932e-05
kruskal_test(rating~as.factor(language_code), data = joined_df)
## 
##  Asymptotic Kruskal-Wallis Test
## 
## data:  rating by
##   as.factor(language_code) (, ara, cze, en-CA, en-GB, en-US, eng, fre, ind, ita, jpn, spa)
## chi-squared = 137.16, df = 11, p-value < 2.2e-16

Во-вторых, построим ящичковую диаграмму для того, чтобы посмотреть на то, в какую сторону наблюдаются эти различия

ggplot(data = goodread_comics)+geom_boxplot(mapping = aes(x = as.factor(language_code), y=as.numeric(average_rating)), na.rm =T) + labs(title = "", x = "Язык издания", y = "Рейтинг") + theme_bw() + theme(text = element_text(size=10), axis.text.x = element_text(angle=40, hjust=1), plot.background = element_rect())

 Следующим шагом мы решили рассмотреть распределение оценок пользователей для фильмов на основании датасета с их отзывами. В нашем случае, оценки наиболее всего напоминают хи-квадрат распределение со скошенностью влево. Из этого мы можем сделать вывод, что в отзывах преобладают положительные оценки. Причем, наблюдаются крайне небольшое количество оценок 1-2. По нашему преположению, это может быть связано с тем фактом, что люди склонны отмечать в не слишком понравившемся комиксе его положительные стороны, а оценкой 0-1 награждать только те комиксы, которые им не понравились в корне.

 Естественно, имеет смысл посмотреть на то, распределение количеств отзывов пользователей. Для начала мы решили посмотреть, какой процент пользователей оставил 1-2 отзыва.

##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    1.00    1.00    3.00    8.21    8.00  116.00
## [1] 0.4720932

 К нашему удивлению оказалось, что такие пользователи составляют более 47% от всех людей, поставивших оценку. Сейчас речь идет о goodread_reviews. Изначально мы хотели удалить таковых пользователей, так как для них не будет работать user-based коллаборативная система рекомендаций. Однако пока что мы их оставим, но будем иметь в виду данный факт.

 Посмотрим также на вcю картину распределения, исключив из нее юзеров, поставивших меньше 3 отзывов. (Об их количестве в общей массе мы и так знаем достаточно).

 Как видно из графика ниже, наблюдается достаточно мало пользователей, поставивших больше 15 оценок. Однако наблюдаются “комиксоманы”, которые поставили более 40 оценок. Рекордсменом в данном высчтупил пользователь, поставивший 116 оценок

 Построив график распределения оценок к одной книге, можем заметить, что в данной выборке нет книг, которые были оценены более чем 50 раз. В генеральной совокупонсти (стобец ratings_count),очевидно, большие значениям, но мы работает с выборкой и по этой причине решил рассмотреть именно данное распрделение.

Корреляционный анализ

На данном этапе работы, мы хотим определить те количественные переменные, которые каким-то образом влияют на средний рейтинг комиксов, и отобрать их при построении content-based системы

Для получения тех графиков, что мы хотим построить нам нужна была функция для расчета корреляции (не та, что есть в готовых библиотеках). Написав данную функцию, мы перешли к анализу связей меджду средним рейтингом и переменными (ratings_count, num_pages,series).

Давайте перейдём к более детальному анализу этих переменных.

  1. Связь между рейтингом и количеством оценок (на платформе goodreads)

Первое, что явно бросатается в глаза – сосредоточенность наблюдений ближе к оси ординат и выбросы, которые икажают линию регрессии и значение корреляции. По этой причине, требуется проверка значимости корреляции между этими переменными с помощью коэффициента ранговой корреляции Кендалла.

## 
##  Shapiro-Wilk normality test
## 
## data:  goodread_comics$ratings_count
## W = 0.37002, p-value < 2.2e-16
## 
##  Shapiro-Wilk normality test
## 
## data:  goodread_comics$average_rating
## W = 0.97888, p-value = 1.189e-06

Можем заметить, что значение этого коэффициента равно 0,3 на уровне значимости 1%. Следовательно, можем сделать вывод о наличии слабой связи.

Вообще, похожая ситуация наблюдается во всех трёх случаях. Низкие значения коэффициент Кендалла и искаженные выбросами значения коэффициентов корреляции.

cor.test(goodread_comics$ratings_count, goodread_comics$average_rating, method = "kendall")
## 
##  Kendall's rank correlation tau
## 
## data:  goodread_comics$ratings_count and goodread_comics$average_rating
## z = 10.021, p-value < 2.2e-16
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
##       tau 
## 0.3006664
  1. Связь между количеством страниц и средним рейтингом

Коэффициент Кендалла равен 0.18 -> очень слабая связь

shapiro.test(goodread_comics$num_pages)
## 
##  Shapiro-Wilk normality test
## 
## data:  goodread_comics$num_pages
## W = 0.73533, p-value < 2.2e-16
shapiro.test(goodread_comics$average_rating)
## 
##  Shapiro-Wilk normality test
## 
## data:  goodread_comics$average_rating
## W = 0.97888, p-value = 1.189e-06
cor.test(goodread_comics$num_pages, goodread_comics$average_rating, method = "kendall")
## 
##  Kendall's rank correlation tau
## 
## data:  goodread_comics$num_pages and goodread_comics$average_rating
## z = 5.5865, p-value = 2.317e-08
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
##       tau 
## 0.1799732
  1. Связь между количеством серий и средним рейтингом

Коэффициент Кендалла равен 0,28 ->слабая связь

shapiro.test(goodread_comics$series)
## 
##  Shapiro-Wilk normality test
## 
## data:  goodread_comics$series
## W = 0.59112, p-value < 2.2e-16
shapiro.test(goodread_comics$average_rating)
## 
##  Shapiro-Wilk normality test
## 
## data:  goodread_comics$average_rating
## W = 0.97888, p-value = 1.189e-06
cor.test(goodread_comics$series, goodread_comics$average_rating, method = "kendall")
## 
##  Kendall's rank correlation tau
## 
## data:  goodread_comics$series and goodread_comics$average_rating
## z = 6.9237, p-value = 4.4e-12
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
##       tau 
## 0.2804373

Давайте теперь посмотрим на то, как отличаются рейтинги серийных и единичных комиксов. Есть заметная разница в медианах - у серийных комиксов рейтинг в выше, но надо оценить значимость этого различия.

ggplot(data = goodread_comics)+geom_boxplot(mapping = aes(x = as.factor(tseries), y=as.numeric(average_rating)), na.rm =T) + labs(title = "", x = "Наличие томов", y = "Рейтинг") + theme_bw() + theme(text = element_text(size=10), axis.text.x = element_text(angle=40, hjust=1), plot.background = element_rect())

По резульатам t-test можно сделать вывод о значимости этого различия

t.test(average_rating~tseries, goodread_comics)
## 
##  Welch Two Sample t-test
## 
## data:  average_rating by tseries
## t = -5.2119, df = 295.18, p-value = 3.518e-07
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
##  -0.2530962 -0.1143480
## sample estimates:
##  mean in group no mean in group yes 
##          3.820248          4.003971

Корреляционная матрица

Можно заметить отрицательную корреляцию между годом и рейтингом

tmp <- goodread_comics %>% 
  select(one_of(c('average_rating', 'num_pages','ratings_count','publication_year','series'))) %>% 
  as.matrix()
corrplot(cor(tmp, use = 'pairwise.complete.obs'), type = "lower")

Исходя из коэффициента Кендалла, можно сделать вывод о наличии слабой связи

added_dates = joined_df$date_added %>%  str_extract_all(' [[:digit:]]{4}')
joined_df$added_date = added_dates
cor.test(goodread_comics$publication_year, goodread_comics$average_rating, method = "kendall") #связи толком нет 
## 
##  Kendall's rank correlation tau
## 
## data:  goodread_comics$publication_year and goodread_comics$average_rating
## z = -3.4262, p-value = 0.000612
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
##        tau 
## -0.1109071

Сетевой анализ

Сеть 1 (по косинусному расстоянию)

Построим первую сеть на основе косинусного расстояния по матрице оценок “realRatingMatrix”.

Принцип работы написанного кода достаточно понятен на интуитивном уровне, но стоит описать один момент:

Подготовим параметры (сообщества, размеры вершин)

fgcommune <- fastgreedy.community(ggg)
mod  = modularity(fgcommune)
size = degree(ggg)
V(ggg)$size = log(size+1)+6
names = V(ggg)$name
V(ggg)$name = ifelse((V(ggg)$size > quantile(V(ggg)$size, 0.999)),names , NA)
last_membership = membership(fgcommune)

Далее, мы решили визуализировать, построенный граф с помощью методов из пакета “igraph” и параметров из предыдущего пункта.

Можем заметить, что сообществ у нас 115 - это не очень хорошо, учитывая то, что есть очень много комиксов без связей. Кроме этого, значение модулярности до 0,4 не является высоким индикатором.

Проверим значения ассортативности по различным переменным и заметим, что эти ассортативности мень 0.1 и можем сделать вывод об отсутствии склонности основания связей на основании этих переменных даже без проверки статистической значимости.

## [1] 0.07018977
## [1] 0.02216209
## [1] 0.07438533

Вывод по первой сети:

#Сетевой анализ 2

В прошлом домашнем задании была дана сеть с похожими переменными и даннымы, мы решили воспользоваться данными из той сети

  1. Загрузили данные

  2. Некоторыми нехитрыми преобразованиями получили общие книги проектного датасета и сети из ДЗ.(таких книг оказалось 56 штук ~10%)

Оценка значимости

g = newcomics
number_of_permutations = 2000
assortativity_shuffled  <- rep(NA, number_of_permutations)
for(i in 1:number_of_permutations){
  V(g)$attr_shuffled = sample(V(g)$publisher, replace = F)
  assortativity_shuffled[i] = assortativity_nominal(g,as.factor(V(g)$attr_shuffled))
}
assortativity_real = assortativity_nominal(g, as.factor(V(g)$publisher), directed = T)

p-value = 0 -> статистически значимое значение ассортативности

pvalue = sum(abs(assortativity_shuffled) >= abs(assortativity_real)) / number_of_permutations
pvalue
## [1] 0

Исходя из наблюдений ассортативности можем сделать предположение о том, что можно построить сеть на основе издательств(publisher) и подготовим переменные.

## [1] 2368

Нарисуем данный граф и заметим, что он состоит из подгрупп, которые непосредственно относятся к издательствам. Значение модулярности равно 0,76, что является достаточно высоким показателем для утверждения о качественности разбиения, но мы так не думаем.

Посмотрим на распредление значений центральности и заметим, что максимальное количество связей - 74.

summary(degree(ggg))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    0.00    2.00   28.00   30.75   65.00   74.00

Анализ тональностей по PMI

Хотим изучить переменную description для того, чтобы понять, как устроены описания книг - какие слова словосочетания характеризуют определенную тональность. По этой причине, сначала обработаем данные(приведём к поддающемуся к анализу виду).

Построим график биграмм по показатеою PMI и заметим, какие словосочетания характеризуют определенные уровни тональности.

rating_df = joined_df %>% group_by(book_id) %>% summarize(avgRat = mean(rating))
goodread_comics = rating_df %>% inner_join(goodread_comics)
positive = reviews.bifiltered %>%
  filter(book_id %in% goodread_comics$book_id[goodread_comics$avgRat>4]) %>% 
  mutate(sent = "positive")
#можно дополнительно отфильтровать по полезности отзыва (stars == 5)
negative = reviews.bifiltered %>%
  filter(book_id %in% goodread_comics$book_id[goodread_comics$avgRat<3]) %>% 
  mutate(sent = "negative")
reviews.pmi = bind_rows(positive, negative) %>% dplyr::select(words,book_id ,sent)
reviews.pmi = reviews.pmi %>% 
  dplyr::count(words ,sent) %>% 
  pivot_wider(names_from = sent, values_from = n, values_fill = 0)
freq_p = reviews.pmi$positive
freq_n = reviews.pmi$negative
sum_p = sum(reviews.pmi$positive) 
sum_n = sum(reviews.pmi$negative) 
pmi_p = log((freq_p/sum_p)/((freq_p+freq_n)/(sum_p+sum_n)*sum_p/(sum_p+sum_n))+1)
reviews.pmi$PMI_p = pmi_p
pmi_n = log((freq_n/sum_n)/((freq_p+freq_n)/(sum_p+sum_n)*sum_n/(sum_p+sum_n))+1)
reviews.pmi$PMI_n = pmi_n

reviews.pmi %>% 
  ggplot(aes(x=log(positive+negative), y=PMI_p-PMI_n, color=5*PMI_p-PMI_n, label=words)) +
  scale_color_gradient2(low="red", high="blue") +
  geom_text(check_overlap = TRUE)

Найдем наиболее частые слова, которые попадаются в описаниях комиксов, перед этим исключив стоп-слова. Взглянем на получившиеся слова. Слова не дают особо зацепок, так как все они относятся к типичным описаниям сюжетов из комиксов.

##      words  n
##  1:   take 99
##  2: series 92
##  3:    now 89
##  4:  story 89
##  5:  first 83
##  6:   good 81
##  7:  comic 80
##  8:   time 78
##  9:   make 71
## 10:   just 70
words n
take 99
series 92
now 89
story 89
first 83
good 81
comic 80
time 78
make 71
just 70

Разделим часто повторяющиеся слова на две категории - те комиксы, которые получили оценку 4 и выше, и те, которые получили оценку менее 3.5. Таким образом мы четко разграничим любимчиков от тех, которые больше тянут на оценку 3. Мы получили два списка слов, однако некоторые слова попали сразу в оба списка. Выделим такие слова в отдельную группу и исключим их из конечных списков.

#резделяем слова для хороших и плохих отзывов

words_descrip_good = description_tokens %>% filter(average_rating > 3.99)
words_descrip_good = words_descrip_good %>% dplyr::count(words, sort = TRUE)
words_descrip_good = filter(words_descrip_good, n > 4)


words_descrip_bad = description_tokens %>% filter(average_rating < 3.5)
words_descrip_bad = words_descrip_bad %>% dplyr::count(words, sort = TRUE)
words_descrip_bad = filter(words_descrip_bad, n > 3)
#слова которые попали в оба списка
join_bad_good_words = inner_join(words_descrip_bad,words_descrip_good, by ="words")
#уберем повторяющиеся слова
anti_words_descrip_bad= anti_join(words_descrip_bad,join_bad_good_words, by ="words" )
anti_words_descrip_good= anti_join(words_descrip_good,join_bad_good_words, by ="words" )

Посмотрим на топ 15 слов по хорошим и по плохим комиксам. Из получившихся слов можем предположить,что Лига Справедливости не особо нравится людям (из-за слова Juctice, хотя возможен вариант что просто комиксы про справедливость меньше нравятся людям) , как и комиксы про аквамена,халка, женщину-кошку и инопланетян. Высокие оценки получили комиксы со словом “york” в описании - что можно объяснить двумя способами. Возможно, журнал New York Times хорошо оценивал этот комикс, что было указано в описании. Либо же действия комикса проиходят в самом Нью-йорке. По остальным словам затруднительно сказать что-то конкретное.

Good Bad
discover captain
school league
day apocalypse
york carol
may horror
true justice
help alien
start aquaman
thing catwoman
battle corner
turn crisis
boy fantastic
finally hulk
force mission
right ringside

Попробуем провести такой же анализ но для биграм. Возможно, он покажет что-то интересное.

#делаем биграмы с двойной фильтрацией для Описаний
description.bigrams = eng_df%>% 
unnest_tokens(bigram, description, token = "ngrams", n = 2)

description.bifiltered = description.bigrams %>% 
separate(bigram, c("word1", "word2"), sep = " ") %>% 
dplyr::filter(!word1 %in% enstopwords$words) %>% 
dplyr::filter(!word2 %in% enstopwords$words) 
description.bifiltered = description.bifiltered %>% unite("bigram", word1:word2, sep = ' ' , remove = FALSE)
description.bigrams_counts = description.bifiltered %>% dplyr::count(bigram, sort = TRUE)
#резделяем биграмы для хороших и плохих отзывов
bigrams_descrip_good = description.bifiltered %>% filter(average_rating > 3.99)
bigrams_descrip_good = bigrams_descrip_good %>% dplyr::count(bigram)
bigrams_descrip_good = filter(bigrams_descrip_good, n > 3)


bigrams_descrip_bad = description.bifiltered %>% filter(average_rating < 3.5)
bigrams_descrip_bad = bigrams_descrip_bad %>% dplyr::count(bigram)
bigrams_descrip_bad = filter(bigrams_descrip_bad, n > 2)


#биграмы которые попали в оба списка
join_bad_good = inner_join(bigrams_descrip_bad,bigrams_descrip_good, by ="bigram")
#уберем повторяющиеся биграмы
anti_bigrams_descrip_bad= anti_join(bigrams_descrip_bad,join_bad_good, by ="bigram" )
anti_bigrams_descrip_good= anti_join(bigrams_descrip_good,join_bad_good, by ="bigram" )

Биграмы показывают, что комиксы, описания которых содержат фразы “Нью-Йорк Таймс Бестселлер” - более высоко оценены. Опять же, это не удивительно. Журнал Таймс часто делает ревью для наиболее успешных или же имеющих потенциал произведений, а возможно и освещает произведения высоко оцененные критиками. Лига Справедливости в очередной раз попала в “плохие” комиксы.Также туда попала Фантастическая Четверка, Зеленый Фонарь, Капитан Марвел, поджанр комиксов “Лавкрафтовские ужасы”, серия комиксов “Супермен/Бетмен” и другие.

Good Bad
new york captain marvel
last man justice league
york time final crisis
year ago chill tale
yes yes green lantern
critically acclaim collect captain
final volume fantastic four
york timesbestselling great hero
dark knight greg pak
dave gibbon lovecraftian horror
eisner award superman batman
high school twilight zone

Пропорциональное соотношение плохих и хороших слов

На данном этапе выделил хорошие и плохие из словаря ‘bing’, и каждому описанию присвоили пропорциб хороших слов.

Коллаборативная фильтрация

goodread_reviews =goodread_reviews%>% select(book_id, user_id, rating)
user_item = goodread_reviews %>%
  pivot_wider(names_from = book_id,values_from = rating) %>%
  as.data.frame()
rownames(user_item) = user_item$user_id
user_item$user_id = NULL
user_item = as.matrix(user_item)

функция для рекомендации CF

 Для того, чтобы описать функцию, удобнее всего визализировать то, каким образом она выбирает решение для каждого отдельного пользователя, включая нового.
A caption

A caption

 Однако перейдем непосредственно к функции,а не вопросам, которые она задает пользователю для определения некоторых параметров.

 Функция состоит из 3 критериев, с помощью которых нам удается определить, какой из способов рекомендации был бы оптимален для конкретного пользователя.

 1 тип: Пользотель у котрого более 10 рекомендаций.

 Для такого пользователя мы выдаем рекомендацию по средствам UBCF. Мы посчитали, что 10 - достаточное количество отзывов, которое позволит нам определить другого пользователя похожего на данного достаточно точно.

 2 тип: Пользователь у которого менее 10 оценок, но среди них есть оценки выше 3, то есть 4 и 5, которые можно расценивать как позитивные.

 Для этого вида пользователей мы спользуем IBCF применительно к комиксам, которые получили оценки 4 и 5. (Мы не можем достаоверно определить является ли оценка 4 положительной, ввиду того, что люди порой имеют достаточно необычные внутринние шкалы оценивания, однако в целом оценка 4 является индикатором позитивного впечатления).

 3 тип: Пользователь не относящийся ни к одному из выше описанных.

 Что можно сказать о человеке, который оценил 1 фильм и это единственному фильму поставил 2? Пока что ничего, ведь мы совсем знаем предпочтения данного пользователя. Выход из этой ситуации один - порекомендовать топ. Проверка показала, что этот вариант работает значительно лучше, чем рандом.

user_recommendation_col=function(user_ID, quantity, review_matrix=goodread_reviews, n_recom = 20, user_item_matrix = user_item,
                               ratings_matrix = goodread_reviews,
                               n_recommendations = 20,
                               threshold = 1,
                               nearest_neighbors = 20){
  ###################################### 1111
  cos_similarity = function(A,B){
  num = sum(A *B, na.rm = T)
  den = sqrt(sum(A^2, na.rm = T)) * sqrt(sum(B^2, na.rm = T)) 
  result = num/den

  return(result)
  
if(count(goodread_reviews%>% filter(user_id == user_ID))>10){
  user_index = which(rownames(user_item_matrix) == user_ID)

  
}
  
  similarity = apply(user_item_matrix, 1, FUN = function(y) 
                      cos_similarity(user_item_matrix[user_index,], y))

  similar_users = tibble(user_id = names(similarity), 
                               similarity = similarity) %>%
    filter(user_id != user_ID) %>% 
    arrange(desc(similarity)) %>%
    top_n(nearest_neighbors, similarity)


  readed_books_user = ratings_matrix$book_id[ratings_matrix$user_id == user_ID]

  recommendations = ratings_matrix %>%
    filter(
      user_id %in% similar_users$user_id &
      !(book_id %in% readed_books_user)) %>%
    group_by(book_id) %>%
    summarise(
      count = n(),
      rating = mean(rating)
    ) %>%
    filter(count > threshold) %>%
    arrange(desc(rating), desc(count)) %>%
    head(n_recommendations)
recommendations= recommendations%>% left_join(goodread_comics)%>% select(title, average_rating, book_id)  

######    1.2

  rates = pivot_wider(goodread_reviews, names_from = book_id, values_from = rating)
userNames = rates$user_id
rates = select(rates, -user_id)
rates = as.matrix(rates)
rownames(rates) = userNames
  r = as(rates, "realRatingMatrix")
  
ratings_comics <- r[rowCounts(r) > 5, colCounts(r) > 10] 
set.seed(100)
test_ind <- sample(1:nrow(ratings_comics), size = nrow(ratings_comics)*0.2)
recc_data_train <- ratings_comics[-test_ind, ]
recc_data_test <- ratings_comics[test_ind, ]
recc_model <- Recommender(data = recc_data_train, method = "IBCF")
model_details <- getModel(recc_model)

recc_predicted <- predict(object = recc_model, newdata = recc_data_test, n = 20)
  recc_user <- recc_predicted@items[[user_ID]]
  comics_user <- recc_predicted@itemLabels[recc_user]
  
  comics_user_1 =  data.frame(list(comics_user))
  names(comics_user_1) <- 'book_id'
  comics_user_1$book_id <- as.numeric(comics_user_1$book_id)
  comics_user_1 = comics_user_1%>% left_join(goodread_comics)%>% select(title, book_id, average_rating)%>% arrange(desc(average_rating))
  
v = comics_user_1%>% inner_join(recommendations)
p = comics_user_1%>% full_join(recommendations)%>% arrange(desc(average_rating))%>% select(title, book_id, average_rating)
v = v%>% full_join(p[1:quantity- nrow(v),]) %>% arrange(desc(average_rating))
  
  return(v)}
 
 #########################222222222222222222222222222222
  
  
grades = (goodread_reviews%>% filter(user_id == user_ID))$rating
if(count(goodread_reviews%>% filter(user_id == user_ID))<=10   & max(grades)>3){

item_recommendation = function(book_ID, rating_matrix = user_item, n_recommendations = 5){

  book_index = which(colnames(rating_matrix) == book_ID)

  similarity = apply(rating_matrix, 2, FUN = function(y) 
                      cos_similarity(rating_matrix[,book_index], y))

  recommendations = tibble(book_id = names(similarity), 
                               similarity = similarity) %>%
    filter(book_id != book_ID) %>% 
    top_n(n_recommendations, similarity) %>%
    arrange(desc(similarity)) 
    return(recommendations)}
  
k = goodread_reviews%>% filter(user_id == user_ID)%>%filter(rating>=4)  
m = k$book_id
use = data.frame(matrix(ncol = 2, nrow = 0))
colnames(use) <- c('book_id', 'similarity')
use$book_id= as.character(use$book_id)

for (i in 1:length(k$book_id)){
  print(i)
  recom_cf_item = item_recommendation(m[i])
  use = use%>%full_join(recom_cf_item)
}

uses = use%>%arrange(desc(similarity))%>%filter(similarity>0.2)
answer = uses[1:quantity,] 
goodread_comics$book_id = as.character(goodread_comics$book_id)
answer = answer%>%left_join(goodread_comics)%>%select(book_id, average_rating, title)%>% arrange(desc(average_rating))

if (length(answer)<quantity)
   {
   additional_data = goodread_comics%>%arrange(desc(average_rating))%>%filter(ratings_count >1000)%>%select(book_id, average_rating, title)
   add_rows = quantity - length(answer)
   additional_data = additional_data[1:add_rows]
   answer = answer%>% full_join(additional_data)%>% arrange(desc(average_rating))%>% select(book_id, average_rating, title)
   answer =  answer[1:quantity,]
   answer = unique(answer)
 return(answer)} 

if (length(answer)==quantity)
  {
  return(answer)
  }

return(answer)}

 ############################################## 3333
  if (count(goodread_reviews%>% filter(user_id == user_ID))<=10 & max((goodread_reviews%>% filter(user_id == user_ID))$rating)<4 ){
    woon = goodread_comics%>%arrange(desc(average_rating))%>%filter(ratings_count >1000)%>%select(book_id, average_rating, title)
  woon = woon[1:quantity,]
  return(woon)}

}

Оценивание рекомендации:

Итак, расмотрим пользователя 08d805375530cc208801531ca7fdefbc. Он оценил 19 комиксов. Только один комикс был оценен на 5 - Hawkeye #19, от издательства Marvel. Еще 8 комиксов были оценены на четверку - от издательств Dark Horse Comics, Image Comics, Marvel Comics, TokyoPop.

Пользователь предпочитает комиксы 2002-2016 года выпуска, различных издательств.Также он в основном читает хорроры, но нельзя сказать что все они ему нравятся. Два раза встречается манга, одна с оценкой в 4, другая - 3. Также присутствует фентези.

## # A tibble: 19 x 9
##    title rating average_rating publisher publication_year popular_shelves…
##    <chr>  <dbl>          <dbl> <chr>                <dbl> <chr>           
##  1 Hawk…      5           4.49 "Marvel …             2014 comics          
##  2 Chob…      4           4.06 "TokyoPo…             2002 manga           
##  3 The …      4           4.33 "Image C…             2010 to-read         
##  4 Wint…      4           4.02 "Marvel …             2013 to-read         
##  5 Saga…      4           4.56 "Image C…             2013 to-read         
##  6 The …      4           4.21 "Image C…             2013 to-read         
##  7 Wint…      4           3.82 "Marvel"              2014 to-read         
##  8 Harr…      4           4.05 "Dark Ho…             2015 to-read         
##  9 The …      4           3.76 "Image C…             2016 to-read         
## 10 The …      3           4.43 ""                    2007 to-read         
## 11 Y: T…      3           4.39 "Vertigo"             2009 to-read         
## 12 Sale…      3           3.5  "Walker …             2009 to-read         
## 13 Neon…      3           3.4  "Avatar …             2011 to-read         
## 14 Star…      3           4.19 "NBM Pub…             2011 to-read         
## 15 The …      3           4.17 "Image C…             2012 to-read         
## 16 Youn…      3           4.26 "Marvel"              2014 to-read         
## 17 Saga…      3           4.46 "Image C…             2014 graphic-novels  
## 18 Saga…      3           4.43 "Image C…             2015 to-read         
## 19 The …      2           3.47 "Bloomsb…             2009 to-read         
## # … with 3 more variables: popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>

Посмотрим, что порекомендовала функция.

Положительные результаты по рекоммендации:

1.Годы комиксов подходят под предпочтения пользователя

2.Издатель - Image Comics, который относительно неплохо оценивался пользователем, составил половину рекомендаций

3.Категории перекликаются с предпочтениями пользователя, например, там есть комиксы манга, хоррор, фэнтази

4.В рекомендациях есть логика - функция рекомендует комиксы той же серии, что положительно оценил пользователь. Например, Saga, Vol. 2 была оценена им на 4 - функция порекомендовала продолжение - 4 и 5 серию комикса, а также Saga: Book Two.

Рекомендация, которая показалась странной, это “The Complete Peanuts, Vol. 6: 1961-1962”. Во-первых, категория комикса - humor. Также, графика совсем отличается от той, что предпочитает пользователь.

Content-based рекомендация

####Принцип работы функции getBooks()

Для существующего в базе пользователя:

Для нового пользователя:

Предобработка переменных и

## # A tibble: 501 x 353
##    book_id authors.0.autho… authors.1.autho… average_rating publication_year
##      <dbl>            <dbl>            <dbl>          <dbl>            <dbl>
##  1    9526             6238          3141986           3.82             2006
##  2   13578             8476           362098           4.28             2006
##  3   13579             8476           362098           4.3              2007
##  4   16997             5363            10309           3.91               NA
##  5   21325            12444            55811           4.29             2004
##  6   22339          1221698            12726           4.21             1997
##  7   22373            12732           783790           3.58             1998
##  8   29497            16589            16591           3.95             2003
##  9   33486             7338            18832           4.2              2005
## 10   43718            12772           106526           4.2                NA
## # … with 491 more rows, and 348 more variables: series <dbl>, prp_pos <dbl>,
## #   Pantheon <dbl>, `Del Rey` <dbl>, `NA` <dbl>, Vertigo <dbl>, `DC Comics
## #   Vertigo` <dbl>, TokyoPop <dbl>, `Dark Horse Books` <dbl>, `Three Rivers
## #   Press` <dbl>, Fantagraphics <dbl>, `Marvel Comics Group` <dbl>,
## #   Wildstorm <dbl>, `Titan Books (UK)` <dbl>, `Warp Graphics` <dbl>, `Image
## #   Comics` <dbl>, `Dark Horse` <dbl>, `DC Comics` <dbl>, Marvel <dbl>,
## #   Graphix <dbl>, `Oni Press` <dbl>, Asterix <dbl>, `Fantagraphics
## #   Books` <dbl>, `Dark Horse Comics` <dbl>, `Katherine Tegen Books` <dbl>,
## #   `VIZ Media, LLC` <dbl>, `First Second` <dbl>, WildStorm <dbl>, `Studio
## #   Foglio` <dbl>, `Random House Children's Books` <dbl>, `ADV Manga` <dbl>,
## #   `Dark Horse Manga` <dbl>, `Harper Paperbacks` <dbl>, HarperCollins <dbl>,
## #   `VIZ Media LLC` <dbl>, `Bloomsbury Children's Books` <dbl>, `Image Comics /
## #   Aria Press` <dbl>, Titan <dbl>, `Seven Stories Press` <dbl>, `Jiang Tan She
## #   / Kodansha` <dbl>, `Tyndale House Publishers` <dbl>, Nalar <dbl>,
## #   Kodansha <dbl>, `Harry N. Abrams` <dbl>, Minx <dbl>, `John Wiley &
## #   Sons` <dbl>, KPG <dbl>, `Little, Brown and Company` <dbl>, `Hill and
## #   Wang` <dbl>, `Zenescope Entertainment` <dbl>, TOKYOPOP <dbl>, `Jiang Tan
## #   She` <dbl>, `VIZ Media` <dbl>, `Yen Press` <dbl>, `Avatar Press` <dbl>,
## #   `BBC Books` <dbl>, `Gradien Mediatama` <dbl>, Shogakukan <dbl>, `Chronicle
## #   Books` <dbl>, `Walker & Company` <dbl>, `PT Gramedia Pustaka Utama` <dbl>,
## #   `Random House Books for Young Readers` <dbl>, `HMH Books for Young
## #   Readers` <dbl>, `Penguin Books` <dbl>, `IDW Publishing` <dbl>,
## #   Archaia <dbl>, `Graphic Universe` <dbl>, `Arthur A. Levine Books` <dbl>,
## #   `bS wTl` <dbl>, `Seven Seas` <dbl>, `Two Lions` <dbl>, Vertical <dbl>,
## #   `Tor/Seven Seas` <dbl>, `Marvel Comics` <dbl>, `Penguin Press` <dbl>,
## #   `Avatar Press, Inc.` <dbl>, `NBM Publishing` <dbl>, `Visual Print
## #   Enterprises` <dbl>, `Dynamite Entertainment` <dbl>, `De Jian Shu
## #   Dian` <dbl>, `Minneapolis : Graphic Universe` <dbl>, `Titan Books` <dbl>,
## #   `Top Shelf` <dbl>, `Kids Can Press` <dbl>, GRAPHIX <dbl>, `Iron Circus
## #   Comics` <dbl>, `Square Enix` <dbl>, `Square Enix, sukuueaenitsukusu` <dbl>,
## #   `Valiant Entertainment, LLC` <dbl>, `Soleil Editions` <dbl>, `Top Shelf
## #   Productions` <dbl>, `KaBOOM!` <dbl>, `Archaia (BOOM! Studios)` <dbl>,
## #   `Kyoto Animation` <dbl>, `Drawn and Quarterly` <dbl>, `Editions
## #   Glenat` <dbl>, `Houghton Mifflin Harcourt` <dbl>, `sukuueaenitsukusu /
## #   Square Enix` <dbl>, `Kodansha Comics` <dbl>, Bridge <dbl>, …
## # A tibble: 501 x 4
##    title                                    ratings_count average_rating book_id
##    <chr>                                            <dbl>          <dbl>   <dbl>
##  1 March: Book Three (March, #3)                     7100           4.71  2.94e7
##  2 Saga: Book Two                                     866           4.68  3.29e7
##  3 Locke & Key Slipcase Set                           321           4.66  2.28e7
##  4 Fullmetal Alchemist, Vol. 21 (Fullmetal…          6383           4.63  6.51e6
##  5 The Complete Peanuts, Vol. 6: 1961-1962            999           4.59  5.46e4
##  6 Skip Beat!, Vol. 09                               4606           4.57  1.11e6
##  7 The Wicked + The Divine #11                        461           4.57  2.53e7
##  8 Saga, Vol. 2 (Saga, #2)                          58474           4.56  1.71e7
##  9 Yotsuba&!, Vol. 06 (Yotsuba&! #6)                 2380           4.55  2.20e6
## 10 Fruits Basket, Vol. 23                            1023           4.55  5.32e6
## # … with 491 more rows
## 
##  Kendall's rank correlation tau
## 
## data:  goodread_comics2$prp_pos and goodread_comics2$average_rating
## z = 0.54499, p-value = 0.5858
## alternative hypothesis: true tau is not equal to 0
## sample estimates:
##        tau 
## 0.01808613

Код первой системы content-based

getBooks = function(id, n=5){
  user = goodread_reviews %>% filter(user_id == id & rating == 5)
  if (nrow(user)==0) {
    recommend = top_books[1:n, ]}
  
  else {
    mostSimilar = head(sort(sim[,as.character(user$book_id)], decreasing = T), n = n)
    a = which(sim[,as.character(user$book_id)] %in% mostSimilar, arr.ind = TRUE)
    index = arrayInd(a, .dim = dim(sim[,as.character(user$book_id)]))
    result = rownames(sim)[index[,1]]
    recommend = filter(goodread_comics,book_id %in% result) %>% dplyr::select(title, book_id)
    if (length(recommend$title)<n){
      recommend2 = filter(goodread_comics,book_id %in% result) %>% dplyr::select(title, book_id)
      recommend1 = top_books[1:(n-nrow(recommend)), ] %>% select(title, book_id) %>% rename(title2 = title)
      recommend = recommend1 %>% full_join(recommend2)
    }}
  recommend = recommend %>% filter(!(recommend$book_id %in% user$book_id ))
  recommend
}

Функция content-based для нового пользователя

Принцип работы этой функции:

В первом случае, функция только предупреждает и не рекомендует ничего. Во втором случае, система заполняет строки столбца title пустыми значениями “NA” ровно столько раз, сколько несуществующих книг запршивается новым пользователем. В третьем случае, функция по n рекмендаций к каждой существующей книге и добавляет строку с “Please try to enter another book”, чтобы указать на наличие недостатков в базе с похожими книгами.

getBooksbyName = function(comics_name, n=3){
  mostSimilar <- data.frame(title=character(0),book_id=numeric(0))
  for(i in 1:length(comics_name)){
    user1 =  goodread_comics %>% filter(title == comics_name[i])
    mostSimilar1 = head(sort(sim[,as.character(user1$book_id)], decreasing = T), n = n)
    for (x in 1:(length(mostSimilar1))){
      if (isTRUE(mostSimilar1[x]==0)){
        warning('Not Acceptable Cosine Similarity Value')
        print('Try another book')
        mostSimilar = "Please try to enter another book"}
      else{
        mostSimilar2 = data.frame(similar = mostSimilar1[x])
        mostSimilar2$book_id = as.numeric(rownames(mostSimilar2))
        mostSimilar2 = mostSimilar2 %>% arrange(-similar)
        recommend1 = mostSimilar2 %>% left_join(goodread_comics) %>% select(title, book_id)
        mostSimilar = rbind(mostSimilar, recommend1)}}}
  mostSimilar
  }

#Оценка базовой рекомендательной системы content-based

Для начала, нашей целью стал анализ двух групп потребителей графической литературы. Так, мы выделили две группы (manga, fantasy) исходя из того, что эти категории, в большей части, входят в топ-15 категорий полок по данным из 4 столбцов с полками, и являются более генерализуемыми в отличие от тех же самых marvel, dc comics или steampunk. Под генерализуемостью мы предполагаем доступность в каждом из четырёх столбцов.

joined_df %>% group_by(popular_shelves.0.name) %>% summarize(avg_rating = mean(rating), n = n()) %>% arrange(-n, -avg_rating)
## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 10 x 3
##    popular_shelves.0.name avg_rating     n
##    <chr>                       <dbl> <int>
##  1 to-read                      3.71 11318
##  2 comics                       3.75   292
##  3 graphic-novels               3.88   259
##  4 manga                        4.00   239
##  5 còmics                       3.98    50
##  6 dc-comics                    3.27    41
##  7 favorites                    3.73    30
##  8 fantasy                      3.35    17
##  9 star-wars                    3.64    14
## 10 picture-books                2.77    13
joined_df %>% group_by(popular_shelves.1.name) %>% summarize(avg_rating = mean(rating), n = n()) %>% arrange(-n, -avg_rating)
## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 30 x 3
##    popular_shelves.1.name avg_rating     n
##    <chr>                       <dbl> <int>
##  1 comics                       3.64  5103
##  2 graphic-novels               3.83  3995
##  3 manga                        3.78   993
##  4 to-read                      3.72   576
##  5 currently-reading            3.56   461
##  6 graphic-novel                3.39   156
##  7 mangá                        4.03   152
##  8 fantasy                      3.87    98
##  9 zombies                      3.80    86
## 10 steampunk                    3.89    75
## # … with 20 more rows
joined_df %>% group_by(popular_shelves.2.name) %>% summarize(avg_rating = mean(rating), n = n()) %>% arrange(-n, -avg_rating)
## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 55 x 3
##    popular_shelves.2.name avg_rating     n
##    <chr>                       <dbl> <int>
##  1 graphic-novels               3.62  5053
##  2 comics                       3.82  2414
##  3 graphic-novel                3.83  1386
##  4 currently-reading            3.61   714
##  5 fantasy                      3.79   476
##  6 horror                       3.96   268
##  7 marvel                       3.47   161
##  8 favorites                    4.34   142
##  9 mangá                        3.84   141
## 10 romance                      4      126
## # … with 45 more rows
joined_df %>% group_by(popular_shelves.3.name) %>% summarize(avg_rating = mean(rating), n = n()) %>% arrange(-n, -avg_rating)
## `summarise()` ungrouping output (override with `.groups` argument)
## # A tibble: 69 x 3
##    popular_shelves.3.name avg_rating     n
##    <chr>                       <dbl> <int>
##  1 graphic-novel                3.65  3135
##  2 graphic-novels               3.58  1125
##  3 fantasy                      3.94  1109
##  4 marvel                       3.63   896
##  5 comics                       3.71   851
##  6 favorites                    4.02   521
##  7 currently-reading            3.90   502
##  8 horror                       3.81   392
##  9 batman                       3.56   331
## 10 dc                           3.58   300
## # … with 59 more rows
goodread_comics %>% skim()
Data summary
Name Piped data
Number of rows 501
Number of columns 24
_______________________
Column type frequency:
character 16
factor 1
numeric 7
________________________
Group variables None

Variable type: character

skim_variable n_missing complete_rate min max empty n_unique whitespace
title 0 1 4 98 0 499 0
title_without_series 0 1 4 98 0 499 0
authors.0.author_id 0 1 3 8 0 292 0
authors.0.role 0 1 0 21 348 25 0
authors.1.author_id 0 1 4 8 0 395 0
authors.1.role 0 1 0 22 133 43 0
country_code 0 1 2 2 0 1 0
description 0 1 0 2003 25 477 0
is_ebook 0 1 4 5 0 2 0
language_code 0 1 0 5 70 12 0
link 0 1 43 117 0 501 0
popular_shelves.0.name 0 1 5 14 0 10 0
popular_shelves.1.name 0 1 2 17 0 30 0
popular_shelves.2.name 0 1 2 18 0 55 0
popular_shelves.3.name 0 1 2 21 0 69 0
publisher 0 1 0 36 46 123 0

Variable type: factor

skim_variable n_missing complete_rate ordered n_unique top_counts
tseries 0 1 FALSE 2 yes: 340, no: 161

Variable type: numeric

skim_variable n_missing complete_rate mean sd p0 p25 p50 p75 p100 hist
book_id 0 1.00 14451810.93 10771006.02 9526.00 3409425.00 13572811.00 23546982.00 35708105.00 ▇▅▅▅▃
avgRat 0 1.00 3.67 0.52 1.30 3.32 3.72 4.06 4.85 ▁▁▃▇▃
average_rating 0 1.00 3.94 0.37 2.81 3.69 3.99 4.22 4.71 ▁▃▆▇▃
num_pages 52 0.90 180.50 117.60 19.00 128.00 152.00 200.00 1192.00 ▇▁▁▁▁
publication_year 39 0.92 2011.37 4.49 1993.00 2009.00 2012.00 2015.00 2017.00 ▁▁▂▅▇
ratings_count 0 1.00 2541.07 6262.01 50.00 326.00 755.00 1983.00 58475.00 ▇▁▁▁▁
series 176 0.65 3.99 5.38 0.00 1.00 2.00 5.00 50.00 ▇▁▁▁▁

Manga Readers

Предупреждения:

Первой группой потребителей стали исключителньно люди, оценившие комиксы, у которых хотя бы в одном из столбцов с popular_shelves есть ключевое слово ‘manga’ - таких наблюдений в нашем датасете joined_df оказалось 1438. Оставив пользователей с оценками равными 5, мы сократили исходное количество наблюдений до 545, и обратились к функции за рекоммендацией десяти фильмов.

## # A tibble: 501 x 4
##    title                                    ratings_count average_rating book_id
##    <chr>                                            <dbl>          <dbl>   <dbl>
##  1 March: Book Three (March, #3)                     7100           4.71  2.94e7
##  2 Saga: Book Two                                     866           4.68  3.29e7
##  3 Locke & Key Slipcase Set                           321           4.66  2.28e7
##  4 Fullmetal Alchemist, Vol. 21 (Fullmetal…          6383           4.63  6.51e6
##  5 The Complete Peanuts, Vol. 6: 1961-1962            999           4.59  5.46e4
##  6 Skip Beat!, Vol. 09                               4606           4.57  1.11e6
##  7 The Wicked + The Divine #11                        461           4.57  2.53e7
##  8 Saga, Vol. 2 (Saga, #2)                          58474           4.56  1.71e7
##  9 Yotsuba&!, Vol. 06 (Yotsuba&! #6)                 2380           4.55  2.20e6
## 10 Fruits Basket, Vol. 23                            1023           4.55  5.32e6
## # … with 491 more rows

Первый пользователь

Среди первых двадцати пользователей можно встретить тех, у кого от 2 до 5 оцененных высшей оценкой книг и проанализировать трёх пользоваетелей с 3,4 и 5 оценками. Давайте посмотрим на предпочтения одного из пользователей с пятью оценками:

user1_data = user %>% filter(user_id == '4cc40b94cc18cf3650da122ca8f75b40')
user1_data
## # A tibble: 5 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  1.79e6   4.7  美少女戦… 美少女戦士セーラームーン新装版… 117369           ""            
## 2  1.95e6   4.29 Kitc… Kitchen Princes… 165682           ""            
## 3  2.08e7   4.5  ノラガミ… ノラガミ 7 [Noragam… 14507930         ""            
## 4  2.26e7   4.45 Kami… Kamisama Kiss, … 3091065          ""            
## 5  2.35e7   4.47 聲の形 … 聲の形 6 [Koe no K… 7009690          ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>

-Bishojo Senshi Sailor Moon Shinsoban; Kitchen Princess #6; Noragami 7: Stray God; Kamisama Kiss 17; A Silent Voice 6.

Первое, что объединяет всю оцененную литературу - это манга, и, соотвественно, ожидается что-то связанное с этим типом литературы.

Давайте обратимся к рекомендательной системе

## # A tibble: 10 x 25
##    title book_id avgRat title_without_s… authors.0.autho… authors.0.role
##    <chr>   <dbl>  <dbl> <chr>            <chr>            <chr>         
##  1 Our …  4.77e5   3.54 Our Hero (Babym… 137561           ""            
##  2 Full…  6.51e6   4.32 Fullmetal Alche… 4698899          ""            
##  3 Blac…  7.62e6   3.91 Black Butler, V… 2988406          ""            
##  4 Kami…  9.40e6   3.78 Kamisama Kiss, … 3091065          ""            
##  5 The …  1.30e7   4.5  The Power of th… 137561           ""            
##  6 Kami…  1.32e7   4    Kamisama Kiss, … 3091065          ""            
##  7 Out …  2.38e7   4.08 Out of the Past… 6851802          ""            
##  8 Blac…  2.57e7   3.92 Black Butler, V… 2988406          ""            
##  9 Capt…  2.87e7   3.06 Captain America… 255466           "Writer"      
## 10 Josi…  3.23e7   2.85 Josie and the P… 7265145          ""            
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Оценим пропорции издательств среди пяти оцененных (на 5 баллов) книг, средний рейтинг издательств и увидим, несоответствия в издательствах, оцененных и рекомендованных книг. Рейтинги издательств манги очень высокие.

## # A tibble: 4 x 3
##   publisher                 avgRat n_prop
##   <chr>                      <dbl>  <dbl>
## 1 Jiang Tan She                  5    0.4
## 2 Del Rey                        5    0.2
## 3 Jiang Tan She  / Kodansha      5    0.2
## 4 VIZ Media LLC                  5    0.2
## # A tibble: 7 x 3
##   publisher                              avgRat n_prop
##   <chr>                                   <dbl>  <dbl>
## 1 "VIZ Media LLC"                          4.52    0.3
## 2 "Yen Press"                              4.51    0.2
## 3 ""                                       3.87    0.1
## 4 "Archie Comic Publications"              3.31    0.1
## 5 "Marvel"                                 3.39    0.1
## 6 "Random House Books for Young Readers"   4.12    0.1
## 7 "Random House Children's Books"          4.04    0.1

Положительные результаты по рекоммендации

  1. Можем заметить, что были предложены комиксы из одинаковой серии “Kamisama Kiss”

  2. Схожие по уровню тональности/направленю комиксы(например, Black Butler и Silent Voice, Bishojo Senshi Sailor Moon Shinsoban, Kitchen Princess и Josie and the Pussycats );

Можно заметить некоторые странности в рекомендованных фильмах:

  1. Captain America: Steve Rogers, Volume 1: Hail Hydra

  2. Out of the Past

  3. Сильные различия в издателях

Данная рекомендация оправдала ожания только в 5 из 10 предложений, что не есть хорошо. Но, это может быть связано с разносторонностью оценок данного пользователя, так как он оценил высшим баллом литературу различного содержанания(good<->bad).

## # A tibble: 5 x 27
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  1.79e6   4.7  美少女戦… 美少女戦士セーラームーン新装版… 117369           ""            
## 2  1.95e6   4.29 Kitc… Kitchen Princes… 165682           ""            
## 3  2.08e7   4.5  ノラガミ… ノラガミ 7 [Noragam… 14507930         ""            
## 4  2.26e7   4.45 Kami… Kamisama Kiss, … 3091065          ""            
## 5  2.35e7   4.47 聲の形 … 聲の形 6 [Koe no K… 7009690          ""            
## # … with 21 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>, prp_pos <dbl>

Второй пользователь

Можем увидеть, что у пользователя 4 высокие оценки

user2_data = user %>% filter(user_id =='f07b2b3332b24aeea24a566e5063e56b')
user2_data
## # A tibble: 3 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  5.32e6   4.5  Frui… Fruits Basket, … 26306            ""            
## 2  2.08e7   4.5  ノラガミ… ノラガミ 7 [Noragam… 14507930         ""            
## 3  2.26e7   4.45 Kami… Kamisama Kiss, … 3091065          ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>

Рекомендация из десяти книг, где две книг в столбце “title2” из топа, а восемь даны рекомендательной системой

## # A tibble: 10 x 25
##    title book_id avgRat title_without_s… authors.0.autho… authors.0.role
##    <chr>   <dbl>  <dbl> <chr>            <chr>            <chr>         
##  1 Full…  6.51e6   4.32 Fullmetal Alche… 4698899          ""            
##  2 Blac…  7.62e6   3.91 Black Butler, V… 2988406          ""            
##  3 Kami…  9.40e6   3.78 Kamisama Kiss, … 3091065          ""            
##  4 Kami…  1.32e7   4    Kamisama Kiss, … 3091065          ""            
##  5 Batm…  1.35e7   3.44 Batman: Knightf… 28709            ""            
##  6 Youn…  1.85e7   4.06 Young Avengers,… 439887           "Writer"      
##  7 Nigh…  2.16e7   3.8  Nightwing Volum… 28710            ""            
##  8 The …  2.36e7   3.67 The Wicked + Th… 439887           ""            
##  9 Out …  2.38e7   4.08 Out of the Past… 6851802          ""            
## 10 Blac…  2.57e7   3.92 Black Butler, V… 2988406          ""            
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Пропорции издательств и средний рейтинг

## # A tibble: 3 x 3
##   publisher       avgRat  nrop
##   <chr>            <dbl> <dbl>
## 1 ""                   5  0.25
## 2 "Jiang Tan She"      5  0.25
## 3 "VIZ Media LLC"      5  0.25
## # A tibble: 6 x 3
##   publisher       avgRat n_prop
##   <chr>            <dbl>  <dbl>
## 1 "VIZ Media LLC"   4.52    0.3
## 2 "DC Comics"       3.93    0.2
## 3 "Yen Press"       4.51    0.2
## 4 ""                3.87    0.1
## 5 "Image Comics"    4.17    0.1
## 6 "Marvel"          4.26    0.1

Положительные результаты по рекомендации

  1. Можем заметить, что были предложены комиксы из одинаковой серии “Kamisama Kiss”

  2. Половина предложенных относятся к категории манга.

  3. Схожие по уровню тональности комиксы(например, Black Butler и Silent Voice, Bishojo Senshi Sailor Moon Shinsoban, Kitchen Princess и Josie and the Pussycats ); то есть (в силу незнания каждой книги) были прочитаны описания и найдены некоторые общие характеристики

  4. Года рекомендованных комиксов не сильно отличаются от понравившихся пользователю. (одно десятилетие)

Тем не менее, система порекомендовала несколько комиксов о супергероях Marvel и DC (Batman: Knightfall, Vol. 3: KnightsEnd, Young Avengers,Nightwing,The Wicked), и на наш взгляд это не совсем удачные рекомендации, так как пользователь, читающий только мангу, скорее захочет видеть в рекомендациях тот же жанр комиксов. Кроме этого, совпадает только половина издателей - VIZ Media LLC и неизвестный издатель.

Третий пользователь

Книги, оцененные пользователем (3 оценки):

user3_data = user %>% filter(user_id =='359e63e506eedc65dc7dc1ecf12bedf9') %>% left_join(goodread_comics, by = "book_id")
user3_data
## # A tibble: 2 x 50
##   book_id avgRat.x title.x title_without_s… authors.0.autho… authors.0.role.x
##     <dbl>    <dbl> <chr>   <chr>            <chr>            <chr>           
## 1 6285607     4.33 PLUTO:… PLUTO: Urasawa … 294649           ""              
## 2 6889271     4.33 PLUTO:… PLUTO: Urasawa … 294649           ""              
## # … with 44 more variables: authors.1.author_id.x <chr>,
## #   authors.1.role.x <chr>, average_rating.x <dbl>, country_code.x <chr>,
## #   description.x <chr>, is_ebook.x <chr>, language_code.x <chr>, link.x <chr>,
## #   num_pages.x <dbl>, popular_shelves.0.name.x <chr>,
## #   popular_shelves.1.name.x <chr>, popular_shelves.2.name.x <chr>,
## #   popular_shelves.3.name.x <chr>, publication_year.x <dbl>,
## #   publisher.x <chr>, ratings_count.x <dbl>, series.x <dbl>, tseries.x <fct>,
## #   user_id <chr>, rating <dbl>, avgRat.y <dbl>, title.y <chr>,
## #   title_without_series.y <chr>, authors.0.author_id.y <chr>,
## #   authors.0.role.y <chr>, authors.1.author_id.y <chr>,
## #   authors.1.role.y <chr>, average_rating.y <dbl>, country_code.y <chr>,
## #   description.y <chr>, is_ebook.y <chr>, language_code.y <chr>, link.y <chr>,
## #   num_pages.y <dbl>, popular_shelves.0.name.y <chr>,
## #   popular_shelves.1.name.y <chr>, popular_shelves.2.name.y <chr>,
## #   popular_shelves.3.name.y <chr>, publication_year.y <dbl>,
## #   publisher.y <chr>, ratings_count.y <dbl>, series.y <dbl>, tseries.y <fct>,
## #   prp_pos <dbl>

Можно заметить, что наблюдается сюжетное и стилистическое сходство этих двух манг. Книги непостредственно связаны с технологиями и убийством персонажей, близких к главным героям. Можем заметить, что книги из одного десятилетия издательства.

Перйдём к анализу рекомендации:

На данном этапе мы запросили 10 книг, но анализируем только половину в силу заметных совпадений издательств после пятого

  1. Книги из данной десятки относятся к пяти издательствам и только одна была классифицирована пользователями как manga (Skip Beat!, Vol. 09).

  2. Можем заметить, что первая книга была рекомендована в силу того, что она относится к одному издательству и является мангой, а остальные немного похожи по описаниям и средним оценкам.

3.Странной рекомендацией здесь можно назвать Air, Volume 2: Flying Machine, так как она сильно отличается описанием.

## # A tibble: 10 x 25
##    title book_id avgRat title_without_s… authors.0.autho… authors.0.role
##    <chr>   <dbl>  <dbl> <chr>            <chr>            <chr>         
##  1 Skip…  1.11e6   4.24 Skip Beat!, Vol… 164127           ""            
##  2 Air,…  6.35e6   2.9  Air, Volume 2: … 815259           ""            
##  3 Morn…  1.01e7   3.52 Morning Glories… 255466           ""            
##  4 I, V…  1.35e7   3.39 I, Vampire, Vol… 510877           "Writer"      
##  5 Nowh…  1.71e7   3.44 Nowhere Men, Vo… 221822           "Writer"      
##  6 Saga…  1.71e7   4.64 Saga, Vol. 2 (S… 24514            "Writer"      
##  7 Secr…  2.23e7   3.04 Secret Origins,… 543719           "Artist"      
##  8 Mart…  2.58e7   3.32 Martian Manhunt… 48010            "Writer"      
##  9 Elve…  2.94e7   3.43 Elves. Vol. 1 (… 261650           ""            
## 10 Supe…  3.47e7   4    Super Sons, Vol… 171132           ""            
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Fantasy Readers

Второй группой стала полка/жанр ‘fantasy’, которая была не в топе распредлеения по оценкам и количеству оценок, и показаллась нам количественно адекватнее чем “graphic-novels”, где остается более десяти тысяч наблюдений. Отфильтровав датасет по нужным нам переменным, мы получили 1700 наблюдений, из которых 598 с высшей оценкой. Далее, по схожей предыдущей оценке логике, мы выделили пользователей с 6,4 и 2 пятёрками.

Отфильтруем исходный датасет под выбранную группу

## # A tibble: 522 x 2
##    user_id                              n
##    <chr>                            <int>
##  1 8273fc29780c84559cbd533fc969c0a6     6
##  2 a62f87dc3e17a93fbcf59657b74e57de     5
##  3 ca1c301fff032671a4fd555429db2298     4
##  4 1660e6eee71858cefa1b86a6cfdffc41     3
##  5 329fa2b533d62e4bed9291adb2f5ad88     3
##  6 4cc40b94cc18cf3650da122ca8f75b40     3
##  7 5f26661d439249b94a9fce394036588f     3
##  8 613eb783a9da80f452dcfe657d008af8     3
##  9 6eabbf9f1b284cda62664a46784c12f3     3
## 10 7f2f0055c2ad439395b5f622b923944a     3
## # … with 512 more rows

Книги, оцененные первым пользователем(жанры этих книг):

user %>% filter(user_id =="8273fc29780c84559cbd533fc969c0a6")
## # A tibble: 6 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  1.36e4   3.4  Tsub… Tsubasa: RESERV… 8476             ""            
## 2  3.39e6   4.08 Kyo … Kyo Kara MAOH!,… 1431671          ""            
## 3  6.51e6   4.32 Full… Fullmetal Alche… 4698899          ""            
## 4  1.87e7   4.16 Avat… Avatar: The Las… 68959            "Writer"      
## 5  2.06e7   4.1  Esca… Escape from Luc… 27372            ""            
## 6  2.59e7   4.46 Avat… Avatar: The Las… 68959            ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>

То есть видна жаноровая связь между оцененными фильмами, где наблюдаются приключения в вымышленных мирах - fantasy. Логично предположить о схожести рекомендаций по жанру, но мы это проверим ниже.

## # A tibble: 10 x 25
##    title book_id avgRat title_without_s… authors.0.autho… authors.0.role
##    <chr>   <dbl>  <dbl> <chr>            <chr>            <chr>         
##  1 Tsub…  1.36e4   3.36 Tsubasa: RESERV… 8476             ""            
##  2 Alie…  3.20e6   2.75 Alien Hunter (D… 3780             ""            
##  3 Mada…  6.64e6   3.58 Madame Xanadu, … 9934             "Writer"      
##  4 Hell…  1.71e7   4    Hellblazer, Vol… 14965            "Writer"      
##  5 Scot…  1.72e7   4.44 Scott Pilgrim, … 16807            "Writer, Arti…
##  6 Just…  1.77e7   3.72 Justice League,… 10305            "Writer"      
##  7 JoJo…  2.25e7   3.25 JoJo's Bizarre … 8452             ""            
##  8 Jame…  2.88e7   3.67 James Bond, Vol… 12772            ""            
##  9 Jame…  3.25e7   4.29 James Bond, Vol… 12772            ""            
## 10 Clea…  3.32e7   3.71 Clean Room, Vol… 45103            "Writer"      
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Очевидно, что странными предложением в данной подборке являются Hellblazer, так как по сравнеию с оставльными предложениями данная книга из другого раздела, но мы предполагаем, что рекомендательная система предложила именно эту книга из-за схожести по издательству. С точки зрения команды, данная рекомендация собрала неплохой набор книг и справилась с задачей в 8 случаях из 10 запрашиваемых.

Анализируем предпочтения и подборку комиксов для пользователся с четырьмя оценками:

user %>% filter(user_id =="ca1c301fff032671a4fd555429db2298")
## # A tibble: 4 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  325751   3.74 Prom… Promethea, Vol.… 3961             ""            
## 2  325752   3.82 Prom… Promethea, Vol.… 3961             ""            
## 3 1792733   4.7  美少女戦… 美少女戦士セーラームーン新装版… 117369           ""            
## 4 6378575   3.17 Jack… Jack of Fables,… 12444            "Writer"      
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>

Можем заметить, что данному пользователю не получается рекомендовать более 4 книг, и по этой причине, ему руомендуются комиксы из первой десятки и все то, что получаем content-based подходом.

Положительные замечания: - Комиксы издательств Marvel И Dynamite Entertainment

Странным явлением является рекомендация Maximum Ride, которая выделяется тем, что эта книга из разряда “манга” по сравнению с остальными, которые больше похожи на graphic-novels и комисы, исходя из издательств и жанров, к которым они относятся.

## # A tibble: 4 x 26
##   title2 book_id title avgRat title_without_s… authors.0.autho… authors.0.role
##   <chr>    <dbl> <chr>  <dbl> <chr>            <chr>            <chr>         
## 1 <NA>    6.32e6 Maxi…   4.1  Maximum Ride, V… 3780             ""            
## 2 <NA>    1.36e7 The …   4.07 The Boys, Volum… 14965            "Writer"      
## 3 <NA>    1.60e7 Capt…   3.62 Captain Marvel,… 16587            "Writer"      
## 4 <NA>    1.83e7 Guar…   3.18 Guardians of th… 12424            "Writer"      
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Анализ третьего пользователся с двумя пятёрками:

user %>% filter(user_id =="0854dcf6ea7dc480e5ddd548d8bbc7d9")
## # A tibble: 2 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  1.77e7   4.57 Fabl… Fables (The Del… 12444            "Writer"      
## 2  2.86e7   3.5  Wayw… Wayward, Vol. 3… 5737122          ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>
## # A tibble: 10 x 25
##    title book_id avgRat title_without_s… authors.0.autho… authors.0.role
##    <chr>   <dbl>  <dbl> <chr>            <chr>            <chr>         
##  1 Fabl…  2.13e4   4.14 Fables, Vol. 4:… 12444            "Writer"      
##  2 The …  1.07e5   4    The Punisher MA… 14965            ""            
##  3 Ulti…  2.68e5   3.5  Ultimate X-Men,… 12736            "Writer"      
##  4 Ulti…  3.53e6   3.1  Ultimate X-Men,… 12425            "Writer"      
##  5 Batm…  8.41e6   3.45 Batman Confiden… 2549186          ""            
##  6 Dead…  1.78e7   4.04 Deadpool, Volum… 6586803          "Writer"      
##  7 Dead…  1.84e7   4    Deadpool by Pos… 6586803          ""            
##  8 FBP:…  2.15e7   3.47 FBP: Federal Bu… 280283           ""            
##  9 Fabl…  2.16e7   4.21 Fables (The Del… 12444            "Writer"      
## 10 Jess…  2.51e7   3.97 Jessica Jones: … 12424            ""            
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Оценка индивидуальной рекомендательной системы

Выше был описан принцип работы данной рекомендательной функции с различными случаями.

Первый случай (полноценная рекомендация)

##                                                 title  book_id   avgRat
## 1                               Kamisama Kiss, Vol. 9 13183545 4.000000
## 2                              Kamisama Kiss, Vol. 17 22609112 4.454545
## 3                                Black Butler, Vol. 3  7620623 3.909091
## 4              The Power of the Parasite (Squish, #3) 12993826 4.500000
## 5    Kitchen Princess, Vol. 06 (Kitchen Princess, #6)  1952950 4.285714
## 6 Captain America: Steve Rogers, Volume 1: Hail Hydra 28665325 3.055556
## 7                        Jessica Jones: Alias, Vol. 2 25066808 3.966667
## 8               Ultimate X-Men, Volume 18: Apocalypse  3526329 3.100000
## 9     Guardians of the Galaxy, Volume 4: Original Sin 23017976 3.625000
##                                  title_without_series authors.0.author_id
## 1                               Kamisama Kiss, Vol. 9             3091065
## 2                              Kamisama Kiss, Vol. 17             3091065
## 3                                Black Butler, Vol. 3             2988406
## 4              The Power of the Parasite (Squish, #3)              137561
## 5    Kitchen Princess, Vol. 06 (Kitchen Princess, #6)              165682
## 6 Captain America: Steve Rogers, Volume 1: Hail Hydra              255466
## 7                        Jessica Jones: Alias, Vol. 2               12424
## 8               Ultimate X-Men, Volume 18: Apocalypse               12425
## 9     Guardians of the Galaxy, Volume 4: Original Sin               12424
##   authors.0.role authors.1.author_id authors.1.role average_rating country_code
## 1                            1411091     Translator           4.47           US
## 2                            1411091     Translator           4.52           US
## 3                            1411091     Translator           4.53           US
## 4                             266721                          4.12           US
## 5                             328260                          4.35           US
## 6         Writer              507122    Illustrator           3.39           US
## 7                              61315    Illustrator           4.11           US
## 8         Writer               61327         Artist           3.58           US
## 9         Writer               61853         Artist           3.64           US
##                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                description
## 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  A divine comedy!\nReads R to L (Japanese Style), for audiences rated teen.\nNanami Momozono is alone and homeless after her dad skips town to evade his gambling debts and the debt collectors kick her out of her apartment. So when a man she's just saved from a dog offers her his home, she jumps at the opportunity. But it turns out that his place is a shrine, and Nanami has unwittingly taken over his job as a local deity!\nNanami may have been (begrudgingly) accepted by the other kami at Izumo, but that doesn't make her any less human or help her deal with her growing feelings for Tomoe. Should she be true to her heart or cut Tomoe loose for his own good? Either way, getting dragged into a group date isn't going to help matters at all!
## 2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    Nanami Momozono is alone and homeless after her dad skips town to evade his gambling debts and the debt collectors kick her out of her apartment. So when a man she's just saved from a dog offers her his home, she jumps at the opportunity. But it turns out that his place is a shrine, and Nanami has unwittingly taken over his job as a local deity!\nNanami has finally found the fallen kami who cursed Tomoe, but before she can rush home to save her beloved shinshi, she must watch the past unfold. But how will her relationship with Tomoe be affected by her standing witness to the torments he and Yukiji suffer?!
## 3                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           Terrorizing its populace, Jack the Ripper has shaken London to its very core. But when Sebastian Michaelis, singular butler of the Phantomhive house, lays bare the madman's true identity, all that is left for him to do is eliminate the perpetrator in the name of the Queen and Phantomhive. But inhumanly efficient skills don't guarantee victory when the opponent is just as supernaturally gifted! And though Sebastian may be able to save Ciel from physical harm in the battle that ensues, will the young earl ever recover from the emotional scars it will leave on his heart?
## 4 Introducing Squish--a hilarious, action packed graphic novel series from the award-winning creators of Babymouse! Filled with superheroes, comics within comics, and gross-out science, Squish is perfect for fans of Dav Pilkey's Captain Underpants, Dan Gutman's Weird School, and Jarrett Krosoczka's Lunch Lady.\nSchool's out! Everyone's favorite amoeba is headed to summer camp! But instead of SUPER AWESOME FUN, Squish's summer is turning out to be SUPER AWESOME TERRIFYING! For one thing, Squish can't swim. And to make matters worse, his new camp friend is a Hydra (scientific fact: A hydra's tentacles can paralyze you!). Will Squish sink or will he swim this summer? (And what's up with Pod and black holes anyways??) Find out the answers to these questions and more in the super spectacular adventure, Squish #4: The Power of the Parasite. Summer reading has never been so slimey!\nYowza! You can draw comics, too! Look in the back to find out how to draw one of the Squish characters! Also includes instructions for a sensational science experiment you can do at home! Shazam!\nHere's what people are saying about everyone's favorite amoeba!\nNew York Times:\n"An energetic, good-hearted escapade, one that young readers will enjoy."\nStarred Review, Kirkus Reviews:\n* "Hilarious. If ever a new series deserved to go viral, this one does."\nThe Bulletin:\n"A perfect mix of writing that is simple enough for early readers but still remarkably snarky, clever, and entertaining. Kids will soak up the humor, tidbits of science instruction, and adventure."
## 5                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            RECIPE FOR DISASTER\nNajika's dreams are coming true! She's in the finals of a national dessert contest and has found her Flan Prince. But then life goes from sweet to sour as she makes a startling discovery and loses her sense of taste!
## 6                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 He's back! The original Sentinel of Liberty returns, with a new shield, a new team, and a new mission! And he's not the only one who's back! Like the saying goes-- cut off one head, two more will take its place! Hail Hydra!\nCollecting: Captain America: Steve Rogers1-6, FCBD 2016
## 7                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       All she ever wanted was to be a super hero. But life had other plans for Jessica Jones. Now, the adventures of the would-be Avenger turned bitter superpowered private eye continue with two new cases. In "Rebecca, Come Home," Jessica travels to upstate New York to investigate the disappearance of a teenage girl rumored to be a mutant in a prejudiced small town - but a murder mystery and a drunken, ill-advised fling might complicate matters somewhat. And in "Raining Men," the hard-luck PI goes on a date with...the Astonishing Ant-Man?!COLLECTING: Alias 11-15
## 8                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             The sinister Shadow King is desperate to escape from the mental prison he was placed in centuries ago - and he'll destroy Storm to do it But will his freedom also unleash the horrifying swarm of the alien Brood? And will even the X-Men be enough to battle a being who has plotted our death and destruction for ages?\nCollecting: Ultimate X-Men89-93
## 9                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  Remember when Star-Lord, Thanos and Nova were trapped in the horrific Cancerverse? When Star-Lord and Nova were going to sacrifice their lives to take out Thanos once and for all? And remember how Drax was supposed to have died? But Star-Lord, Drax and Thanos seem to be running around just fine nowadays. So what exactly happened to Richard Rider? It's finally time to get some answers about the true ending of the Cancerverse saga! Then, when Venom leads the team to an entire world teeming with his fellow alien symbiotes, will the Guardians ever trust Flash Thompson again? His symbiote is becoming more and more uncontrollable, and this may be seriously bad news for the team. Plus: What is a S.H.I.E.L.D. Helicarrier doing in space?!\nCollecting: Guardians of the Galaxy18-23, Annual 1
##   is_ebook language_code
## 1    false           eng
## 2    false           eng
## 3    false           eng
## 4    false           eng
## 5    false         en-US
## 6    false           eng
## 7    false         en-GB
## 8    false           eng
## 9    false           eng
##                                                                            link
## 1              https://www.goodreads.com/book/show/13183545-kamisama-kiss-vol-9
## 2             https://www.goodreads.com/book/show/22609112-kamisama-kiss-vol-17
## 3                https://www.goodreads.com/book/show/7620623-black-butler-vol-3
## 4        https://www.goodreads.com/book/show/12993826-the-power-of-the-parasite
## 5           https://www.goodreads.com/book/show/1952950.Kitchen_Princess_Vol_06
## 6                  https://www.goodreads.com/book/show/28665325-captain-america
## 7                    https://www.goodreads.com/book/show/25066808-jessica-jones
## 8          https://www.goodreads.com/book/show/3526329-ultimate-x-men-volume-18
## 9 https://www.goodreads.com/book/show/23017976-guardians-of-the-galaxy-volume-4
##   num_pages popular_shelves.0.name popular_shelves.1.name
## 1       192                to-read                  manga
## 2       200                to-read                  manga
## 3       192                to-read                  manga
## 4        96                to-read         graphic-novels
## 5       208                to-read                  manga
## 6       168                to-read                 comics
## 7       128                to-read                 comics
## 8       120                to-read                 comics
## 9       136                to-read                 comics
##   popular_shelves.2.name popular_shelves.3.name publication_year
## 1                fantasy                romance             2012
## 2                fantasy              favorites             2015
## 3                fantasy           black-butler             2010
## 4          graphic-novel              childrens             2012
## 5                romance       kitchen-princess             2008
## 6         graphic-novels                 marvel             2016
## 7         graphic-novels          graphic-novel             2015
## 8         graphic-novels                 marvel             2008
## 9         graphic-novels                 marvel             2015
##                              publisher ratings_count series tseries   prp_pos
## 1                        VIZ Media LLC          2043      9     yes 0.2857143
## 2                        VIZ Media LLC           410     17     yes 0.1250000
## 3                            Yen Press           693      3     yes 0.5000000
## 4 Random House Books for Young Readers          1829      3     yes 0.7777778
## 5                              Del Rey          3669      6     yes 0.2000000
## 6                               Marvel           399      1     yes 1.0000000
## 7                               Marvel           596      2     yes 0.3333333
## 8                               Marvel           744     18     yes 0.1538462
## 9                        Marvel Comics           701      4     yes 0.3750000

По умолчанию, функция рекомендует по три книги к каждой введенной пользователем. Так, для трёх введенных книг мы получили 9 рекомендаций, и для данных трёх книг никаких предупреждений.

Давайте оценим сами рекомендации на адекватность (будем оценивать по блокам из трёх в силу приципа работы этой функции)

Первый блок - этр блок из трёх рекомендаций к комиксу из серии “Kamisama Kiss”

  1. Можем заметить, что были рекомендованы две книги из этой серии - это скорее хорошо

  2. Несмотря на то, что комикс полностью отличается от того, что нравится пользователю, положительным моментом являетя совпадение одного из авторов - это тоже хорошо

3/3

Второй блок - блок из трех рекомендаций к скорее детскому комиксу из серии “Our Hero (Babymouse)”

  1. Есть одна детская книга ‘Kitchen Princess’ и ‘The Power of Parasit’, но третья как-то мимо

2/3

Третий блок - что-то в стиле героев американских комиксов

  1. Все рекомендации издательства Marvel

3/3, но истинные ценители комиксов могут не согласиться (в нашей команде нет таких)

Давайте попробуем построить еще одну рекомендацию для комиксов, рекомендованных ранее

##                                                 title  book_id   avgRat
## 1               Ultimate X-Men, Volume 18: Apocalypse  3526329 3.100000
## 2                        Jessica Jones: Alias, Vol. 2 25066808 3.966667
## 3        Ultimate X-Men, Volume 2: Return to Weapon X   267794 3.500000
## 4 Captain America: Steve Rogers, Volume 1: Hail Hydra 28665325 3.055556
## 5                            Our Hero (Babymouse, #2)   476911 3.538462
## 6              The Power of the Parasite (Squish, #3) 12993826 4.500000
## 7                     Fables (The Deluxe Edition, #8) 17671951 4.571429
## 8                     Fables (The Deluxe Edition, #9) 21555995 4.214286
## 9        Ultimate X-Men, Volume 2: Return to Weapon X   267794 3.500000
##                                  title_without_series authors.0.author_id
## 1               Ultimate X-Men, Volume 18: Apocalypse               12425
## 2                        Jessica Jones: Alias, Vol. 2               12424
## 3        Ultimate X-Men, Volume 2: Return to Weapon X               12736
## 4 Captain America: Steve Rogers, Volume 1: Hail Hydra              255466
## 5                            Our Hero (Babymouse, #2)              137561
## 6              The Power of the Parasite (Squish, #3)              137561
## 7                     Fables (The Deluxe Edition, #8)               12444
## 8                     Fables (The Deluxe Edition, #9)               12444
## 9        Ultimate X-Men, Volume 2: Return to Weapon X               12736
##   authors.0.role authors.1.author_id authors.1.role average_rating country_code
## 1         Writer               61327         Artist           3.58           US
## 2                              61315    Illustrator           4.11           US
## 3         Writer               61330    Illustrator           3.70           US
## 4         Writer              507122    Illustrator           3.39           US
## 5                             266721                          4.04           US
## 6                             266721                          4.12           US
## 7         Writer               55811         Artist           4.45           US
## 8         Writer               55811         Artist           4.40           US
## 9         Writer               61330    Illustrator           3.70           US
##                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                description
## 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             The sinister Shadow King is desperate to escape from the mental prison he was placed in centuries ago - and he'll destroy Storm to do it But will his freedom also unleash the horrifying swarm of the alien Brood? And will even the X-Men be enough to battle a being who has plotted our death and destruction for ages?\nCollecting: Ultimate X-Men89-93
## 2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       All she ever wanted was to be a super hero. But life had other plans for Jessica Jones. Now, the adventures of the would-be Avenger turned bitter superpowered private eye continue with two new cases. In "Rebecca, Come Home," Jessica travels to upstate New York to investigate the disappearance of a teenage girl rumored to be a mutant in a prejudiced small town - but a murder mystery and a drunken, ill-advised fling might complicate matters somewhat. And in "Raining Men," the hard-luck PI goes on a date with...the Astonishing Ant-Man?!COLLECTING: Alias 11-15
## 3                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Now pawn of the mysterious weapon X program, the mutant heros' only hope lies with the one team member to evade capture: the enigmatic, unproven Wolverine! Can Logan go it alone against the shadow-ops organisation that transformed him into one of the worlds most lethal killing machines.\nCollecting: Ultimate X-Men7-12
## 4                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 He's back! The original Sentinel of Liberty returns, with a new shield, a new team, and a new mission! And he's not the only one who's back! Like the saying goes-- cut off one head, two more will take its place! Hail Hydra!\nCollecting: Captain America: Steve Rogers1-6, FCBD 2016
## 5                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  For Babymouse, school is a constant battle between good (Babymouse), evil (Felicia Furrpaws), and more evil (gym class!). Can things get any worse? Yup. Because it's time for the annual dodgeball tournament. What's a mouse to do? Don't miss the excitement in Babymouse: Our Hero!
## 6 Introducing Squish--a hilarious, action packed graphic novel series from the award-winning creators of Babymouse! Filled with superheroes, comics within comics, and gross-out science, Squish is perfect for fans of Dav Pilkey's Captain Underpants, Dan Gutman's Weird School, and Jarrett Krosoczka's Lunch Lady.\nSchool's out! Everyone's favorite amoeba is headed to summer camp! But instead of SUPER AWESOME FUN, Squish's summer is turning out to be SUPER AWESOME TERRIFYING! For one thing, Squish can't swim. And to make matters worse, his new camp friend is a Hydra (scientific fact: A hydra's tentacles can paralyze you!). Will Squish sink or will he swim this summer? (And what's up with Pod and black holes anyways??) Find out the answers to these questions and more in the super spectacular adventure, Squish #4: The Power of the Parasite. Summer reading has never been so slimey!\nYowza! You can draw comics, too! Look in the back to find out how to draw one of the Squish characters! Also includes instructions for a sensational science experiment you can do at home! Shazam!\nHere's what people are saying about everyone's favorite amoeba!\nNew York Times:\n"An energetic, good-hearted escapade, one that young readers will enjoy."\nStarred Review, Kirkus Reviews:\n* "Hilarious. If ever a new series deserved to go viral, this one does."\nThe Bulletin:\n"A perfect mix of writing that is simple enough for early readers but still remarkably snarky, clever, and entertaining. Kids will soak up the humor, tidbits of science instruction, and adventure."
## 7                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           Flycatcher is drawn into the spotlight as he discovers the startling truth about his own past as the Frog Prince. At the same time, he learns that the Adversary plans to destroy his foes once and for all. How can the meek Flycatcher stop this deadly foe?\nCollecting: Fables60-63, 65-69
## 8                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 The final battle between the free Fables of the mundane world and the Empire occupying their former Homelands is here! The creatures of myth and fairytale lore have assembled together to finally face the Adversary and his hordes. But victory will not come without a price--who will live and who will die for the fate of the Homelands?\n\001's Eisner Award-winning, New York Timesbest-selling series comes to the deluxe hardcover format here in Fables: The Deluxe Edition, Book Nine in one of the most epic storylines in the series' long history.\nCollecting: \00170-82
## 9                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          Now pawn of the mysterious weapon X program, the mutant heros' only hope lies with the one team member to evade capture: the enigmatic, unproven Wolverine! Can Logan go it alone against the shadow-ops organisation that transformed him into one of the worlds most lethal killing machines.\nCollecting: Ultimate X-Men7-12
##   is_ebook language_code
## 1    false           eng
## 2    false         en-GB
## 3    false         en-US
## 4    false           eng
## 5    false         en-US
## 6    false           eng
## 7    false           eng
## 8    false           eng
## 9    false         en-US
##                                                                     link
## 1   https://www.goodreads.com/book/show/3526329-ultimate-x-men-volume-18
## 2             https://www.goodreads.com/book/show/25066808-jessica-jones
## 3     https://www.goodreads.com/book/show/267794.Ultimate_X_Men_Volume_2
## 4           https://www.goodreads.com/book/show/28665325-captain-america
## 5                    https://www.goodreads.com/book/show/476911.Our_Hero
## 6 https://www.goodreads.com/book/show/12993826-the-power-of-the-parasite
## 7                    https://www.goodreads.com/book/show/17671951-fables
## 8                    https://www.goodreads.com/book/show/21555995-fables
## 9     https://www.goodreads.com/book/show/267794.Ultimate_X_Men_Volume_2
##   num_pages popular_shelves.0.name popular_shelves.1.name
## 1       120                to-read                 comics
## 2       128                to-read                 comics
## 3       144                to-read                 comics
## 4       168                to-read                 comics
## 5        96                to-read         graphic-novels
## 6        96                to-read         graphic-novels
## 7       232                to-read         graphic-novels
## 8       368                to-read         graphic-novels
## 9       144                to-read                 comics
##   popular_shelves.2.name popular_shelves.3.name publication_year
## 1         graphic-novels                 marvel             2008
## 2         graphic-novels          graphic-novel             2015
## 3         graphic-novels                 marvel             2006
## 4         graphic-novels                 marvel             2016
## 5          graphic-novel              childrens             2005
## 6          graphic-novel              childrens             2012
## 7                 comics                fantasy             2014
## 8                 comics                fantasy             2014
## 9         graphic-novels                 marvel             2006
##                              publisher ratings_count series tseries   prp_pos
## 1                               Marvel           744     18     yes 0.1538462
## 2                               Marvel           596      2     yes 0.3333333
## 3                               Marvel          1765      2     yes 0.1428571
## 4                               Marvel           399      1     yes 1.0000000
## 5        Random House Children's Books          2137      2     yes 0.4285714
## 6 Random House Books for Young Readers          1829      3     yes 0.7777778
## 7                              Vertigo           642      8     yes 0.0000000
## 8                              Vertigo           498      9     yes 0.2857143
## 9                               Marvel          1765      2     yes 0.1428571

Первый блок рекомендаций - для “Guardians of the Galaxy”

  1. Как и в предыдущей рекомендации, всё из компании Marvel

  2. Как ожидалось, был рекомендован комикс “Ultimate X-Men”

3/3

Второй блок - детские книги

Рекомендованы две детские книги похожих издателей, но третья (Marvel) мимо

2/3

Третий блок - Fables

  1. Рекомендованы книги из серии “Fables” - скорее хорошо

  2. Сомнительная реомендация, которая может быть связана только по схожести издательств, т.к. Vertigo - это импринт DC Comics, а люди-X и Fables нацелены на более взрослую аудиторию

То есть можем сделать вывод скорее об адекватности этой системы . Наверное, наш подход не очень адекватен в смысле построения рекомендаций на основе каждого отдельного комикса, но данная система справляется немного лучше предыдущей, и нет какой-то мистики в принципе работы системы, т.к. нет совсем странных случаев.

Неполноценные рекомендации

Следующие случаи будут рассмотрены с целью представления приципа работы, а может и недостатков системы, но никак не для оценки адекватности отдельных рекомеднаций

Второй случай (когда нет книг, похожих на запрашиваемые/запрашиваемый комиксы/комикс)

Можем заметить предупреждения о низких значениях косинусного расстояния и итоговый текст о невозможности построения рекомендации.

## [1] "Try another book"
## [1] "Try another book"
## [1] "Try another book"
## [1] "Try another book"
## [1] "Please try to enter another book"

Третий случай (Когда нет ни одного комикса из списка)

Давайте введём абсолютно случайные значения и заметим, что на выходе у нас таблица из NA с совпадаюшим с количеством введенных элементов количеством столбцов.

##   title book_id
## 1  <NA>       1
## 2  <NA>       1
## 3  <NA>       1
## 4  <NA>       1
## 5  <NA>       1
## 6  <NA>       1

Четвертый случай (микс)

Давайте введеём два комикса без похожих, четыре нормальных, и одно случайное значение.

И на выходе получим 12 рекомендаций для существующих комиксов, строку с предупреждением, строку с пустым значением(NA)

## [1] "Try another book"
## [1] "Try another book"
## [1] "Try another book"
##                                                      title
## 1                         Please try to enter another book
## 2                                    Kamisama Kiss, Vol. 9
## 3                                   Kamisama Kiss, Vol. 17
## 4                                     Black Butler, Vol. 3
## 5                   The Power of the Parasite (Squish, #3)
## 6         Kitchen Princess, Vol. 06 (Kitchen Princess, #6)
## 7      Captain America: Steve Rogers, Volume 1: Hail Hydra
## 8                    Tsubasa: RESERVoir CHRoNiCLE, Vol. 12
## 9  Scott Pilgrim, Volume 4: Scott Pilgrim Gets It Together
## 10                           Wonder Woman, Volume 6: Bones
## 11                            Jessica Jones: Alias, Vol. 2
## 12                   Ultimate X-Men, Volume 18: Apocalypse
## 13         Guardians of the Galaxy, Volume 4: Original Sin
## 14                                                    <NA>
##                             book_id
## 1  Please try to enter another book
## 2                          13183545
## 3                          22609112
## 4                           7620623
## 5                          12993826
## 6                           1952950
## 7                          28665325
## 8                             13579
## 9                            744615
## 10                         23012564
## 11                         25066808
## 12                          3526329
## 13                         23017976
## 14                                1
Примеры collaborative filtering
## # A tibble: 10 x 3
##     book_id average_rating title                                                
##       <dbl>          <dbl> <chr>                                                
##  1 29436571           4.71 March: Book Three (March, #3)                        
##  2  6506079           4.63 Fullmetal Alchemist, Vol. 21 (Fullmetal Alchemist, #…
##  3  1111162           4.57 Skip Beat!, Vol. 09                                  
##  4 17131869           4.56 Saga, Vol. 2 (Saga, #2)                              
##  5  2201788           4.55 Yotsuba&!, Vol. 06 (Yotsuba&! #6)                    
##  6  5322056           4.55 Fruits Basket, Vol. 23                               
##  7 20697563           4.53 Attack on Titan: No Regrets, Volume 02               
##  8  1792733           4.52 美少女戦士セーラームーン新装版 12 [Bishōjo Senshi Sailor Moon Shins…
##  9  6394175           4.49 Astonishing X-Men: Omnibus                           
## 10 18932560           4.49 Saga #15

 Как было ранее показано на схеме, предварительно новому пользователю задается ряд вопросов, нацеленных на то, чтобы определить к какому их 3 типов, описанных ранее принадлежит новый.

 P.S. Так как для работы с новыми пользователями 1 и 2-го типов мы вносим их в общую базу данных, для того, чтобы получить валидные рекомендации для следующего нового пользователя, необходимо обновить goodread_review до первоначального варианта. Чтобы не забывать об этом шаге мы включили автообновление датасета до исходного при вводе данных.

 Необходимость отвечать в консоле не дает это продемонстрировать. Пройдя код и раскомментировав вы сможете сами в этом убедиться

#load("~/shared/minor2_2020/data/good_read/books_g_6.RData")
#load("~/shared/minor2_2020/data/good_read/reviews_g_6.RData")
#goodread_reviews =goodread_reviews%>% select(book_id, user_id, rating)
#user_item = goodread_reviews %>%
#pivot_wider(names_from = book_id,values_from = rating) %>%
#as.data.frame()
#rownames(user_item) = user_item$user_id
#user_item$user_id = NULL
#user_item = as.matrix(user_item)
#user = readline('are you user? yes,no,да, нет')
#if(user == 'yes'|user == 'да')
#{id = readline('what is your id?')
#id = as.character(id)}


#quantity = readline('how many recommendations do you want? write a number')
#quantity =  as.numeric(quantity)


#if(user == 'no'|user == 'нет'){
  #goodread_comics$ratings_count = as.numeric(goodread_comics$ratings_count)
  #quest = readline('are you ready to answer my questions? yes,no,да, нет')
  #if(quest == 'no'|quest == 'нет'){
    #print('no, problem')
    #lazy_answer = goodread_comics%>% arrange(desc(average_rating))%>%select(title, average_rating, book_id)
    #lazy_answer = lazy_answer[1:quantity,]
    #final_answer = lazy_answer
  #}
  #if(quest== 'yes'|quest == 'да'){
    #questions = goodread_comics%>% arrange(desc(ratings_count))%>%select(title)
    #questions = questions[1:10]
    #my_vec =vector()
    
    #for (i in 1:10){
      #ques <- readline(questions[i,]) 
      #ques = as.numeric(ques)
    #my_vec <- c(my_vec, ques)}
    #questions$rating <- my_vec
    #questions = na.omit(questions)
    #questions$user_id <- 'new'
    #questions = questions%>% left_join(goodread_comics)%>% select(book_id, rating, user_id)
    #load("~/shared/minor2_2020/data/good_read/reviews_g_6.RData")
    #goodread_reviews =goodread_reviews%>% select(book_id, user_id, rating)
    #goodread_reviews = goodread_reviews %>% full_join(questions)
    #final_answer = user_recommendation_col('new', quantity)
    
    
  #}
#}

#if (user== 'yes'|user == 'да'){
  #if(count(goodread_reviews%>% filter(user_id == id)) != 0){
      #final_answer= user_recommendation_col('new', quantity)
#}
  #if (count(goodread_reviews%>% filter(user_id == id)) == 0){
    #print('We have not found you in the list of users. No problem, rely on us:)')
    #lazy_answer = goodread_comics%>% arrange(desc(average_rating))%>%select(title, average_rating, book_id)
    #lazy_answer = lazy_answer[1:quantity,]
    #final_answer = lazy_answer
    
  #}}

  #final_answer
Примеры content-based

Ровно 12 примеров разобраны в части с оценкой системы

Выводы

Ответы на вопросы peer review

Вопрос:Проверяются ли данные на совпадение в отношении уже прочитанных пользователем комиксов?

Ответ:Да, данные проверяются, в функции встроен outer_join, позволяющий нам выкинуть комиксы, которые уже были прочитаны пользователем, прежде чем давать ему новую рекомендацию.

Вопрос: Почему в одном случае использован метод UBCF, а в другом IBCF - чем это объясняется?

Ответ:Насколько мы поняли задачу, функция дожна была стать наиболее эффективной в своем классе, то есть в классе коллаборативной фильтрации. После того, как мы провели разведывательный анализ, было выяснено, что около половины пользователей послтавили лишь 1-2 оценки, что естественно не достаточно для того, чтобы с достаточной точностью найти в пару к пользователю другого похожего на него. Ма задумались о том, каким образом может быть решена данная проблема и пришли к выводу, что IBCF станет хорошим подспорьем на данном поприще: поможет работать не с каждым пользователем, а с каждым фильмом, который был оценен на 4-5 баллов.

Вопрос: Я не поняла пункт про аккаунт пользователя в первой коллаборативной системе. Как это отличается от присутствия номера айди пользователя в системе?

Ответ:В целом, ничем не отличается. На этапе формулировки вопросов мы решили, что наиболее клиентоориентированным и привычным вопросом является вопрос о налии/отсутствии аккаунта в системе, нежели прямой вопрос о id пользователя. Более того, как Вы могли заметить, мы сначала спрашиваем о наличии аккаунта, а только потом, если ответ бл положительный, о конкретном id, что позволяет новому пользователю не пугатьс вопросов, на которые он заведомо не знает ответов.

Вопрос: Зачем после применения функции джойнить результат со всем датасетом? Много колонок, местами пустые клетки.

Ответ:То, о чем вы говорите, это промежуточный этап работы, который был проведен в ходе оценивания качества функции. Мы соединили со всем датасетом, чтоб увидеть не только самую главную информацию о фильме, которую выдает функция, но и дополнительную информацию, позволяющую провести тест на адекватность рекомендации.

Вопрос:А что будет, если новому пользователю не понравится ни один из топовых комиксов?

Ответ:Если пользователю ничего не понравилось из топа и он не хочет оценивать другие комиксы, то пусть переходит на другой сайт.

**Вопрос:* Если бы мне нравились комиксы по супермэну и бэтмэну, что бы мне порекомендовали? Если бы я был юзером, у которого куса отзывов на манги, но есть отзывы и на другие комиксы, что бы вы мне посоветовали?

Ответ: Как можно видеть по результатам, пользователь получил в рекомендациях комиксы из вселенной dс, а также другие комиксы, связанные с супергероями

user = joined_df %>% filter(popular_shelves.0.name=='dc-comics'|popular_shelves.2.name =='dc' | popular_shelves.2.name =='batman'|popular_shelves.3.name=='batman')
user  = user%>% filter(rating==5)
user %>% count(user_id) %>% arrange(-n)
## # A tibble: 93 x 2
##    user_id                              n
##    <chr>                            <int>
##  1 6305fa58820260714d2ca097d7cb82ac     4
##  2 1d02d7115117999be6c86a54360c673b     3
##  3 01a723850ff625fdee36e8bbc152e07e     2
##  4 4a8b6f4c6a692e6eea5ac097978fee32     2
##  5 60f5a8f8a4724b1a81faec3fec51922d     2
##  6 70da424cfb5d9e0e9839651405092f56     2
##  7 b50475acf92c2bc41a3710c02b93b408     2
##  8 00d538e7c57b6e1e108bc67b4e11f0f1     1
##  9 039823e43759feb87a7dd6cf37fd7600     1
## 10 056cabd396b7faa3aaf79b2e695dc51e     1
## # … with 83 more rows
user %>% filter(user_id == '6305fa58820260714d2ca097d7cb82ac')
## # A tibble: 4 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1   66483   3.27 Infi… Infinite Crisis  10305            ""            
## 2 4788225   3.66 Batm… Batman: Heart o… 61935            ""            
## 3 6672187   3.73 Batm… Batman Confiden… 28126            ""            
## 4 7939733   3.24 Batm… Batman: The Wid… 8236             ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>
getBooks('6305fa58820260714d2ca097d7cb82ac',10)
## # A tibble: 10 x 2
##    title                                                          book_id
##    <chr>                                                            <dbl>
##  1 Birds of Prey, Vol. 3: Of Like Minds                             79368
##  2 Fire and Flight (ElfQuest #1)                                    98019
##  3 The Losers, Vol. 1: Ante Up                                     103546
##  4 The Starman Omnibus, Vol. 1                                    2140338
##  5 Ex Machina, Vol. 7: Ex Cathedra (Ex Machina, #7)               2660314
##  6 Ex Machina, Vol. 9: Ring Out the Old (Ex Machina, #9)          7607300
##  7 Superman: The Black Ring Vol. 2                               10941969
##  8 Hawkeye #19                                                   22849275
##  9 Teen Titans Go! Vol. 1: Party, Party!                         23012552
## 10 Elfquest: The Final Quest (ElfQuest: The Final Quest, Vol #1) 23012630

Вопрос: Я так и не увидел оценку работы системы, основанной на коллаборативной фильтрации. Действительно ли она работает качественно?

Ответ:Мы провели техническую оценку по показателям RMSE = 1,24; MSE = 1,54; MAE = 0,88. Это значит, что наша система рекомендательная система в среднем ошибается чуть меньше, чем на 1 балл. Кажется, с технической точки зрения это значит, что она работает качественно.

Вопрос:Предположим, я слишком требовательный читатель, и пока что я не нашел ни одного комикса, который можно было оценить больше, чем на 3. Вы порекомендовали ТОП комиксов, но я их уже прочитал и поставил им заслуженные 1 или 2 балла из 5. Что вы будете делать в этом случае? Подсказка: используйте силу рандома.

Ответ:Такому пользователю мы просто порекомендуем топ по среднему рейтингу, так как ни один из предложенных комиксов ему не понравился.

Вопрос:Если я новый пользователь и хочу получить рекомендации, однако не читала предложенные комиксы из топ-списка (соответственно, не могу их оценить) и при этом хочу указать приоритетный тип комикса (например, манга) - какая рекомендация будет выдана? просто топ комиксов, топ манг или манги на рандом?

Ответ:В коллаборативной функции есть опция выбрать любимый жанр, тогда при выборе этой опции вам выйдет топ комиксов по выбранному жанру. В данном примере - топ манги.

Вопрос:Вопрос возник в начале презентации, по предворительному анализу, поскольку мало сказано о том, как это было посчитана и на основе чего даная информация, использовалась ли какая-то метрика (LDA,TF-IDF) и тд.

Ответ:В предворительном анализе нами был использован метод LDA. Однако в анализ в презентации мы его не вставили. В презентации была указана переменная prp_pos, которая была посчитана с помощью сентимент анализа.

Вопрос:Если я пользователь, которому нравится экшн манга типа Стального Алхимика, порекомендуют ли мне американские/англоязычные экшн-комиксы из супергеройских вселенных?

Ответ:Говоря о контентной фукции - да. Как и в уже разобранных нами примерах, функция скорее всего выдаст вам в основном манги, но с большой вероятностью в рекомендацию попадут и комиксы из супергеройских вселенных по типу Марвел и DC.

Вопрос: Если был бы пользователь, имеющий 5 оценок 5+ для аниме манг, и еще 5 по 5+ для исторических комиксов, то первое место в списке рекомендаций будет принадлежать комиксу из наиболее многочисленного жанра?

Ответ:Так как наша функция не имеет конкретной прописанной привязки к жанрам, имеющимся уже в оценках у пользователя, сложно заранее оценить, что она порекомендует. Предположительно, что в рекомендацию войдут оба жанра, но об их процентном распределении можно будет судить только на конкретном примере.

Вопрос:Если мой пользователь любит комиксы по гуль вселенным, а именно комиксы про Рик и Морти, будут ли ему рекомендоваться более детские комиксы по типу время приключений?

Ответ:К сожалению, у нас нет в датасе комиксов про Рика и Морти, как и комиксов “Аdventure time” и других известных аналогов, чтобы проверить, что выдаст рекомендательная система.

Вопрос:Хотелось бы проверить как работает эта система на нескольких примерах: сначала я бы ответил что не хочу создавать аккаунт, посмотрел бы на рекомендации, потом сравнил бы эти рекомендации с теми, которые были бы у меня, согласившись я на создание аккаунта. Ожидаю, что результат будет один и тот же

Ответ:Результат действительно будет один и тот же, проверили

Вопрос:Абсолютно лишним было описание видов переменных, которые были использованы в проекте, простому пользователю, да и нам, это ни к чему. Кроме того, я бы вставила результаты прогона систем в таблицу, а не переключалась на код, чтобы это показать, т.к. простой пользователь, опять е, не понял бы. К сожалению, в презентации не представлены методы оценивания и успешные/провальные примеры работы систем, а опять же представлены кодом, в котором сложно сразу что-то понять. Еще один вопрос, почему во второй системы у вас такая разбивка пользователей на группы? Там же было много разных жанров, а не только манга и фентези.

Ответ:Ответ на этот вопрос в самом начале построенной системы

**Вопрос:*Насколько изменится рекомендации системы, для двух пользователей, если разбить пользователей на другие специфические группы(жанры)? А если изменить не только группу но и пользователей? Ожидаемый результат: скорее всего рекомендовательная система выдаст хуже результат, чем 6 из 10, посокльку наибольшое количетво хороших оценок у манга и фэнтези.

Ответ:Для начала, сравним пропорции хороших и плохих оценок в случаях manga, fantasy и потенциальной полкой favorites. Заметим, что в пропорциональном соотношении, хороших оценок среди manga и fantasy не выше всех остальных, т.к. есть другие категории, которые сильно превосходят эти две категории по количеству положительных оценок, но и не стоит отрицать того факта, что manga и fantasy превосходят другие категории в пропорциональном соотношении хороших оценок.

## # A tibble: 10 x 2
##    popular_shelves.0.name prop_good
##    <chr>                      <dbl>
##  1 comics                       1.5
##  2 còmics                       0.3
##  3 dc-comics                    0.2
##  4 fantasy                      0.1
##  5 favorites                    0.2
##  6 graphic-novels               1.5
##  7 manga                        1.5
##  8 picture-books                0  
##  9 star-wars                    0.1
## 10 to-read                     58.5
## # A tibble: 30 x 2
##    popular_shelves.1.name prop_good
##    <chr>                      <dbl>
##  1 art                          0.1
##  2 bd                           0.2
##  3 comic                        0.1
##  4 comics                      25.1
##  5 cómics                       0.4
##  6 currently-reading            2.2
##  7 dc                           0.1
##  8 doctor-who                   0.1
##  9 fantasy                      0.5
## 10 favorites                    0.1
## # … with 20 more rows
## # A tibble: 55 x 2
##    popular_shelves.2.name prop_good
##    <chr>                      <dbl>
##  1 art                          0.4
##  2 asterix                      0.1
##  3 batman                       0.3
##  4 big-nate                     0.1
##  5 biography                    0.3
##  6 books-i-own                  0.2
##  7 children-s-books             0  
##  8 comedy                       0.1
##  9 comic-books                  0.1
## 10 comics                      13.3
## # … with 45 more rows
## # A tibble: 69 x 2
##    popular_shelves.3.name prop_good
##    <chr>                      <dbl>
##  1 adventure                    0  
##  2 animals                      0.2
##  3 batman                       1.5
##  4 bd                           0.1
##  5 black-butler                 0.3
##  6 books-i-own                  0.2
##  7 castle                       0  
##  8 childrens                    0.3
##  9 christian                    0.1
## 10 comic                        0.5
## # … with 59 more rows

Давайте в качестве третьей группы возьмём те комиксы, которые хотя бы в каком-то из случаев были отнесены к favorites.

Какова причина такого выбора?

Давайте начнём работу с этой категорией.

user = joined_df %>% filter(popular_shelves.0.name=='favorites'|popular_shelves.1.name =='favorites' | popular_shelves.2.name =='favorites'|popular_shelves.3.name=='favorites')
user  = user %>% filter(rating==5)

user
## # A tibble: 324 x 26
##    book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##      <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
##  1  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  2  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  3  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  4  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  5  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  6  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  7  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  8  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
##  9  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
## 10  102458   3.98 Hell… Hellboy, Vol. 1… 10182            ""            
## # … with 314 more rows, and 20 more variables: authors.1.author_id <chr>,
## #   authors.1.role <chr>, average_rating <dbl>, country_code <chr>,
## #   description <chr>, is_ebook <chr>, language_code <chr>, link <chr>,
## #   num_pages <dbl>, popular_shelves.0.name <chr>,
## #   popular_shelves.1.name <chr>, popular_shelves.2.name <chr>,
## #   popular_shelves.3.name <chr>, publication_year <dbl>, publisher <chr>,
## #   ratings_count <dbl>, series <dbl>, tseries <fct>, user_id <chr>,
## #   rating <dbl>

Посмотрим, распределение количеств “отличных” оценок среди пользователей, оценивших книги этой категории и заметим, что, в основном, это меньше трёх оценок - всего два пользователя с тремя оценками и один с четырьмя. Давайте оценим рекомендации пользователей с 2, 3 и 4 оценками.

user %>% count(user_id) %>% arrange(-n)
## # A tibble: 303 x 2
##    user_id                              n
##    <chr>                            <int>
##  1 f07b2b3332b24aeea24a566e5063e56b     4
##  2 4cc40b94cc18cf3650da122ca8f75b40     3
##  3 a410bfaed52d4b018939ccf8352a346e     3
##  4 01cd98f00ff6183b6bf9e80cc257b08b     2
##  5 37b3e60b4e4152c580fd798d405150ff     2
##  6 58a5c755fc5749ec2bbb36156db9bc17     2
##  7 5c0a76a445829482c8bbc8243734795a     2
##  8 67d3aaaedf7a929e5650d19dd3b9eef4     2
##  9 8273fc29780c84559cbd533fc969c0a6     2
## 10 8444ed5f25c636065370da187e76f8e5     2
## # … with 293 more rows

Первый пользователь

Можем заметить, что пользователь совпал со вторым пользователем из категории manga. Поэтому стоит перейти к следующему.

user %>% filter(user_id == 'f07b2b3332b24aeea24a566e5063e56b')
## # A tibble: 4 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  5.32e6   4.5  Frui… Fruits Basket, … 26306            ""            
## 2  6.51e6   4.32 Full… Fullmetal Alche… 4698899          ""            
## 3  2.08e7   4.5  ノラガミ… ノラガミ 7 [Noragam… 14507930         ""            
## 4  2.26e7   4.45 Kami… Kamisama Kiss, … 3091065          ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>
## # A tibble: 10 x 3
##    title2                         book_id title                                 
##    <chr>                            <dbl> <chr>                                 
##  1 March: Book Three (March, #3) 29436571 <NA>                                  
##  2 Saga: Book Two                32926680 <NA>                                  
##  3 <NA>                           7620623 Black Butler, Vol. 3                  
##  4 <NA>                           9404151 Kamisama Kiss, Vol. 2                 
##  5 <NA>                          13183545 Kamisama Kiss, Vol. 9                 
##  6 <NA>                          13532246 Batman: Knightfall, Vol. 3: KnightsEnd
##  7 <NA>                          21556028 Nightwing Volume 1: Blüdhaven         
##  8 <NA>                          23759966 Out of the Past (Once Upon a Time, #3)
##  9 <NA>                          25670943 Black Butler, Volume 21               
## 10 <NA>                          29633087 Midnighter, Vol. 2

Второй пользователь

Предпочтения:

Можем заметить, что все три книги - манга. Следовательно, от рекомендательных систем ожидается что-то связанное именно с этим видом литературы.

user %>% filter(user_id == 'a410bfaed52d4b018939ccf8352a346e')
## # A tibble: 3 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1  5.32e6   4.5  Frui… Fruits Basket, … 26306            ""            
## 2  7.33e6   3.46 Baku… Bakuman, Volume… 5502079          ""            
## 3  2.07e7   4.34 Atta… Attack on Titan… 5365396          "Original Aut…
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>

Обратимся к рекомендательной функции за пятью рекомендациями:

В остальных случаях, система советует что-то странное из серии DC Comics, что не есть хорошо для человека, высоко оценившего мангу. Скорее всего, система составила такие рекомендации исходя из каких-то других переменных.

2/5

## # A tibble: 5 x 25
##   title book_id avgRat title_without_s… authors.0.autho… authors.0.role
##   <chr>   <dbl>  <dbl> <chr>            <chr>            <chr>         
## 1 I Lo…  9.18e6   3.48 I Love Him to P… 3056490          ""            
## 2 Deat…  9.48e6   4.09 Death Note: Bla… 5502079          ""            
## 3 Nigh…  2.16e7   3.8  Nightwing Volum… 28710            ""            
## 4 Plat…  2.96e7   4    Platinum End, V… 5502079          ""            
## 5 Supe…  3.14e7   3.94 Superman, Volum… 171132           "Writer"      
## # … with 19 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, prp_pos <dbl>

Теперь, когда у нас есть адаптированная под названия функция, мы можем проверить системы на пересечения в рекомендациях, и оценить слабые и сильные стороны каждой. Заметим, что все рекомендации первой системы представлены также и второй системой.

##                                                         title  book_id   avgRat
## 1                               Nightwing Volume 1: Blüdhaven 21556028 3.800000
## 2                      Batman: Knightfall, Vol. 3: KnightsEnd 13532246 3.437500
## 3                        Criminal: The Deluxe Edition, Vol. 1  6676791 4.428571
## 4        I Love Him to Pieces (My Boyfriend Is a Monster, #1)  9179493 3.480000
## 5                 Superman, Volume 2: Trial of the Super Sons 31353032 3.944444
## 6 Avatar: The Last Airbender: The Rift, Part 1 (The Rift, #1) 18687079 4.160000
## 7                           Death Note: Black Edition, Vol. 2  9484096 4.090909
## 8                                        Platinum End, Vol. 1 29632245 4.000000
## 9                                               Bedlam vol. 1 17876809 4.600000
##                                          title_without_series
## 1                               Nightwing Volume 1: Blüdhaven
## 2                      Batman: Knightfall, Vol. 3: KnightsEnd
## 3                        Criminal: The Deluxe Edition, Vol. 1
## 4        I Love Him to Pieces (My Boyfriend Is a Monster, #1)
## 5                 Superman, Volume 2: Trial of the Super Sons
## 6 Avatar: The Last Airbender: The Rift, Part 1 (The Rift, #1)
## 7                           Death Note: Black Edition, Vol. 2
## 8                                        Platinum End, Vol. 1
## 9                                               Bedlam vol. 1
##   authors.0.author_id authors.0.role authors.1.author_id   authors.1.role
## 1               28710                              19020    Illustrations
## 2               28709                              19886                 
## 3               37450                              22671                 
## 4             3056490                            4277935      Illustrator
## 5              171132         Writer              241175 Writer, Penciler
## 6               68959         Writer               90808           Writer
## 7             5502079                           15577045      Illustrator
## 8             5502079                           15577045    Illustrations
## 9              255466                             748258              Art
##   average_rating country_code
## 1           4.01           US
## 2           3.86           US
## 3           4.49           US
## 4           3.77           US
## 5           3.88           US
## 6           4.33           US
## 7           4.50           US
## 8           3.92           US
## 9           4.00           US
##                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       description
## 1                                                                                                                                                                                                                                                                                                                                                                                                      Dennis O'Neil introduces Dick Grayson's brand new costume and career in Nightwing's first solo series!\nNightwing flies solo as Dick Grayson uncovers new facts about the murder of his parents--evidence suggesting there was far more to their deaths than he ever suspected. But shadowy forces have strong reasons for keeping the truth buried and send assassins to silence him forever.\nCollecting NIGHTWING #1-4, NIGHTWING #1-8.
## 2                    In the final chapter of this series, Bruce Wayne completes his improbable recovery from his broken back and is ready to resume his role as Gotham's protector. But Jean Paul Valley, the man who now patrols the night as a vicious and violent Batman, is not willing to give up his new identity. Driven to the brink of madness by inner demons, the new Batman seeks to destroy Bruce as they meet in mortal combat. But in the end, Bruce defeats Jean Paul both mentally and physically and reclaims his legendary cape and cowl.\nThis new edition includes many chapters of KNIGHTFALL never before collected.\nCollects Batman #509-510, #512-514, Batman: Shadow of the Bat #29-30, 32-34, Detective Comics #676-677, #679-681, Batman: Legends of the Dark Knight #62-63, Robin #8-9, #11-13 and Catwoman #12-13.
## 3                                                                                                                          A fantastically-designed and printed book showcasing the Eisner and Harvey Award-Winning crime comics from the creators of Sleeper and Incognito, this oversized, deluxe hardback edition features Criminal books 1 thru 3 - Cowards, Lawless, and The Dead and the Dying. Also features many extras, including a Criminal short story and the never-before-printed five page "movie trailer in comics form" that Brubaker and Phillips created to announce the series online, plus illustrations, selected articles, behind-the-scenes glimpses, painted covers, and much more! Features an introduction by comics legend and Watchmen artist Dave Gibbons.\nCollects Criminal (2006) #1-10 and Criminal (2008) #1-3.
## 4                                                                                               Can love survive the zombie apocalypse? Maybe Dicey's first chance at a real relationship was dead from the start. She's the star of her high school baseball team, and Jack's the star of the science program. Her idea of a study session includes sleeping in the sun, and his idea of a good game involves dungeons and dice. But opposites start attracting when they're assigned to be partners in a class project. Now an outbreak of a weird infection--it eats your brains and leaves you hungry for more--might not mean just the end of their first date. It might mean the end of everything. Will their relationship fall apart faster than zombies in the Florida sun, or can Dicey and Jack beat the odds and find a happy ending?
## 5                                                                           Superman and his super-son Jon are back in the second volume by best-selling author Peter J. Tomasi!\nWith Jon becoming more and more powerful by the day, Superman's greatest foes are starting to take notice of the new super-kid on the block. When one of the most evil and ruthless of Superman's rogues' gallery comes for the Man of Steel's son, Clark must decide just how far he's willing to go to protect the ones he loves.\nSuperman and Jon Kent are transported to Dinosaur Island to find the last of the Losers! Then, after a quick trip to the county fair, Jon meets his match in Damian Wayne--and the Super Sons' fathers soon put the two young heroes through their paces as a new crime-fighting team is forged!\nCollecting: Superman7-13
## 6                                                                                                                                                                                                                                                                                                                                                                            Sacred Land Defiled!\nAvatar Aang asks his friends to help him honor Yangchen's Festival--one of the highest Air Nomad holidays, which hasn't been celebrated in over one hundred years. But cryptic visits from the spirit of Avatar Yangchen herself lead Aang to discover a jointly owned Fire Nation and Earth Kingdom refinery--operating on land sacred to the Airbenders! Is this simply a case of corporate greed or is something more mysterious happening?
## 7                                                                                                                                                                                                                                                    Killer 2-for-1 value on the hit thriller Death Note!\nReads R to L (Japanese Style) for audiences T+. Contains Volumes 3 and 4 of Death Note!\nLight Yagami is an ace student with great prospects--and he's bored out of his mind. But all that changes when he finds the Death Note, a notebook dropped by a rogue Shinigami death god. Any human whose name is written in the notebook dies, and now Light has vowed to use the power of the Death Note to rid the world of evil. Will Light's noble goal succeed, or will the Death Note turn him into the very thing he fights against?
## 8 Troubled Mirai's life changes when he gains the power of an angel, but he may need to become a devil to survive in the battle against others just like him!\nAs his classmates celebrate their middle school graduation, troubled Mirai is mired in darkness. But his battle is just beginning when he receives some salvation from above in the form of an angel. Now Mirai is pitted against 12 other chosen humans in a battle in which the winner becomes the next god of the world. Mirai has an angel in his corner, but he may need to become a devil to survive.\nMirai's once-great life turned to hell after his family was killed in a mysterious accident. But now that an angel is on his side, things might be looking up. With his newly received angelic powers, can Mirai get over his tragic past and find true happiness...?
## 9                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      Fillmore Press was once Madder Red, a homicidal maniac and criminal overlord who ruled the city of Bedlam. Now he's been cured of his mania, and says he wants to help protect the place he once terrorized -- but can he be trusted?\nCollects BEDLAM 1-6
##   is_ebook language_code
## 1    false           eng
## 2    false              
## 3    false           eng
## 4    false              
## 5    false           eng
## 6    false           eng
## 7    false           eng
## 8    false           eng
## 9    false           eng
##                                                               link num_pages
## 1  https://www.goodreads.com/book/show/21556028-nightwing-volume-1       288
## 2              https://www.goodreads.com/book/show/13532246-batman       652
## 3             https://www.goodreads.com/book/show/6676791-criminal       432
## 4 https://www.goodreads.com/book/show/9179493-i-love-him-to-pieces       123
## 5   https://www.goodreads.com/book/show/31353032-superman-volume-2       168
## 6              https://www.goodreads.com/book/show/18687079-avatar        76
## 7           https://www.goodreads.com/book/show/9484096-death-note       396
## 8  https://www.goodreads.com/book/show/29632245-platinum-end-vol-1       192
## 9        https://www.goodreads.com/book/show/17876809-bedlam-vol-1       188
##   popular_shelves.0.name popular_shelves.1.name popular_shelves.2.name
## 1                to-read                 comics         graphic-novels
## 2                to-read                 comics         graphic-novels
## 3                to-read                 comics         graphic-novels
## 4                to-read         graphic-novels          graphic-novel
## 5         graphic-novels                to-read               superman
## 6                to-read         graphic-novels                 comics
## 7                to-read                  mangá         graphic-novels
## 8                  manga                to-read                fantasy
## 9         graphic-novels                 horror      currently-reading
##   popular_shelves.3.name publication_year         publisher ratings_count
## 1                     dc             2014         DC Comics           348
## 2                 batman             2012         DC Comics          1173
## 3                  crime             2009            Marvel           982
## 4                zombies             2011  Graphic Universe           980
## 5           read-in-2017             2017         DC Comics           595
## 6                fantasy             2014 Dark Horse Comics         10667
## 7            books-i-own             2011     VIZ Media LLC           795
## 8      currently-reading             2016     VIZ Media LLC           167
## 9                  image             2013      Image Comics           161
##   series tseries   prp_pos
## 1      1     yes 0.1250000
## 2      3     yes 0.3846154
## 3      1     yes 0.0000000
## 4      1     yes 0.2857143
## 5      2     yes 0.5833333
## 6      1     yes 0.5000000
## 7      2     yes 0.2142857
## 8      1     yes 0.5000000
## 9      1     yes 0.3000000

Третий пользователь

И снова две манги. Наверное, в данной нам выборке есть какая-то склонность к высокому оцениванию манги, т.к. уже третий пользователь из разряда favorites непосредственно связан с мангой.

user %>% filter(user_id == "5c0a76a445829482c8bbc8243734795a")
## # A tibble: 2 x 26
##   book_id avgRat title title_without_s… authors.0.autho… authors.0.role
##     <dbl>  <dbl> <chr> <chr>            <chr>            <chr>         
## 1 1111162   4.24 Skip… Skip Beat!, Vol… 164127           ""            
## 2 6506079   4.32 Full… Fullmetal Alche… 4698899          ""            
## # … with 20 more variables: authors.1.author_id <chr>, authors.1.role <chr>,
## #   average_rating <dbl>, country_code <chr>, description <chr>,
## #   is_ebook <chr>, language_code <chr>, link <chr>, num_pages <dbl>,
## #   popular_shelves.0.name <chr>, popular_shelves.1.name <chr>,
## #   popular_shelves.2.name <chr>, popular_shelves.3.name <chr>,
## #   publication_year <dbl>, publisher <chr>, ratings_count <dbl>, series <dbl>,
## #   tseries <fct>, user_id <chr>, rating <dbl>

Обратимся к первой системе:

Заметим странность: система рекомендует книгу, которая уже была оценена пользователем, несмотря на то, что мы исправили эту ошибку и в других случаях, где мы столкнулись с той же самой омибкой, такое не наблюдается.

## # A tibble: 5 x 25
##   title ratings_count average_rating book_id avgRat title_without_s…
##   <chr>         <dbl>          <dbl>   <dbl>  <dbl> <chr>           
## 1 Marc…          7100           4.71  2.94e7   4.56 March: Book Thr…
## 2 Saga…           866           4.68  3.29e7   4.85 Saga: Book Two  
## 3 Lock…           321           4.66  2.28e7   4.71 Locke & Key Sli…
## 4 Full…          6383           4.63  6.51e6   4.32 Fullmetal Alche…
## 5 The …           999           4.59  5.46e4   4.1  The Complete Pe…
## # … with 19 more variables: authors.0.author_id <chr>, authors.0.role <chr>,
## #   authors.1.author_id <chr>, authors.1.role <chr>, country_code <chr>,
## #   description <chr>, is_ebook <chr>, language_code <chr>, link <chr>,
## #   num_pages <dbl>, popular_shelves.0.name <chr>,
## #   popular_shelves.1.name <chr>, popular_shelves.2.name <chr>,
## #   popular_shelves.3.name <chr>, publication_year <dbl>, publisher <chr>,
## #   series <dbl>, tseries <fct>, prp_pos <dbl>
##                                       title  book_id   avgRat
## 1             Air, Volume 2: Flying Machine  6346036 2.900000
## 2 Martian Manhunter, Volume 1: The Epiphany 25810152 3.320000
## 3         Hana-Kimi, Vol. 3 (Hana-Kimi, #3)   282358 3.636364
## 4    Out of the Past (Once Upon a Time, #3) 23759966 4.083333
## 5                        Midnighter, Vol. 2 29633087 3.200000
## 6                     Kamisama Kiss, Vol. 2  9404151 3.777778
##                        title_without_series authors.0.author_id authors.0.role
## 1             Air, Volume 2: Flying Machine              815259               
## 2 Martian Manhunter, Volume 1: The Epiphany               48010         Writer
## 3         Hana-Kimi, Vol. 3 (Hana-Kimi, #3)              164153               
## 4    Out of the Past (Once Upon a Time, #3)             6851802               
## 5                        Midnighter, Vol. 2             7214373               
## 6                     Kamisama Kiss, Vol. 2             3091065               
##   authors.1.author_id authors.1.role average_rating country_code
## 1             7224101    Illustrator           3.59           US
## 2              418985    Illustrator           3.50           US
## 3             1360332     Translator           4.36           US
## 4             2820757                          3.87           US
## 5             2772318    Illustrator           3.90           US
## 6             1411091     Translator           4.47           US
##                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            description
## 1 Ladies and gentlemen, there's been a change in our flight plan. You may have heard of a group called the Etesian Front -- vigilantes dedicated to taking the skies back from terrorism. Sounds like a noble cause, right? But there's more to them than meets the eye. They're after someone I know. Someone who is either an average frequent flier -- or a terrorist. And he's got a secret. Something that will change the way we fly -- and the way we see technology -- forever.\nTo find him, we've altered course. We're en route to a country that doesn't exist on any maps. Only one person knows how to get us there: me. My name is Blythe, and I'll be your stewardess today. So buckle your seatbelts -- this will be the flight of your life.\nIn this second volume, Blythe's mysterious rescuer reveals the truth behind one of the most shocking disappearances in aviation history - a secret tied to the origin of hyperprax flight. As the race to find the device begins, Blythe must master her skills as a hyperpract. But her fear of heights may get the better of her. Blythe has traveled through a country that doesn't exist to a dimension of lost things to search for the stranger she's fallen in love with -- a man who may or may not be a terrorist. Now, they will be reunited in the strangest way possible: Trapped in 10-year-old Zayn's body, Blythe will relive his life. The things she'll learn will shock her, and perhaps forever alter her course...
## 2                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      For some time now, Martian Manhunter has been lost in our world. An alien in every aspect, he has struggled to find his place even after joining the Justice League of America, Justice League United and Stormwatch. Now his past has come back to haunt him, as an alien invasion threatens to destroy the world. In order to validate to himself, as well as the world, that he is the hero he knows himself to be, the Martian Manhunter must make the ultimate sacrifice. What happens next, is truly alien!\nThis unique new take on the longtime Justice League member is here in Martian Manhunter, Volume 1: The Epiphany, written by Rob Williams and stunning art by Eddy Barrows.\nCollecting: Martian Manhunter1-6
## 3                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      MEN AT WORK\nIzumi, his friend Nakatsu and our crossdressing heroine Mizuki are hired to work at a beach chalet run by the family of weird school nurse Dr. Umeda! But when Kagurazaka--Izumi's high-jump rival--shows up with his two younger sisters in tow, the job gets personal! Kagurazaka's attractive sister Tamami has a crush on Izumi too, and she sees Izumi's classmate Mizuki as a way to find out about the object of her affections. And then someone realizes that Mizuki's actually a girl...
## 4                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     Return to the immersive world of ABC's hit TV series Once Upon a Time with an all-new sequel to the original graphic novel, Once Upon A Time: Shadow of The Queen. Welcome to the Enchanted Forest, where the characters from classic fairy tales have come to life - and are locked in an epic struggle between good and evil! Plotted by series writer and co-executive producer Kalinda Vazquez, and co-written by returning author Corinna Bechko, this all-new blockbuster will spin four spellbinding, never-before-told tales of fan-favorite characters!
## 5                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     The edgy humor of one of DC's most unbelievable series continues here in MIDNIGHTER VOL. 2!\nThe mastermind behind the theft of the God Garden's technology is finally unveiled...and Midnighter never could have guessed the ultimate goal of the heist! However, as he recovers from one of his most brutal battles to date, Lucas Trent finds himself back in the sights of Spyral... and the Suicide Squad!\nWriter Steve Orlando and illustrator ACO continue their critically accalimed run with MIDNIGHTER VOL. 2. Collects issues #7-13.
## 6                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        A divine comedy!\nReads R to L (Japanese Style) T audience.\nNanami Momozono is alone and homeless after her dad skips town to evade his gambling debts and the debt collectors kick her out of her apartment. So when a man she's just saved from a dog offers her his home, she jumps at the opportunity. But it turns out that his place is a shrine, and Nanami has unwittingly taken over his job as a local deity!\nNanami doesn't want to miss out on the fun when a hot teen idol joins the student body. Tomoe reluctantly agrees to let her go, as long as she conceals her divine mark. After all, what could possibly go wrong at high school...?
##   is_ebook language_code
## 1    false           eng
## 2    false           eng
## 3    false         en-US
## 4    false           eng
## 5    false           eng
## 6    false           eng
##                                                                      link
## 1                https://www.goodreads.com/book/show/6346036-air-volume-2
## 2 https://www.goodreads.com/book/show/25810152-martian-manhunter-volume-1
## 3              https://www.goodreads.com/book/show/282358.Hana_Kimi_Vol_3
## 4            https://www.goodreads.com/book/show/23759966-out-of-the-past
## 5           https://www.goodreads.com/book/show/29633087-midnighter-vol-2
## 6         https://www.goodreads.com/book/show/9404151-kamisama-kiss-vol-2
##   num_pages popular_shelves.0.name popular_shelves.1.name
## 1       126                to-read         graphic-novels
## 2       160                to-read                 comics
## 3       200                  manga                to-read
## 4        NA                to-read         graphic-novels
## 5       144                to-read                 comics
## 6       200                to-read                  manga
##   popular_shelves.2.name popular_shelves.3.name publication_year      publisher
## 1                 comics          graphic-novel             2009        Vertigo
## 2         graphic-novels                     dc             2016      DC Comics
## 3                romance                 shoujo             2004 VIZ Media, LLC
## 4                 comics                fantasy             2015               
## 5         graphic-novels              dc-comics             2016      DC Comics
## 6                fantasy                romance             2011  VIZ Media LLC
##   ratings_count series tseries   prp_pos
## 1           652      2     yes 0.3888889
## 2           318      1     yes 0.2500000
## 3          4208      3     yes 0.6250000
## 4           309      3     yes 0.6666667
## 5           264      2     yes 0.3333333
## 6          4355      2     yes 0.4545455

#Вывод:

 Итак, в этом отчете мы провели детальный анализ, который помог нам понять, какие данные представлены в нашем датасете, выявить закономерности и просто познакомиться с пользователями. Этот этап был несомненно важен, так как в функциях были не только применены общие методы для создания функций, но и введены исключения, относящиеся непосредственно к нашей выборке, не лишенной своих особенностей.

 Для наиболее точных рекомендаций нами были созданы 3 функции: collaborating filtering, content-based и content-based для ного пользователя. Все функции дают достаточно хорошие результаты, однако и их есть в чем совершенствовать.

 Подводя итог всему вышесказанному, разработка таких систем - только начало в вопросах такого рода, так как для выявления всех тонкостей системы, всех ее недочётов или нерассмотренных исключений требудет не только большего объема данных, но и несколько других методов, которые бы смогли детальнее анализировать не только самих пользователей, но и фильм, учиться с каждым новым отзывов. Это открывает нам путь к новой части data science — машинному обучению.