{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "initial_id", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:02:01.021005Z", "start_time": "2024-12-01T15:01:58.161848Z" }, "collapsed": true }, "outputs": [], "source": [ "import itertools\n", "import numpy as np\n", "import pandas as pd\n", "from collections import Counter\n", "from sklearn.preprocessing import LabelEncoder\n", "from sklearn.preprocessing import MultiLabelBinarizer" ] }, { "cell_type": "code", "execution_count": 2, "id": "9b91b6a97eb2b9be", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:02:57.510795Z", "start_time": "2024-12-01T15:02:01.039033Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1259417, 7)\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
book_idtitledescriptionpublication_yearpublisherauthorssimilar_books
01333909Good HarborAnita Diamant's international bestseller \"The ...2001Simon & Schuster Audio[626222][8709549, 17074050, 28937, 158816, 228563, 112...
17327624The Unschooled Wizard (Sun Wolf and Starhawk, ...Omnibus book club edition containing the Ladie...1987Nelson Doubleday, Inc.[10333][19997, 828466, 1569323, 425389, 1176674, 2627...
26066819Best Friends ForeverAddie Downs and Valerie Adler were eight when ...2009Atria Books[9212][6604176, 6054190, 2285777, 82641, 7569453, 70...
3287141The Aeneid for Boys and GirlsRelates in vigorous prose the tale of Aeneas, ...2006Yesterday's Classics[3041852][]
46066812All's Fairy in Love and War (Avalon: Web of Ma...To Kara's astonishment, she discovers that a p...2009Seven Seas[19158][948696, 439885, 274955, 12978730, 372986, 216...
\n", "
" ], "text/plain": [ " book_id title \\\n", "0 1333909 Good Harbor \n", "1 7327624 The Unschooled Wizard (Sun Wolf and Starhawk, ... \n", "2 6066819 Best Friends Forever \n", "3 287141 The Aeneid for Boys and Girls \n", "4 6066812 All's Fairy in Love and War (Avalon: Web of Ma... \n", "\n", " description publication_year \\\n", "0 Anita Diamant's international bestseller \"The ... 2001 \n", "1 Omnibus book club edition containing the Ladie... 1987 \n", "2 Addie Downs and Valerie Adler were eight when ... 2009 \n", "3 Relates in vigorous prose the tale of Aeneas, ... 2006 \n", "4 To Kara's astonishment, she discovers that a p... 2009 \n", "\n", " publisher authors \\\n", "0 Simon & Schuster Audio [626222] \n", "1 Nelson Doubleday, Inc. [10333] \n", "2 Atria Books [9212] \n", "3 Yesterday's Classics [3041852] \n", "4 Seven Seas [19158] \n", "\n", " similar_books \n", "0 [8709549, 17074050, 28937, 158816, 228563, 112... \n", "1 [19997, 828466, 1569323, 425389, 1176674, 2627... \n", "2 [6604176, 6054190, 2285777, 82641, 7569453, 70... \n", "3 [] \n", "4 [948696, 439885, 274955, 12978730, 372986, 216... " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df = pd.read_csv('goodreads_books.csv')\n", "df = df[df['title'].notna()]\n", "df['authors'] =df['authors'].apply(eval)\n", "df['similar_books'] =df['similar_books'].apply(eval)\n", "print(df.shape)\n", "df.head()" ] }, { "cell_type": "code", "execution_count": 3, "id": "6ca5d8672eb45020", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:02:59.577742Z", "start_time": "2024-12-01T15:02:57.692112Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of books that have similar books 640364\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
book_idtitledescriptionpublication_yearpublisherauthorssimilar_books
01333909Good HarborAnita Diamant's international bestseller \"The ...2001Simon & Schuster Audio[626222][8709549, 17074050, 28937, 158816, 228563, 112...
17327624The Unschooled Wizard (Sun Wolf and Starhawk, ...Omnibus book club edition containing the Ladie...1987Nelson Doubleday, Inc.[10333][19997, 828466, 1569323, 425389, 1176674, 2627...
26066819Best Friends ForeverAddie Downs and Valerie Adler were eight when ...2009Atria Books[9212][6604176, 6054190, 2285777, 82641, 7569453, 70...
46066812All's Fairy in Love and War (Avalon: Web of Ma...To Kara's astonishment, she discovers that a p...2009Seven Seas[19158][948696, 439885, 274955, 12978730, 372986, 216...
6287149The Devil's NotebookWisdom, humor, and dark observations by the fo...2000Feral House[2983296, 40075][287151, 1104760, 1172822, 440292, 287082, 630...
\n", "
" ], "text/plain": [ " book_id title \\\n", "0 1333909 Good Harbor \n", "1 7327624 The Unschooled Wizard (Sun Wolf and Starhawk, ... \n", "2 6066819 Best Friends Forever \n", "4 6066812 All's Fairy in Love and War (Avalon: Web of Ma... \n", "6 287149 The Devil's Notebook \n", "\n", " description publication_year \\\n", "0 Anita Diamant's international bestseller \"The ... 2001 \n", "1 Omnibus book club edition containing the Ladie... 1987 \n", "2 Addie Downs and Valerie Adler were eight when ... 2009 \n", "4 To Kara's astonishment, she discovers that a p... 2009 \n", "6 Wisdom, humor, and dark observations by the fo... 2000 \n", "\n", " publisher authors \\\n", "0 Simon & Schuster Audio [626222] \n", "1 Nelson Doubleday, Inc. [10333] \n", "2 Atria Books [9212] \n", "4 Seven Seas [19158] \n", "6 Feral House [2983296, 40075] \n", "\n", " similar_books \n", "0 [8709549, 17074050, 28937, 158816, 228563, 112... \n", "1 [19997, 828466, 1569323, 425389, 1176674, 2627... \n", "2 [6604176, 6054190, 2285777, 82641, 7569453, 70... \n", "4 [948696, 439885, 274955, 12978730, 372986, 216... \n", "6 [287151, 1104760, 1172822, 440292, 287082, 630... " ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "has_similar_books1 = df['similar_books'].apply(len) > 0\n", "has_similar_books1.head()\n", "\n", "all_similar_books = np.array(list(itertools.chain(*(df['similar_books'].values))))\n", "has_similar_books2 = np.isin(df['book_id'], all_similar_books)\n", "\n", "has_similar_books = has_similar_books1 | has_similar_books2\n", "\n", "df = df[has_similar_books]\n", "print('Number of books that have similar books', df.shape[0])\n", "df.head()" ] }, { "cell_type": "code", "execution_count": null, "id": "6846b3dccaf40875", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 4, "id": "d239e42cfd34de80", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:02:59.627408Z", "start_time": "2024-12-01T15:02:59.621594Z" } }, "outputs": [], "source": [ "data = {}" ] }, { "cell_type": "markdown", "id": "cffdf6de4137a3a0", "metadata": {}, "source": [ "## Labels" ] }, { "cell_type": "code", "execution_count": 5, "id": "d3b34765c70b3dc0", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:23.519314Z", "start_time": "2024-12-01T15:02:59.779801Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
book_idgenres
05333265[history, historical fiction, biography]
11333909[history, historical fiction, biography]
27327624[fantasy, paranormal, mystery, thriller, crime...
36066819[romance, mystery, thriller, crime]
4287141[history, historical fiction, biography, child...
\n", "
" ], "text/plain": [ " book_id genres\n", "0 5333265 [history, historical fiction, biography]\n", "1 1333909 [history, historical fiction, biography]\n", "2 7327624 [fantasy, paranormal, mystery, thriller, crime...\n", "3 6066819 [romance, mystery, thriller, crime]\n", "4 287141 [history, historical fiction, biography, child..." ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "genres = pd.read_csv('goodreads_book_genres_initial.csv')\n", "genres['genres'] = genres['genres'].apply(eval)\n", "genres.head()" ] }, { "cell_type": "code", "execution_count": 6, "id": "55c11b0fe27fe6e8", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:25.895897Z", "start_time": "2024-12-01T15:03:23.616794Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(594484, 8)\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
book_idtitledescriptionpublication_yearpublisherauthorssimilar_booksgenres
01333909Good HarborAnita Diamant's international bestseller \"The ...2001Simon & Schuster Audio[626222][8709549, 17074050, 28937, 158816, 228563, 112...[history, historical fiction, biography]
17327624The Unschooled Wizard (Sun Wolf and Starhawk, ...Omnibus book club edition containing the Ladie...1987Nelson Doubleday, Inc.[10333][19997, 828466, 1569323, 425389, 1176674, 2627...[fantasy, paranormal, mystery, thriller, crime...
26066819Best Friends ForeverAddie Downs and Valerie Adler were eight when ...2009Atria Books[9212][6604176, 6054190, 2285777, 82641, 7569453, 70...[romance, mystery, thriller, crime]
36066812All's Fairy in Love and War (Avalon: Web of Ma...To Kara's astonishment, she discovers that a p...2009Seven Seas[19158][948696, 439885, 274955, 12978730, 372986, 216...[fantasy, paranormal, young-adult, children]
4287149The Devil's NotebookWisdom, humor, and dark observations by the fo...2000Feral House[2983296, 40075][287151, 1104760, 1172822, 440292, 287082, 630...[history, historical fiction, biography]
\n", "
" ], "text/plain": [ " book_id title \\\n", "0 1333909 Good Harbor \n", "1 7327624 The Unschooled Wizard (Sun Wolf and Starhawk, ... \n", "2 6066819 Best Friends Forever \n", "3 6066812 All's Fairy in Love and War (Avalon: Web of Ma... \n", "4 287149 The Devil's Notebook \n", "\n", " description publication_year \\\n", "0 Anita Diamant's international bestseller \"The ... 2001 \n", "1 Omnibus book club edition containing the Ladie... 1987 \n", "2 Addie Downs and Valerie Adler were eight when ... 2009 \n", "3 To Kara's astonishment, she discovers that a p... 2009 \n", "4 Wisdom, humor, and dark observations by the fo... 2000 \n", "\n", " publisher authors \\\n", "0 Simon & Schuster Audio [626222] \n", "1 Nelson Doubleday, Inc. [10333] \n", "2 Atria Books [9212] \n", "3 Seven Seas [19158] \n", "4 Feral House [2983296, 40075] \n", "\n", " similar_books \\\n", "0 [8709549, 17074050, 28937, 158816, 228563, 112... \n", "1 [19997, 828466, 1569323, 425389, 1176674, 2627... \n", "2 [6604176, 6054190, 2285777, 82641, 7569453, 70... \n", "3 [948696, 439885, 274955, 12978730, 372986, 216... \n", "4 [287151, 1104760, 1172822, 440292, 287082, 630... \n", "\n", " genres \n", "0 [history, historical fiction, biography] \n", "1 [fantasy, paranormal, mystery, thriller, crime... \n", "2 [romance, mystery, thriller, crime] \n", "3 [fantasy, paranormal, young-adult, children] \n", "4 [history, historical fiction, biography] " ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "books = pd.merge(df, genres, on='book_id', how='left')\n", "books = books[~books['genres'].isna()]\n", "books = books[books['genres'].apply(len)>0]\n", "print(books.shape)\n", "books.head()" ] }, { "cell_type": "code", "execution_count": 7, "id": "c0a46d2d54eadc71", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:27.087963Z", "start_time": "2024-12-01T15:03:26.056872Z" } }, "outputs": [], "source": [ "label_encoder = MultiLabelBinarizer(sparse_output=True)\n", "labels = label_encoder.fit_transform(books['genres']).astype(np.bool_)" ] }, { "cell_type": "code", "execution_count": 8, "id": "f30a5996f451165c", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:27.164320Z", "start_time": "2024-12-01T15:03:27.157773Z" } }, "outputs": [], "source": [ "data['book_labels'] = labels" ] }, { "cell_type": "markdown", "id": "dd38e5df5bf7243c", "metadata": {}, "source": [ "## Book-Author Links" ] }, { "cell_type": "code", "execution_count": 9, "id": "6ee5abdfe0caf84", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:28.025301Z", "start_time": "2024-12-01T15:03:27.250118Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of authors 147863\n" ] }, { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
authorcount
181237152000
933891739
35937801544
21119471418
15346251209
\n", "
" ], "text/plain": [ " author count\n", "18 123715 2000\n", "9 3389 1739\n", "359 3780 1544\n", "2111 947 1418\n", "1534 625 1209" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "authors = list(itertools.chain(*(books['authors'].values)))\n", "author_count_dict = Counter(authors)\n", "author_count_df = pd.DataFrame(list(author_count_dict.items()), columns=['author', 'count'])\n", "print('Number of authors', author_count_df.shape[0])\n", "author_count_df.sort_values(by='count', ascending=False).head()" ] }, { "cell_type": "code", "execution_count": 10, "id": "f8fdc6fae6ed6a11", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:31.862308Z", "start_time": "2024-12-01T15:03:28.116806Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of book-author links: 826369\n" ] } ], "source": [ "book_ids = np.concatenate([np.full(count, i) \n", " for i, count in enumerate(books['authors'].apply(len))])\n", "\n", "author_id_encoder = LabelEncoder()\n", "author_ids = author_id_encoder.fit_transform(authors).astype(np.int32)\n", "\n", "print('Number of book-author links:', author_ids.shape[0])\n", "\n", "data['book-author'] = (book_ids, author_ids)" ] }, { "cell_type": "code", "execution_count": null, "id": "a5a30970b7fae165", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "1380cf57160349e2", "metadata": {}, "source": [ "## Book-Publisher Links" ] }, { "cell_type": "code", "execution_count": 11, "id": "243f23406fe1c845", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:32.182494Z", "start_time": "2024-12-01T15:03:31.968836Z" } }, "outputs": [], "source": [ "books['publisher'] = books['publisher'].str.lower()" ] }, { "cell_type": "code", "execution_count": 12, "id": "36d25bd5e5d2b5ae", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:32.942637Z", "start_time": "2024-12-01T15:03:32.260068Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of publishers: 43910\n" ] } ], "source": [ "publisher_id_encoder = LabelEncoder()\n", "publisher_ids = publisher_id_encoder.fit_transform(books['publisher'])\n", "print('Number of publishers:', publisher_ids.max()+1)" ] }, { "cell_type": "code", "execution_count": 13, "id": "14631f9a7bb9eb09", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:32.972437Z", "start_time": "2024-12-01T15:03:32.962111Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of book-publisher links: 594484\n" ] } ], "source": [ "book_ids = np.arange(books.shape[0])\n", "publisher_ids = publisher_ids.astype(np.uint16)\n", "\n", "print('Number of book-publisher links:', publisher_ids.shape[0])\n", "data['book-publisher'] = (book_ids, publisher_ids)" ] }, { "cell_type": "code", "execution_count": null, "id": "6a7f6d07b544bcfb", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "5881666538c61e9b", "metadata": {}, "source": [ "## Book-Book Links" ] }, { "cell_type": "code", "execution_count": 14, "id": "c3fae65aa006b6b", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:33.241692Z", "start_time": "2024-12-01T15:03:33.214832Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
book_idtitledescriptionpublication_yearpublisherauthorssimilar_booksgenres
01333909Good HarborAnita Diamant's international bestseller \"The ...2001simon & schuster audio[626222][8709549, 17074050, 28937, 158816, 228563, 112...[history, historical fiction, biography]
17327624The Unschooled Wizard (Sun Wolf and Starhawk, ...Omnibus book club edition containing the Ladie...1987nelson doubleday, inc.[10333][19997, 828466, 1569323, 425389, 1176674, 2627...[fantasy, paranormal, mystery, thriller, crime...
26066819Best Friends ForeverAddie Downs and Valerie Adler were eight when ...2009atria books[9212][6604176, 6054190, 2285777, 82641, 7569453, 70...[romance, mystery, thriller, crime]
36066812All's Fairy in Love and War (Avalon: Web of Ma...To Kara's astonishment, she discovers that a p...2009seven seas[19158][948696, 439885, 274955, 12978730, 372986, 216...[fantasy, paranormal, young-adult, children]
4287149The Devil's NotebookWisdom, humor, and dark observations by the fo...2000feral house[2983296, 40075][287151, 1104760, 1172822, 440292, 287082, 630...[history, historical fiction, biography]
\n", "
" ], "text/plain": [ " book_id title \\\n", "0 1333909 Good Harbor \n", "1 7327624 The Unschooled Wizard (Sun Wolf and Starhawk, ... \n", "2 6066819 Best Friends Forever \n", "3 6066812 All's Fairy in Love and War (Avalon: Web of Ma... \n", "4 287149 The Devil's Notebook \n", "\n", " description publication_year \\\n", "0 Anita Diamant's international bestseller \"The ... 2001 \n", "1 Omnibus book club edition containing the Ladie... 1987 \n", "2 Addie Downs and Valerie Adler were eight when ... 2009 \n", "3 To Kara's astonishment, she discovers that a p... 2009 \n", "4 Wisdom, humor, and dark observations by the fo... 2000 \n", "\n", " publisher authors \\\n", "0 simon & schuster audio [626222] \n", "1 nelson doubleday, inc. [10333] \n", "2 atria books [9212] \n", "3 seven seas [19158] \n", "4 feral house [2983296, 40075] \n", "\n", " similar_books \\\n", "0 [8709549, 17074050, 28937, 158816, 228563, 112... \n", "1 [19997, 828466, 1569323, 425389, 1176674, 2627... \n", "2 [6604176, 6054190, 2285777, 82641, 7569453, 70... \n", "3 [948696, 439885, 274955, 12978730, 372986, 216... \n", "4 [287151, 1104760, 1172822, 440292, 287082, 630... \n", "\n", " genres \n", "0 [history, historical fiction, biography] \n", "1 [fantasy, paranormal, mystery, thriller, crime... \n", "2 [romance, mystery, thriller, crime] \n", "3 [fantasy, paranormal, young-adult, children] \n", "4 [history, historical fiction, biography] " ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "books.head()" ] }, { "cell_type": "code", "execution_count": 15, "id": "1b5c2f8770c233c1", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:37.317930Z", "start_time": "2024-12-01T15:03:33.565952Z" } }, "outputs": [], "source": [ "book_ids = np.concatenate([np.full(count, i) \n", " for i, count in enumerate(books['similar_books'].apply(len))])" ] }, { "cell_type": "code", "execution_count": 16, "id": "d9a0f2ea5eafc2b7", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:38.723310Z", "start_time": "2024-12-01T15:03:37.413450Z" } }, "outputs": [], "source": [ "similar_book_ids = np.array(list(itertools.chain(*(books['similar_books'].values))))" ] }, { "cell_type": "code", "execution_count": 17, "id": "98d12cf75643deb5", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:39.188161Z", "start_time": "2024-12-01T15:03:38.734349Z" } }, "outputs": [], "source": [ "mask = np.isin(similar_book_ids, books['book_id'].values)\n", "book_ids = book_ids[mask]\n", "similar_book_ids = similar_book_ids[mask]" ] }, { "cell_type": "code", "execution_count": 18, "id": "71668c7c67f579a1", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:48.529895Z", "start_time": "2024-12-01T15:03:39.420886Z" } }, "outputs": [], "source": [ "book_id_map = dict(zip(books['book_id'].values, range(len(book_ids))))\n", "similar_book_ids = np.array([book_id_map[_] for _ in similar_book_ids])" ] }, { "cell_type": "code", "execution_count": 19, "id": "fbfc9064c9306926", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:49.570122Z", "start_time": "2024-12-01T15:03:49.436004Z" } }, "outputs": [], "source": [ "# Save memory\n", "mask = book_ids < similar_book_ids\n", "book_ids = book_ids[mask]\n", "similar_book_ids = similar_book_ids[mask]" ] }, { "cell_type": "code", "execution_count": 20, "id": "8edc9d69e5eadb21", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:50.457376Z", "start_time": "2024-12-01T15:03:50.449784Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of book-book links: 3510209\n" ] } ], "source": [ "print('Number of book-book links:', similar_book_ids.shape[0])\n", "data['book-book'] = (book_ids, similar_book_ids)" ] }, { "cell_type": "code", "execution_count": null, "id": "8cc7b055644c1d42", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 21, "id": "32ff5477051870d5", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:51.333417Z", "start_time": "2024-12-01T15:03:51.323284Z" } }, "outputs": [], "source": [ "book_years = (books['publication_year']).values.astype(np.int16)\n", "data['book_years'] = book_years" ] }, { "cell_type": "code", "execution_count": 22, "id": "3f59be40f4948310", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:52.244019Z", "start_time": "2024-12-01T15:03:52.229147Z" } }, "outputs": [ { "data": { "text/plain": [ "{'book_labels': ,\n", " 'book-author': (array([ 0, 1, 2, ..., 594482, 594482, 594483]),\n", " array([ 53976, 3557, 3138, ..., 784, 81819, 128754])),\n", " 'book-publisher': (array([ 0, 1, 2, ..., 594481, 594482, 594483]),\n", " array([36145, 27416, 2948, ..., 16709, 27036, 16233], dtype=uint16)),\n", " 'book-book': (array([ 0, 0, 0, ..., 594468, 594476, 594476]),\n", " array([236765, 406277, 529992, ..., 594479, 594481, 594479])),\n", " 'book_years': array([2001, 1987, 2009, ..., 2007, 2015, 2014], dtype=int16)}" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "data" ] }, { "cell_type": "code", "execution_count": 23, "id": "a0867ffd9f4ee3f9", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T15:03:53.251143Z", "start_time": "2024-12-01T15:03:53.174887Z" } }, "outputs": [], "source": [ "import pickle\n", "\n", "with open('book.pkl', 'wb') as f:\n", " pickle.dump(data, f)" ] }, { "cell_type": "code", "execution_count": 15, "id": "1d4bf279de35c717", "metadata": { "ExecuteTime": { "end_time": "2024-12-01T14:30:28.500440Z", "start_time": "2024-12-01T14:30:18.334222Z" } }, "outputs": [], "source": [ "books.to_csv('Book.csv', index=False)" ] }, { "cell_type": "markdown", "id": "7487e86adadcaec", "metadata": {}, "source": [ "### Node Features\n", "\n", "We generate embeddings as features for each node in the graph. Node embeddings are generated by passing the title and the description through a Sentence-BERT model and obtaining a 384-embedding vector for each movie node.\n", "\n", "\n", "According to [Sentence-Transformers docs](https://www.sbert.net/docs/pretrained_models.html), the **all-MiniLM-L6-v2** model provides the best quality. So we use it to generate node features.\n", "\n", "all-MiniLM-L6-v2\n", "\n", "Description:\tAll-round model tuned for many use-cases. Trained on a large and diverse dataset of over 1 billion training pairs.\n", "Base Model:\tnreimers/MiniLM-L6-H384-uncased\n", "Max Sequence Length:\t256\n", "Dimensions:\t384\n", "Normalized Embeddings:\ttrue\n", "Suitable Score Functions:\tdot-product (util.dot_score), cosine-similarity (util.cos_sim), euclidean distance\n", "Size:\t80 MB\n", "Pooling:\tMean Pooling\n", "Training Data:\t1B+ training pairs. For details, see model card.\n", "Model Card:\thttps://huggingface.co/sentence-transformers/all-MiniLM-L6-v2\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "15e53898382782a0", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
book_idtitledescriptionpublication_yearpublisherauthorssimilar_booksgenres
01333909Good HarborAnita Diamant's international bestseller \"The ...2001simon & schuster audio[626222][8709549, 17074050, 28937, 158816, 228563, 112...['history, historical fiction, biography']
17327624The Unschooled Wizard (Sun Wolf and Starhawk, ...Omnibus book club edition containing the Ladie...1987nelson doubleday, inc.[10333][19997, 828466, 1569323, 425389, 1176674, 2627...['fantasy, paranormal', 'mystery, thriller, cr...
26066819Best Friends ForeverAddie Downs and Valerie Adler were eight when ...2009atria books[9212][6604176, 6054190, 2285777, 82641, 7569453, 70...['romance', 'mystery, thriller, crime']
36066812All's Fairy in Love and War (Avalon: Web of Ma...To Kara's astonishment, she discovers that a p...2009seven seas[19158][948696, 439885, 274955, 12978730, 372986, 216...['fantasy, paranormal', 'young-adult', 'childr...
4287149The Devil's NotebookWisdom, humor, and dark observations by the fo...2000feral house[2983296, 40075][287151, 1104760, 1172822, 440292, 287082, 630...['history, historical fiction, biography']
\n", "
" ], "text/plain": [ " book_id title \\\n", "0 1333909 Good Harbor \n", "1 7327624 The Unschooled Wizard (Sun Wolf and Starhawk, ... \n", "2 6066819 Best Friends Forever \n", "3 6066812 All's Fairy in Love and War (Avalon: Web of Ma... \n", "4 287149 The Devil's Notebook \n", "\n", " description publication_year \\\n", "0 Anita Diamant's international bestseller \"The ... 2001 \n", "1 Omnibus book club edition containing the Ladie... 1987 \n", "2 Addie Downs and Valerie Adler were eight when ... 2009 \n", "3 To Kara's astonishment, she discovers that a p... 2009 \n", "4 Wisdom, humor, and dark observations by the fo... 2000 \n", "\n", " publisher authors \\\n", "0 simon & schuster audio [626222] \n", "1 nelson doubleday, inc. [10333] \n", "2 atria books [9212] \n", "3 seven seas [19158] \n", "4 feral house [2983296, 40075] \n", "\n", " similar_books \\\n", "0 [8709549, 17074050, 28937, 158816, 228563, 112... \n", "1 [19997, 828466, 1569323, 425389, 1176674, 2627... \n", "2 [6604176, 6054190, 2285777, 82641, 7569453, 70... \n", "3 [948696, 439885, 274955, 12978730, 372986, 216... \n", "4 [287151, 1104760, 1172822, 440292, 287082, 630... \n", "\n", " genres \n", "0 ['history, historical fiction, biography'] \n", "1 ['fantasy, paranormal', 'mystery, thriller, cr... \n", "2 ['romance', 'mystery, thriller, crime'] \n", "3 ['fantasy, paranormal', 'young-adult', 'childr... \n", "4 ['history, historical fiction, biography'] " ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "\n", "books = pd.read_csv('Book.csv')\n", "books.head()" ] }, { "cell_type": "code", "execution_count": 2, "id": "b3cfbb60", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'book_labels': ,\n", " 'book-author': (array([ 0, 1, 2, ..., 594482, 594482, 594483], dtype=int32),\n", " array([ 53976, 3557, 3138, ..., 784, 81819, 128754], dtype=int32)),\n", " 'book-publisher': (array([ 0, 1, 2, ..., 594481, 594482, 594483], dtype=int32),\n", " array([36145, 27416, 2948, ..., 16709, 27036, 16233], dtype=uint16)),\n", " 'book-book': (array([ 0, 0, 0, ..., 594468, 594476, 594476], dtype=int32),\n", " array([236765, 406277, 529992, ..., 594479, 594481, 594479], dtype=int32)),\n", " 'book_years': array([2001, 1987, 2009, ..., 2007, 2015, 2014], dtype=int16)}" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pickle\n", "\n", "with open('book.pkl', 'rb') as f:\n", " data = pickle.load(f)\n", "data" ] }, { "cell_type": "code", "execution_count": 3, "id": "7bd49dd4", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/usr/local/lib/python3.10/dist-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] }, { "data": { "text/plain": [ "SentenceTransformer(\n", " (0): Transformer({'max_seq_length': 256, 'do_lower_case': False}) with Transformer model: BertModel \n", " (1): Pooling({'word_embedding_dimension': 384, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})\n", " (2): Normalize()\n", ")" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import torch\n", "from sentence_transformers import SentenceTransformer\n", "\n", "device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n", "model = SentenceTransformer('../sentence-transformers/all-MiniLM-L6-v2', device=device)\n", "model" ] }, { "cell_type": "code", "execution_count": 4, "id": "b86eb9fc", "metadata": {}, "outputs": [], "source": [ "text = books['title'] + ' ' + books['description']" ] }, { "cell_type": "code", "execution_count": 5, "id": "ab1586ef", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "Batches: 100%|██████████| 146/146 [07:21<00:00, 3.02s/it]\n" ] } ], "source": [ "feats = model.encode(text, batch_size=4096, show_progress_bar=True, convert_to_numpy=True)" ] }, { "cell_type": "code", "execution_count": 9, "id": "f6b5c92e", "metadata": {}, "outputs": [], "source": [ "data['book_feats'] = feats" ] }, { "cell_type": "code", "execution_count": 11, "id": "497721b0", "metadata": {}, "outputs": [], "source": [ "with open('book.pkl', 'wb') as f:\n", " pickle.dump(data, f)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.12" } }, "nbformat": 4, "nbformat_minor": 5 }