├── .gitignore
├── LICENSE
├── README.md
├── deeplogit
├── __init__.py
├── deeplogit.py
├── embeddings.py
└── pca.py
├── examples
├── example.py
└── example_data
│ ├── images
│ ├── 21.jpg
│ ├── 23.jpg
│ ├── 29.jpg
│ ├── 3.jpg
│ ├── 4.jpg
│ ├── 45.jpg
│ ├── 46.jpg
│ ├── 47.jpg
│ ├── 8.jpg
│ └── 9.jpg
│ ├── long_choice_data.csv
│ └── texts
│ ├── books.csv
│ ├── descriptions.csv
│ ├── reviews.csv
│ └── titles.csv
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # UV
98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | #uv.lock
102 |
103 | # poetry
104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105 | # This is especially recommended for binary packages to ensure reproducibility, and is more
106 | # commonly ignored for libraries.
107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108 | #poetry.lock
109 |
110 | # pdm
111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112 | #pdm.lock
113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114 | # in version control.
115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116 | .pdm.toml
117 | .pdm-python
118 | .pdm-build/
119 |
120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121 | __pypackages__/
122 |
123 | # Celery stuff
124 | celerybeat-schedule
125 | celerybeat.pid
126 |
127 | # SageMath parsed files
128 | *.sage.py
129 |
130 | # Environments
131 | .env
132 | .venv
133 | env/
134 | venv/
135 | ENV/
136 | env.bak/
137 | venv.bak/
138 |
139 | # Spyder project settings
140 | .spyderproject
141 | .spyproject
142 |
143 | # Rope project settings
144 | .ropeproject
145 |
146 | # mkdocs documentation
147 | /site
148 |
149 | # mypy
150 | .mypy_cache/
151 | .dmypy.json
152 | dmypy.json
153 |
154 | # Pyre type checker
155 | .pyre/
156 |
157 | # pytype static type analyzer
158 | .pytype/
159 |
160 | # Cython debug symbols
161 | cython_debug/
162 |
163 | # PyCharm
164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166 | # and can be added to the global gitignore or merged into this file. For a more nuclear
167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168 | #.idea/
169 |
170 | # PyPI configuration file
171 | .pypirc
172 |
173 | venv/
174 | .DS_Store
175 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # deeplogit: Mixed Logit Estimation with Text and Image Embeddings Extracted Using Deep Learning Models
2 |
3 | ## Overview
4 |
5 | This package provides a class [`DeepLogit`](https://github.com/franklinshe/DeepLogit/blob/master/deeplogit/deeplogit.py) that can be used to estimate a mixed logit model with text and image embeddings extracted using deep learning models. The class provides methods to preprocess text and image data, fit the model, and make predictions.
6 |
7 | The DeepLogit package relies heavily on the xlogit library for the implementation of the mixed logit model. For more information on the xlogit library, see the [xlogit repository](https://github.com/arteagac/xlogit/).
8 |
9 |
10 | ## Installation
11 |
12 | This package is supported on Python 3.9. Please make sure you have Python 3.9 installed before proceeding.
13 |
14 | This package is available on PyPI [here](https://pypi.org/project/deeplogit/). You can install it using pip:
15 |
16 | ```bash
17 | pip install deeplogit
18 | ```
19 |
20 | ## Example
21 |
22 | ### 1. Import libraries and load data
23 |
24 | ```python
25 | import pandas as pd
26 | from deeplogit import DeepLogit
27 |
28 | # Load long choice data
29 | input_dir_path = "example_data/"
30 | long_choice_data = pd.read_csv(input_dir_path + "long_choice_data.csv")
31 |
32 | # Define structured attribute names
33 | variables_attributes = ["price", "position"]
34 |
35 | # Define unstructured data file paths
36 | descriptions_csv_path = input_dir_path + "texts/descriptions.csv"
37 | images_dir_path = input_dir_path + "images/"
38 | ```
39 |
40 | ### 2. Initialize and fit the model
41 |
42 | ```python
43 | # Initialize the model
44 | model = DeepLogit()
45 |
46 | # Fit the model
47 | model.fit(
48 | data=long_choice_data,
49 | variables=variables_attributes,
50 | unstructured_data_path=descriptions_csv_path,
51 | select_optimal_PC_RCs=True,
52 | number_of_PCs=3,
53 | n_draws=100,
54 | n_starting_points=100,
55 | print_results=True,
56 | )
57 | ```
58 |
59 | The `fit` method has the following parameters:
60 | - `data` : pandas.DataFrame
61 | The choice data in long format where each observation is a consumer-product pair. Must contain the following columns:
62 | - choice_id: Consumer identifier
63 | - product_id: Product identifier
64 | - choice: The choice indicator (1 for chosen alternative, 0 otherwise).
65 | - price: The price of the product.
66 | - `variables` : list
67 | The list of variable names that vary both across products and consumers. The names must match the column names in the data. Must include the price variable.
68 | - `unstructured_data_path` : str
69 | The path to the unstructured data. If the data is images, this should be the path to the directory containing the images. If the data is text, this should be the path to the CSV file containing the text data.
70 | - `select_optimal_PC_RCs` : bool, optional
71 | True to select the AIC-minimizing combination of principal components via brute force algorithm. False to include all principal components without optimization. Default is True.
72 | - `number_of_PCs` : int, optional
73 | The number of principal components to extract from the unstructured data. Default is 3.
74 | - `n_draws` : int, optional
75 | The number of draws to approximate mixing distributions of the random coefficients. Default is 100.
76 | - `n_starting_points` : int, optional
77 | The number of starting points to use in the estimation. Default is 100.
78 | - `print_results` : bool, optional
79 | Whether to print the results of each model fit. Default is True.
80 |
81 |
82 | ### 3. Access model diagnostics
83 |
84 | ```python
85 | # Print model diagnostics
86 | print(f"Fitted model log-likelihood: {model.loglikelihood}")
87 | print(f"Fitted model AIC: {model.aic}")
88 | print(f"Fitted model estimate names: {model.coeff_names}")
89 | print(f"Fitted model estimate values: {model.coeff_}")
90 | print(f"Fitted model estimate standard errors: {model.stderr}")
91 | ```
92 |
93 | ### 4. Make predictions
94 |
95 | ```python
96 | # Predict market shares (J x N matrix)
97 | predicted_market_shares = model.predict(data=long_choice_data)
98 |
99 | # Predict diversion ratios (J x J matrix)
100 | predicted_diversion_ratios = model.predict_diversion_ratios(data=long_choice_data)
101 | ```
102 |
103 | ### 5. Another fit example
104 |
105 | ```python
106 | # Example: Use images, extract 5 PCs, and include all PCs without optimization
107 | model.fit(
108 | data=long_choice_data,
109 | variables=variables_attributes,
110 | unstructured_data_path=images_dir_path,
111 | select_optimal_PC_RCs=False,
112 | number_of_PCs=5,
113 | n_draws=100,
114 | n_starting_points=100,
115 | print_results=True,
116 | )
117 | ```
118 |
119 | For a full example, including the dataset used in this example, see the `examples/` directory in the repository.
120 |
121 | ## Contributors
122 |
123 | We are deeply grateful to Franklin She for transforming our existing code into a user-friendly, well-documented Python package. We also thank Celina Park, Tanner Parsons, James Ryan, Janani Sekar, Andrew Sharng, Adam Sy, and Vitalii Tubdenov for their exceptional research assistance. The code they developed in the past either inspired this package or was directly used to build it.
124 |
125 | ## Citing DeepLogit
126 |
127 | Our **DeepLogit** package borrows extensively from the code of the existing **Xlogit** package [(see here)](https://github.com/arteagac/xlogit). Therefore, if you use **DeepLogit** in your work, please cite both our package and the original **Xlogit** package as follows:
128 |
129 | Compiani, G., Morozov, I., & Seiler, S. (2023). Demand estimation with text and image data. SSRN Working Paper. [Link to paper](https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4588941)
130 |
131 | Arteaga, C., Park, J., Beeramoole, P. B., & Paz, A. (2022). Xlogit: An open-source Python package for GPU-accelerated estimation of Mixed Logit models. Journal of Choice Modelling, 42, 100339. [Link to paper](https://doi.org/10.1016/j.jocm.2021.100339)
132 |
--------------------------------------------------------------------------------
/deeplogit/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | deeplogit.
3 |
4 | Mixed Logit Estimation with Text and Image Embeddings Extracted Using Deep Learning Models
5 | """
6 |
7 | __version__ = "0.1.0"
8 |
9 | from .deeplogit import *
10 |
--------------------------------------------------------------------------------
/deeplogit/deeplogit.py:
--------------------------------------------------------------------------------
1 | import os
2 | from functools import partial
3 | from glob import glob
4 | from itertools import combinations
5 | from multiprocessing import Pool, cpu_count
6 |
7 | import numpy as np
8 | import pandas as pd
9 | from tensorflow.keras.preprocessing import image
10 | from xlogit import MixedLogit
11 |
12 | from .embeddings import generate_image_embeddings, generate_text_embeddings
13 | from .pca import compute_principal_components
14 |
15 | os.environ["TOKENIZERS_PARALLELISM"] = "false"
16 |
17 |
18 | class DeepLogit:
19 | """Class for estimation of mixed logit models with image or text embeddings.
20 |
21 | Attributes:
22 | model : xlogit.MixedLogit
23 | The fitted mixed logit model.
24 |
25 | best_specification : str
26 | The best specification of the model.
27 |
28 | best_embedding_model : str
29 | The best embedding model used in the model.
30 |
31 | best_varnames : list
32 | The list of variable names used in the model.
33 |
34 | Attributes (inherited from xlogit.MixedLogit):
35 | ceoff_ : numpy.ndarray
36 | Estimated coefficients of the model.
37 |
38 | coeff_names : numpy.ndarray
39 | Names of the estimated coefficients.
40 |
41 | stderr : numpy.ndarray
42 | Standard errors of the estimated coefficients.
43 |
44 | zvalues : numpy.ndarray
45 | Z-values of the estimated coefficients.
46 |
47 | pvalues : numpy.ndarray
48 | P-values of the estimated coefficients.
49 |
50 | loglikelihood : float
51 | Log-likelihood of the model at the end of estimation.
52 |
53 | convergence : bool
54 | Whether the model has converged during estimation.
55 |
56 | total_iter : int
57 | Total number of iterations executed during estimation
58 |
59 | sample_size : int
60 | Number of samples used in estimation.
61 |
62 | aic : float
63 | Akaike Information Criterion of the estimated model.
64 |
65 | bic : float
66 | Bayesian Information Criterion of the estimated model.
67 | """
68 |
69 | def __init__(self):
70 | """Initializes the DeepLogit object."""
71 | self.model = None
72 | self.best_specification = None
73 | self.best_embedding_model = None
74 | self.best_varnames = None
75 |
76 | def fit(
77 | self,
78 | data,
79 | variables,
80 | unstructured_data_path,
81 | select_optimal_PC_RCs=True,
82 | number_of_PCs=3,
83 | n_draws=100,
84 | n_starting_points=100,
85 | print_results=True,
86 | ):
87 | """Fits a mixed logit model with unstructured data embeddings.
88 |
89 | Args:
90 | data : pandas.DataFrame
91 | The choice data in long format where each observation is a consumer-product pair. Must contain the following columns:
92 | - choice_id: Consumer identifier
93 | - product_id: Product identifier
94 | - choice: The choice indicator (1 for chosen alternative, 0 otherwise).
95 | - price: The price of the product.
96 |
97 | variables : list
98 | The list of variable names that vary both across products and consumers. The names must match the column names in the data. Must include the price variable.
99 |
100 | unstructured_data_path : str
101 | The path to the unstructured data. If the data is images, this should be the path to the directory containing the images. If the data is text, this should be the path to the CSV file containing the text data.
102 |
103 | select_optimal_PC_RCs : bool, optional
104 | True to select the AIC-minimizing combination of principal components via brute force algorithm. False to include all principal components without optimization. Default is True.
105 |
106 | number_of_PCs : int, optional
107 | The number of principal components to extract from the unstructured data. Default is 3.
108 |
109 | n_draws : int, optional
110 | The number of draws to approximate mixing distributions of the random coefficients. Default is 100.
111 |
112 | n_starting_points : int, optional
113 | The number of starting points to use in the estimation. Default is 100.
114 |
115 | print_results : bool, optional
116 | Whether to print the results of each model fit. Default is True.
117 |
118 | Returns:
119 | None
120 | """
121 |
122 | # Create dummy variables for product_id column and add to variables
123 | product_dummies = pd.get_dummies(
124 | data["product_id"], prefix="product_id"
125 | ).astype(int)
126 |
127 | data = pd.concat([data, product_dummies], axis=1)
128 |
129 | # Append the names of the first J - 1 product_id_{product_id} columns to the list of strings variables
130 | dummy_columns = [
131 | col for col in product_dummies.columns if col != product_dummies.columns[-1]
132 | ]
133 | variables.extend(dummy_columns)
134 |
135 | # Determine the type of unstructured data
136 | if os.path.isdir(unstructured_data_path):
137 | unstructured_data_type = "images"
138 | elif os.path.isfile(unstructured_data_path) and unstructured_data_path.endswith(
139 | ".csv"
140 | ):
141 | unstructured_data_type = "text"
142 | else:
143 | raise ValueError(
144 | "Unstructured data path must be a directory (for images) or a CSV file (for text)"
145 | )
146 |
147 | # 1. Transform unstructured data into embeddings
148 | if unstructured_data_type == "images":
149 | unstructured_data = self._load_images(unstructured_data_path)
150 | embeddings = generate_image_embeddings(unstructured_data)
151 | elif unstructured_data_type == "text":
152 | unstructured_data = self._load_texts(unstructured_data_path)
153 | embeddings = generate_text_embeddings(unstructured_data)
154 | text_name = list(embeddings.keys())[0]
155 | embeddings = embeddings[list(embeddings.keys())[0]]
156 | embeddings = {f"{text_name}_{k}": v for k, v in embeddings.items()}
157 | else:
158 | raise ValueError("Unstructured data type must be 'images' or 'text'")
159 |
160 | # 2. Perform PCA on embeddings
161 | principal_components_matrices = compute_principal_components(
162 | embeddings,
163 | num_components=number_of_PCs,
164 | )
165 |
166 | # 3. Join principal components with choice data
167 | principal_components = {}
168 |
169 | for (
170 | model_name,
171 | principal_components_matrix,
172 | ) in principal_components_matrices.items():
173 | principal_components_df = pd.DataFrame(principal_components_matrix)
174 | principal_components_df["product_id"] = list(unstructured_data.keys())
175 |
176 | for i, col in enumerate(principal_components_df.columns):
177 | if col == "product_id":
178 | continue
179 | # NOTE: Normalize each principal component for better convergence
180 | pc_normalized = self._standardize(principal_components_df[col])
181 | principal_components[f"{model_name}_pc{i+1}"] = dict(
182 | zip(principal_components_df["product_id"], pc_normalized)
183 | )
184 |
185 | for key, pc_dict in principal_components.items():
186 | data[key] = data["product_id"].map(lambda x: pc_dict.get(str(x)))
187 |
188 | # 4. Fit mixed logit models and select the best one
189 | best_model = None
190 | best_specification = None
191 | best_embedding_model = None
192 | best_varnames = None
193 | best_AIC = np.inf
194 |
195 | for model_name in principal_components_matrices.keys():
196 | varnames = variables + [
197 | f"{model_name}_pc{i}" for i in range(1, number_of_PCs + 1)
198 | ]
199 |
200 | pc_specifications = self._generate_pc_specifications(
201 | number_of_PCs, model_name
202 | )
203 |
204 | if not select_optimal_PC_RCs:
205 | max_randvars = max(
206 | [len(randvars) for randvars in pc_specifications.values()]
207 | )
208 | pc_specifications = {
209 | k: v for k, v in pc_specifications.items() if len(v) == max_randvars
210 | }
211 |
212 | for specification, randvars in pc_specifications.items():
213 | if print_results:
214 | print("-" * 50)
215 | print(f"Trying model: {model_name}, specification: {specification}")
216 | model = self._estimate_mixed_logit(
217 | data=data,
218 | varnames=varnames,
219 | randvars=randvars,
220 | n_draws=n_draws,
221 | num_starting_points=n_starting_points,
222 | )
223 | if print_results:
224 | print(f"LL: {model.loglikelihood}, AIC: {model.aic}")
225 | if model.aic < best_AIC:
226 | best_model = model
227 | best_AIC = model.aic
228 | best_specification = specification
229 | best_embedding_model = model_name
230 | best_varnames = varnames
231 |
232 | # 5. Store the best model
233 | self.model = best_model
234 | self.best_specification = best_specification
235 | self.best_embedding_model = best_embedding_model
236 | self.best_varnames = best_varnames
237 |
238 | def predict(self, data, seed=123):
239 | """Predicts the choice probabilities for the given data using the fitted model.
240 |
241 | Args:
242 | data : pandas.DataFrame
243 | The choice data in long format. Must contain the following columns:
244 | - choice_id: The ID of the choice situation.
245 | - product_id: The ID of the product.
246 |
247 | seed : int, optional
248 | The random seed to use for the prediction. Default is 123.
249 |
250 | Returns:
251 | numpy.ndarray: The predicted choice probabilities.
252 | """
253 | assert self.model is not None, "Model has not been fitted yet."
254 | _, predicted_probs = self.model.predict(
255 | X=data[self.best_varnames],
256 | varnames=self.best_varnames,
257 | ids=data["choice_id"],
258 | alts=data["product_id"],
259 | return_proba=True,
260 | halton=False,
261 | random_state=seed,
262 | )
263 |
264 | return predicted_probs
265 |
266 | def predict_diversion_ratios(self, data, seed=123):
267 | """Predicts the diversion ratios for the given data using the fitted model.
268 |
269 | Args:
270 | data : pandas.DataFrame
271 | The choice data in long format. Must contain the following columns:
272 | - choice_id: The ID of the choice situation.
273 | - product_id: The ID of the product.
274 |
275 | seed : int, optional
276 | The random seed to use for the prediction. Default is 123.
277 |
278 | Returns:
279 | numpy.ndarray: The predicted diversion ratios.
280 | """
281 | assert self.model is not None, "Model has not been fitted yet."
282 | coeff_dict = dict(zip(self.model.coeff_names, self.model.coeff_))
283 |
284 | np.random.seed(seed)
285 | choice_ids = data["choice_id"].unique()
286 | unique_products = data["product_id"].unique()
287 | J = len(unique_products)
288 |
289 | # Prepare an empty count matrix: (J x J).
290 | # predicted_count_matrix[j1, j2] = number of times product j2 is chosen second
291 | # given that product j1 was chosen first.
292 | predicted_count_matrix = np.zeros((J, J), dtype=float)
293 |
294 | # Loop through each choice situation
295 | for i in choice_ids:
296 | utilities = self._simulate_individual(data, coeff_dict, i, seed=seed + i)
297 | sorted_idx = np.argsort(utilities)[::-1]
298 | first_choice_idx = sorted_idx[0]
299 | second_choice_idx = sorted_idx[1]
300 |
301 | # Map these back to actual product IDs
302 | first_choice_product_id = unique_products[first_choice_idx]
303 | second_choice_product_id = unique_products[second_choice_idx]
304 |
305 | # Update predicted_count_matrix
306 | row_index_for_first = np.where(unique_products == first_choice_product_id)[
307 | 0
308 | ][0]
309 | col_index_for_second = np.where(
310 | unique_products == second_choice_product_id
311 | )[0][0]
312 | predicted_count_matrix[row_index_for_first, col_index_for_second] += 1
313 |
314 | # Compute predicted diversion matrix
315 | col_sums = predicted_count_matrix.sum(axis=1, keepdims=True)
316 | with np.errstate(divide="ignore", invalid="ignore"):
317 | predicted_diversion_matrix = np.where(
318 | col_sums != 0, predicted_count_matrix / col_sums, 0
319 | )
320 |
321 | assert np.allclose(predicted_diversion_matrix.sum(axis=1), 1)
322 |
323 | return predicted_diversion_matrix
324 |
325 | def __getattr__(self, name):
326 | """Override the __getattr__ method to allow access to the attributes of the xlogit.MixedLogit object."""
327 | if name.startswith("__") and name.endswith("__"):
328 | raise AttributeError(
329 | f"'{self.__class__.__name__}' object has no attribute '{name}'"
330 | )
331 |
332 | if name in self.__dict__:
333 | return self.__dict__[name]
334 |
335 | if self.model is not None:
336 | if hasattr(self.model.__class__, name) or name in self.model.__dict__:
337 | return getattr(self.model, name)
338 |
339 | raise AttributeError(
340 | f"'{self.__class__.__name__}' object has no attribute '{name}'"
341 | )
342 |
343 | def _load_images(self, dir_path):
344 | images = {}
345 | image_paths = glob(os.path.join(dir_path, "*.jpg"))
346 | target_size = (224, 224)
347 |
348 | for path in image_paths:
349 | path = path.replace("\\", "/")
350 | asin = os.path.splitext(os.path.basename(path))[0]
351 | try:
352 | img = image.load_img(path, target_size=target_size)
353 | img_array = image.img_to_array(img)
354 | img_array = np.expand_dims(img_array, axis=0)
355 | images[asin] = img_array
356 | except Exception as e:
357 | print(f"Error loading image {path}: {e}")
358 |
359 | images = dict(sorted(images.items()))
360 |
361 | return images
362 |
363 | def _load_texts(self, file_path):
364 | texts = {}
365 |
366 | # Load the CSV file
367 | texts_df = pd.read_csv(file_path)
368 |
369 | # Ensure the first column is 'id'
370 | columns = texts_df.columns
371 | assert len(columns) >= 2, f"Expected at least 2 columns, got {len(columns)}"
372 | assert columns[0] == "id", f"Expected first column to be 'id', got {columns[0]}"
373 |
374 | text_columns = columns[1:] # Exclude the 'id' column
375 |
376 | for _, row in texts_df.iterrows():
377 | id = str(row["id"])
378 | text_dict = {col: str(row[col]) for col in text_columns}
379 | texts[id] = text_dict
380 |
381 | return texts
382 |
383 | def _standardize(self, series):
384 | """Standardizes a pandas Series."""
385 | return (series - series.mean()) / series.std()
386 |
387 | def _simulate_individual(
388 | self,
389 | first_choice_data,
390 | coeff_dict,
391 | i,
392 | seed=1,
393 | include_gumbels=True,
394 | ):
395 | """Simulates the utilities for an individual given the first choice data and coefficients."""
396 | unique_products = first_choice_data["product_id"].unique()
397 | J = len(unique_products)
398 |
399 | np.random.seed(seed)
400 | # Extract the subset of rows corresponding to this individual's choice situation
401 | df_i = first_choice_data.loc[first_choice_data["choice_id"] == i]
402 |
403 | # Draw individual-specific random coefficients (if any)
404 | individual_coeffs = {}
405 | for param in coeff_dict.keys():
406 | # Skip the 'sd_' parameters themselves; these are used for the standard deviation
407 | # of the random parameters
408 | if param.startswith("sd."):
409 | param_mean = param[3:]
410 | mean_ = coeff_dict[param_mean]
411 | sd_ = np.abs(coeff_dict[param])
412 | individual_coeffs[param_mean] = np.random.normal(mean_, sd_)
413 | else:
414 | # Otherwise, it's a fixed parameter
415 | individual_coeffs[param] = coeff_dict[param]
416 |
417 | # Compute utilities for each product
418 | # Add Gumbel random error for each product as well
419 | utilities = []
420 | if include_gumbels:
421 | epsilons = np.random.gumbel(loc=0, scale=1, size=J)
422 | else:
423 | epsilons = np.zeros(J)
424 |
425 | # Sort df_i by product_id to ensure consistent ordering
426 | df_i = df_i.sort_values(by="product_id")
427 | df_i_indexed = df_i.set_index("product_id")
428 |
429 | # For each product in unique_products (which are sorted), compute the utility
430 | for j, j_id in enumerate(unique_products):
431 | row_ij = df_i_indexed.loc[j_id]
432 |
433 | util_ij = 0.0
434 | # Sum up the utility from each variable in varnames
435 | for v in individual_coeffs.keys():
436 | if v.startswith("sd."):
437 | continue
438 | if v in df_i.columns:
439 | util_ij += individual_coeffs[v] * row_ij[v]
440 | else:
441 | raise ValueError(f"Variable {v} not found in df_i.columns")
442 |
443 | # Add the random Gumbel error
444 | util_ij += epsilons[j]
445 |
446 | utilities.append(util_ij)
447 |
448 | utilities = np.array(utilities)
449 |
450 | return utilities
451 |
452 | def _generate_pc_specifications(self, K, embedding_model):
453 | """Generates the pc_specifications dictionary based on the number of principal components (K)."""
454 | base_attributes = ["price"] + [
455 | f"{embedding_model}_pc{i}" for i in range(1, K + 1)
456 | ]
457 |
458 | pc_specifications = {}
459 | pc_specifications["plain logit"] = {}
460 |
461 | # Generate all combinations
462 | for r in range(1, len(base_attributes) + 1):
463 | for combo in combinations(base_attributes, r):
464 | combo_name = []
465 | for attr in combo:
466 | if attr == "price":
467 | combo_name.append("price")
468 | else:
469 | combo_name.append(
470 | attr.split("_")[-1].upper()
471 | ) # Extract PC1, PC2, etc.
472 | combo_name = ", ".join(combo_name)
473 |
474 | combo_dict = {attr: "n" for attr in combo}
475 | pc_specifications[combo_name] = combo_dict
476 |
477 | return pc_specifications
478 |
479 | def _estimate_mixed_logit(
480 | self,
481 | data,
482 | varnames,
483 | randvars,
484 | n_draws=100,
485 | num_starting_points=100,
486 | seed=1,
487 | halton=False,
488 | ):
489 | """Estimates a mixed logit model with given data and specifications using the xlogit library."""
490 |
491 | fit_func = partial(
492 | self._fit_single_model,
493 | data=data,
494 | varnames=varnames,
495 | randvars=randvars,
496 | n_draws=n_draws,
497 | halton=halton,
498 | )
499 |
500 | n_cores = max(1, cpu_count() - 1)
501 |
502 | with Pool(n_cores) as pool:
503 | results = pool.map(
504 | fit_func,
505 | range(
506 | 1 + num_starting_points * seed,
507 | num_starting_points + 1 + num_starting_points * seed,
508 | ),
509 | )
510 |
511 | # Filter out failed fits and find best model
512 | valid_results = [(model, ll) for model, ll in results if model is not None]
513 |
514 | if not valid_results:
515 | raise RuntimeError(
516 | "All model fits failed. Please check your data and parameters."
517 | )
518 |
519 | # Get model with highest log-likelihood
520 | best_model, _ = max(valid_results, key=lambda x: x[1])
521 |
522 | return best_model
523 |
524 | def _fit_single_model(
525 | self, random_state, data, varnames, randvars, n_draws, halton=False
526 | ):
527 | """Helper function to fit a single model with given random state"""
528 | try:
529 | model = MixedLogit()
530 | model.fit(
531 | X=data[varnames],
532 | y=data["choice"],
533 | varnames=varnames,
534 | ids=data["choice_id"],
535 | alts=data["product_id"],
536 | n_draws=n_draws,
537 | random_state=random_state,
538 | randvars=randvars,
539 | halton=halton,
540 | verbose=0,
541 | )
542 | return model, model.loglikelihood
543 | except Exception as e:
544 | print(f"Warning: Fitting failed for random_state {random_state}: {str(e)}")
545 | return None, -np.inf
546 |
--------------------------------------------------------------------------------
/deeplogit/embeddings.py:
--------------------------------------------------------------------------------
1 | import os
2 | import random
3 |
4 | import nltk
5 | import numpy as np
6 | import pandas as pd
7 | import regex as re
8 | import tensorflow as tf
9 | import tensorflow_hub as hub
10 | from nltk.corpus import stopwords, wordnet
11 | from nltk.stem import WordNetLemmatizer
12 | from nltk.tokenize import word_tokenize
13 | from sentence_transformers import SentenceTransformer
14 | from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
15 | from tensorflow.keras.applications import inception_v3, resnet50, vgg16, vgg19, xception
16 |
17 | # -------------------- Image Embeddings --------------------
18 |
19 | np.random.seed(42)
20 | tf.random.set_seed(42)
21 | random.seed(42)
22 |
23 |
24 | def initialize_image_models():
25 | """
26 | Initialize pre-trained CNN models from Keras Applications.
27 |
28 | Returns
29 | -------
30 | models : dict
31 | Dictionary with model names as keys and model instances as values.
32 | """
33 | models = {}
34 | model_configs = [
35 | ("VGG16", vgg16.VGG16),
36 | ("VGG19", vgg19.VGG19),
37 | ("ResNet50", resnet50.ResNet50),
38 | ("Xception", xception.Xception),
39 | ("InceptionV3", inception_v3.InceptionV3),
40 | ]
41 |
42 | for name, model_class in model_configs:
43 | model = model_class(weights="imagenet", include_top=False, pooling="avg")
44 | model.trainable = False
45 | models[name] = model
46 |
47 | return models
48 |
49 |
50 | def get_preprocessing_function(model_name):
51 | """
52 | Retrieve the appropriate preprocessing function for a given image model.
53 |
54 | Parameters
55 | ----------
56 | model_name : str
57 | Name of the image model.
58 |
59 | Returns
60 | -------
61 | function
62 | Corresponding preprocessing function.
63 | """
64 | preprocessing_functions = {
65 | "VGG16": vgg16.preprocess_input,
66 | "VGG19": vgg19.preprocess_input,
67 | "ResNet50": resnet50.preprocess_input,
68 | "Xception": xception.preprocess_input,
69 | "InceptionV3": inception_v3.preprocess_input,
70 | }
71 |
72 | if model_name not in preprocessing_functions:
73 | raise ValueError(f"Unknown model name: {model_name}")
74 |
75 | return preprocessing_functions[model_name]
76 |
77 |
78 | def extract_image_features(images, model, preprocess_input_fn, batch_size=64):
79 | """
80 | Extract features from all images using a pre-trained model in batches.
81 |
82 | Parameters
83 | ----------
84 | images : dict
85 | Dictionary with ASINs as keys and image arrays as values.
86 | model : keras.Model
87 | Pre-trained CNN model for feature extraction.
88 | preprocess_input_fn : function
89 | Preprocessing function for the model.
90 | batch_size : int
91 | Number of images to process in each batch.
92 |
93 | Returns
94 | -------
95 | numpy.ndarray
96 | Array of extracted features (N, D).
97 | """
98 | image_ids = list(images.keys())
99 | num_images = len(image_ids)
100 | features = []
101 |
102 | for i in range(0, num_images, batch_size):
103 | batch_ids = image_ids[i : i + batch_size]
104 | batch_images = np.vstack([images[asin] for asin in batch_ids])
105 | batch_images_preprocessed = preprocess_input_fn(batch_images.copy())
106 | batch_features = model.predict(batch_images_preprocessed)
107 | features.append(batch_features)
108 |
109 | return np.vstack(features)
110 |
111 |
112 | # -------------------- Text Embeddings --------------------
113 |
114 |
115 | def initialize_nltk():
116 | """
117 | Initialize NLTK data and global variables needed for text preprocessing.
118 | """
119 | required_nltk_data = [
120 | "punkt",
121 | "averaged_perceptron_tagger",
122 | "wordnet",
123 | "stopwords",
124 | "punkt_tab",
125 | "averaged_perceptron_tagger_eng",
126 | ]
127 | for item in required_nltk_data:
128 | nltk.download(item)
129 |
130 | global stop_words, wl
131 | stop_words = set(stopwords.words("english"))
132 | wl = WordNetLemmatizer()
133 |
134 |
135 | def get_wordnet_pos(pos_tag):
136 | """
137 | Map NLTK POS tag to WordNet POS tag for lemmatization.
138 |
139 | Parameters
140 | ----------
141 | pos_tag : str
142 | POS tag from NLTK's pos_tag.
143 |
144 | Returns
145 | -------
146 | str
147 | Corresponding WordNet POS tag.
148 | """
149 | tag_map = {"J": wordnet.ADJ, "V": wordnet.VERB, "N": wordnet.NOUN, "R": wordnet.ADV}
150 | return tag_map.get(pos_tag[0], wordnet.NOUN)
151 |
152 |
153 | def preprocess_text(text):
154 | """
155 | Preprocess a single text string.
156 |
157 | Parameters
158 | ----------
159 | text : str
160 | The text to preprocess.
161 |
162 | Returns
163 | -------
164 | str
165 | The preprocessed text.
166 | """
167 | text = text.lower()
168 | text = re.sub(r"[^\w\s]", " ", text)
169 | text = re.sub(r"\d+", " ", text)
170 | tokens = word_tokenize(text)
171 | tokens = [word for word in tokens if word not in stop_words]
172 | pos_tags = nltk.pos_tag(tokens)
173 | lemmatized_tokens = [
174 | wl.lemmatize(word, get_wordnet_pos(pos)) for word, pos in pos_tags
175 | ]
176 | return " ".join(lemmatized_tokens)
177 |
178 |
179 | def preprocess_texts(texts):
180 | """
181 | Preprocess a list of texts.
182 | """
183 | return [preprocess_text(text) for text in texts]
184 |
185 |
186 | def initialize_models():
187 | """
188 | Initialize text embedding models.
189 |
190 | Returns
191 | -------
192 | dict
193 | Dictionary with model names as keys and models as values.
194 | """
195 | models = {
196 | "COUNT": CountVectorizer(stop_words="english", ngram_range=(1, 2)),
197 | "TFIDF": TfidfVectorizer(stop_words="english", ngram_range=(1, 2)),
198 | }
199 |
200 | models["USE"] = hub.load("https://tfhub.dev/google/universal-sentence-encoder/4")
201 |
202 | models["ST"] = SentenceTransformer("all-MiniLM-L6-v2")
203 |
204 | return models
205 |
206 |
207 | def extract_text_features(texts, model_name, model):
208 | """
209 | Extract features from texts using the specified embedding model.
210 |
211 | Parameters
212 | ----------
213 | texts : list
214 | List of preprocessed texts.
215 | model_name : str
216 | Name of the embedding model.
217 | model : object
218 | The embedding model instance.
219 |
220 | Returns
221 | -------
222 | numpy.ndarray
223 | Array of extracted features.
224 | """
225 | if model_name in ["COUNT", "TFIDF"]:
226 | return model.transform(texts).toarray()
227 | elif model_name == "USE":
228 | return embed_texts_use(texts, model)
229 | elif model_name == "ST":
230 | return model.encode(texts, batch_size=32, show_progress_bar=True)
231 | else:
232 | raise ValueError(f"Unknown model name: {model_name}")
233 |
234 |
235 | def embed_texts_use(texts, model_use, batch_size=64):
236 | """
237 | Embed texts using the Universal Sentence Encoder (USE).
238 |
239 | Parameters
240 | ----------
241 | texts : list
242 | List of preprocessed texts.
243 | model_use : tensorflow_hub.Module
244 | The USE model.
245 | batch_size : int
246 | Number of texts to process in each batch.
247 |
248 | Returns
249 | -------
250 | numpy.ndarray
251 | Array of embeddings.
252 | """
253 | embeddings = []
254 | for i in range(0, len(texts), batch_size):
255 | batch_texts = texts[i : i + batch_size]
256 | batch_embeddings = model_use(batch_texts)
257 | embeddings.append(batch_embeddings.numpy())
258 | return np.vstack(embeddings)
259 |
260 |
261 | # -------------------- Main Functions --------------------
262 |
263 |
264 | def generate_image_embeddings(images, save_to_csv=False, dir_path=None):
265 | """Generates image embeddings for each model and saves them to disk.
266 |
267 | Parameters
268 | ----------
269 | images : dict
270 | Dictionary with ASINs as keys and preprocessed image arrays as values.
271 | file_path : str
272 | Path to save the embeddings.
273 | """
274 |
275 | models = initialize_image_models()
276 |
277 | # Extract features using each model
278 | features_dict = {}
279 | for model_name, model in models.items():
280 | preprocess_input_fn = get_preprocessing_function(model_name)
281 | features = extract_image_features(images, model, preprocess_input_fn)
282 | features_dict[model_name] = features
283 |
284 | # Save the embeddings to disk
285 | if save_to_csv and dir_path:
286 | os.makedirs(os.path.dirname(dir_path), exist_ok=True)
287 | for model_name, features in features_dict.items():
288 | npy_file = os.path.join(dir_path, f"{model_name.lower()}_features.npy")
289 | np.save(npy_file, features)
290 |
291 | output_file = os.path.join(dir_path, f"{model_name.lower()}_features.csv")
292 | features_df = pd.DataFrame(features)
293 | features_df.insert(0, "asin", images.keys())
294 | features_df.to_csv(output_file, index=False, float_format="%.18e")
295 |
296 | print(f"Saved image embeddings to {dir_path}.")
297 |
298 | return features_dict
299 |
300 |
301 | def generate_text_embeddings(texts, save_to_csv=False, dir_path=None):
302 | """Generates text embeddings for each model and saves them to disk.
303 |
304 | Parameters
305 | ----------
306 | texts : dict
307 | Dictionary with ASINs as keys and text data as a dictionary as values.
308 | file_path : str
309 | Path to save the embeddings.
310 | """
311 |
312 | initialize_nltk()
313 |
314 | # Get text sources from secondary key of texts
315 | text_sources = set(key for asin_dict in texts.values() for key in asin_dict.keys())
316 | review_keys = sorted(key for key in text_sources if key.startswith("user_review_"))
317 |
318 | # Preprocess texts for each source
319 | texts_per_source = {}
320 | for source in text_sources:
321 | text = [texts[asin].get(source, "") for asin in texts.keys()]
322 | texts_per_source[source] = preprocess_texts(text)
323 |
324 | # Combine texts for vectorizer fitting
325 | all_preprocessed_texts = []
326 | for text in texts_per_source.values():
327 | all_preprocessed_texts.extend(text)
328 |
329 | # Initialize models
330 | embedding_models = initialize_models()
331 |
332 | # Fit COUNT and TFIDF vectorizers
333 | for model_name in ["COUNT", "TFIDF"]:
334 | try:
335 | embedding_models[model_name].fit(all_preprocessed_texts)
336 | except Exception as e:
337 | print(texts)
338 | print(f"Error fitting {model_name}: {e}")
339 | print(f"Directory: {dir_path}")
340 |
341 | # Extract features for each text source and model
342 | features = {}
343 | for source in text_sources:
344 | features[source] = {}
345 | for model_name, model in embedding_models.items():
346 | features[source][model_name] = extract_text_features(
347 | texts_per_source[source], model_name, model
348 | )
349 |
350 | if review_keys:
351 | # Average user review embeddings
352 | features["user_reviews"] = {}
353 | for model_name in embedding_models:
354 | review_embeddings = [
355 | features[review_key][model_name] for review_key in review_keys
356 | ]
357 | features["user_reviews"][model_name] = np.mean(
358 | np.stack(review_embeddings), axis=0
359 | )
360 |
361 | # Remove individual review features
362 | for review_key in review_keys:
363 | features.pop(review_key)
364 |
365 | # Save the embeddings to disk
366 | if save_to_csv and dir_path:
367 | os.makedirs(os.path.dirname(dir_path), exist_ok=True)
368 | for source, features_dict in features.items():
369 | for model_name, features in features_dict.items():
370 | output_file = os.path.join(
371 | dir_path, f"{source}_{model_name}_features.npy"
372 | )
373 | np.save(output_file, features)
374 |
375 | output_file = os.path.join(
376 | dir_path, f"{source}_{model_name}_features.csv"
377 | )
378 | features_df = pd.DataFrame(features)
379 | features_df.insert(0, "asin", texts.keys())
380 | features_df.to_csv(output_file, index=False, float_format="%.18e")
381 |
382 | print(f"Saved text embeddings to {dir_path}.")
383 |
384 | return features
385 |
--------------------------------------------------------------------------------
/deeplogit/pca.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import pandas as pd
4 | from sklearn.decomposition import PCA
5 | from sklearn.preprocessing import StandardScaler
6 |
7 |
8 | def compute_principal_components(
9 | embeddings,
10 | num_components=3,
11 | principal_components_path=None,
12 | save_to_csv=True,
13 | ):
14 | """Compute principal components for multiple embedding matrices and combined embeddings.
15 |
16 | Args:
17 | embeddings (dict): Dictionary of (J, num_features) matrices where the key is the model.
18 | combined_embeddings (np.ndarray): The combined feature matrix of shape (J, total_num_features).
19 | principal_components_path (str): The path to save the principal components.
20 | num_components (int, optional): Number of principal components to compute. Defaults to 10.
21 |
22 | Returns:
23 | dict: Dictionary of principal component matrices for each model and combined embeddings.
24 | """
25 | # Initialize dictionary to store all principal components
26 | all_principal_components = {}
27 |
28 | # Compute PCA for each model's embeddings
29 | for model_name, embedding_matrix in embeddings.items():
30 | non_zero_cols = (embedding_matrix != 0).sum(axis=0) > 0
31 | embedding_matrix = embedding_matrix[:, non_zero_cols]
32 | if embedding_matrix.shape[1] == 0:
33 | # Skip this model if all columns are zero
34 | print(f"Skipping {model_name} because all columns are zero.")
35 | continue
36 |
37 | # 2. Standardize (center and scale to unit variance)
38 | scaler = StandardScaler()
39 | embedding_matrix_scaled = scaler.fit_transform(embedding_matrix)
40 |
41 | # Initialize and fit PCA
42 | pca = PCA(n_components=num_components, svd_solver="full")
43 | principal_components = pca.fit_transform(embedding_matrix_scaled)
44 |
45 | # Store the principal components
46 | all_principal_components[model_name] = principal_components
47 |
48 | # Save to CSV
49 | if save_to_csv and principal_components_path:
50 | os.makedirs(principal_components_path, exist_ok=True)
51 | principal_components_df = pd.DataFrame(principal_components)
52 | output_path = os.path.join(
53 | principal_components_path, f"{model_name}_principal_components.csv"
54 | )
55 | principal_components_df.to_csv(output_path, index=False)
56 |
57 | return all_principal_components
58 |
--------------------------------------------------------------------------------
/examples/example.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 |
3 | from deeplogit import DeepLogit
4 |
5 |
6 | def main():
7 | input_dir_path = "example_data/"
8 |
9 | # Load data
10 | long_choice_data = pd.read_csv(input_dir_path + "long_choice_data.csv")
11 | variables_attributes = [
12 | "price",
13 | "position",
14 | ]
15 |
16 | images_dir_path = input_dir_path + "images/"
17 | titles_csv_path = input_dir_path + "texts/titles.csv"
18 | descriptions_csv_path = input_dir_path + "texts/descriptions.csv"
19 | reviews_csv_path = input_dir_path + "texts/reviews.csv"
20 |
21 | unstructured_data_list = [
22 | ("reviews", reviews_csv_path),
23 | ("titles", titles_csv_path),
24 | ("descriptions", descriptions_csv_path),
25 | ("images", images_dir_path),
26 | ]
27 |
28 | results = {}
29 |
30 | for (
31 | unstructured_data_name,
32 | unstructured_data_path,
33 | ) in unstructured_data_list:
34 | print(f"Running model with {unstructured_data_name} as unstructured data")
35 | results[unstructured_data_name] = {}
36 |
37 | model = DeepLogit()
38 |
39 | # Fit the model
40 | model.fit(
41 | data=long_choice_data,
42 | variables=variables_attributes,
43 | unstructured_data_path=unstructured_data_path,
44 | select_optimal_PC_RCs=True,
45 | number_of_PCs=3,
46 | n_draws=100,
47 | n_starting_points=100,
48 | print_results=True,
49 | )
50 |
51 | # Predict market shares and diversion ratios
52 | predicted_market_shares = model.predict(data=long_choice_data)
53 | predicted_diversion_ratios = model.predict_diversion_ratios(
54 | data=long_choice_data
55 | )
56 |
57 | # Save selected embedding model and specification
58 | results[unstructured_data_name][
59 | "selected_embedding_model"
60 | ] = model.best_embedding_model
61 | results[unstructured_data_name][
62 | "selected_specification"
63 | ] = model.best_specification
64 |
65 | # Save model fit statistics
66 | results[unstructured_data_name]["log_likelihood"] = model.loglikelihood
67 | results[unstructured_data_name]["aic"] = model.aic
68 |
69 | # Save estimated parameters and standard errors
70 | results[unstructured_data_name]["coefficient_names"] = model.coeff_names
71 | results[unstructured_data_name]["estimated_coefficients"] = model.coeff_
72 | results[unstructured_data_name]["standard_errors"] = model.stderr
73 |
74 | # Save predicted market shares and diversion ratios
75 | results[unstructured_data_name][
76 | "predicted_market_shares"
77 | ] = predicted_market_shares
78 | results[unstructured_data_name][
79 | "predicted_diversion_ratios"
80 | ] = predicted_diversion_ratios
81 |
82 | print("\n\nResults:")
83 | print("==" * 40)
84 |
85 | for unstructured_data_name, result in results.items():
86 | print(f"\nResults for {unstructured_data_name} as unstructured data")
87 | print("Selected embedding model:", result["selected_embedding_model"])
88 | print("Selected specification:", result["selected_specification"])
89 | print("Log-likelihood:", result["log_likelihood"])
90 | print("AIC:", result["aic"])
91 | print("Coefficient names:")
92 | print(result["coefficient_names"])
93 | print("Estimated coefficients:")
94 | print(result["estimated_coefficients"])
95 | print("Standard errors:")
96 | print(result["standard_errors"])
97 | print("\n")
98 |
99 | print("==" * 40)
100 |
101 | for unstructured_data_name, result in results.items():
102 | print(f"\nResults for {unstructured_data_name} as unstructured data")
103 | # print("Predicted market shares:")
104 | # print(result["predicted_market_shares"])
105 | print("Predicted diversion ratios:")
106 | print(result["predicted_diversion_ratios"])
107 | print("\n")
108 |
109 | print("==" * 40)
110 |
111 |
112 | if __name__ == "__main__":
113 | main()
114 |
--------------------------------------------------------------------------------
/examples/example_data/images/21.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/21.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/23.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/23.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/29.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/29.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/3.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/3.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/4.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/4.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/45.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/45.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/46.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/46.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/47.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/47.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/8.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/8.jpg
--------------------------------------------------------------------------------
/examples/example_data/images/9.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/deep-logit-demand/deeplogit/6e0e338039b82903c1371ac983a5697ab5489dae/examples/example_data/images/9.jpg
--------------------------------------------------------------------------------
/examples/example_data/texts/books.csv:
--------------------------------------------------------------------------------
1 | id,url,asin,title,author,genre,price,number_of_pages,publication_year,description,user_review_1,user_star_rating_1,user_review_2,user_star_rating_2,user_review_3,user_star_rating_3,user_review_4,user_star_rating_4,user_review_5,user_star_rating_5
2 | 3,https://www.amazon.com/Please-Tell-Me-Mike-Omer-ebook/dp/B0BWNW9G8X/ref=zg_bs_g_157305011_sccl_5/132-6615511-8040164?psc=1,B0BWNW9G8X,Please Tell Me,Mike Omer,"Mystery, Thriller & Suspense",4.99,377.0,2023.0,"After a year in captivity, a kidnapped child escapes—only to reveal horrific truths that lead her psychologist on a race against time in this thriller from New York Times bestselling author Mike Omer.
3 |
4 | When eight-year-old Kathy Stone turns up on the side of the road a year after her abduction, the world awaits her harrowing story. But Kathy doesn't say a word. Traumatized by her ordeal, she doesn't speak at all, not even to her own parents.
5 |
6 | Child therapist Robin Hart is the only one who's had success connecting with the girl. Robin has been using play therapy to help Kathy process her memories. But as their work continues, Kathy's playtime takes a grim turn: a doll stabs another doll, a tiny figurine is chained to a plastic toy couch. All of these horrifying moments, enacted within a Victorian doll house. Every session, another toy dies.
7 |
8 | But the most disturbing detail? Kathy seems to be playacting real unsolved murders.
9 |
10 | Soon Robin wonders if Kathy not only holds the key to the murders of the past but if she knows something about the murders of the future. Can Robin unlock the secrets in Kathy's brain and stop a serial killer before he strikes again? Or is Robin's work with Kathy putting her in the killer's sights?","""This was almost an Amazon First Read's pick for me but I grabbed a different one instead. I couldn't stop thinking about the sample I'd read from it though and ended up buying it anyway and waiting for the December release. Today I remembered I had access to it and started reading and didn't put it down except for two dog potty breaks and a puppy bath. I just finished reading it this afternoon and was so satisfied with the entire book. It kept me on the edge of my seat and had the perfect mix of tension and relief. Thoroughly enjoyed this thriller and would recommend it to anyone who enjoys true crime reads or thriller novels and is looking for another new book to read."" --Meghan Miller (Amazon Reader)",5.0,"""I don't leave reviews very often, but just finished this book last night. I've read other books by Mr Omer and enjoyed them, but this one - this one is in a class all its own. It starts out pretty laid back but builds as pages turn. I actually had to stay up to the wee hours of the morning to finish it and find out the who what where and why of the abduction. A great read, perhaps because it didn't follow the standard tropes of its genre and consequently surprises the reader as they get drawn in ever deeper to the characters and the story itself.
11 |
12 | Way to go Mr. Omer! You managed to totally wreck my sleep patterns - something most books don't accomplish. LMAO"" --Karen DeCrane (Amazon Reader)",5.0,"""It took me a while at the beginning to piece the non-linear chapters together but once I did, I found this book to be extremely thought-provoking, realistic and trying to figure out who the bad guy was. When I got close to the end, and the romance was beginning I thought oh it's just another case solved now two people fall in love and live happily ever after but it turns out there was a twist to the plot, which Turned out to be another story in itself, and even though they still fell in love at the end, it was one page and wasn't cheesy"" --D. Burton (Amazon Reader)",5.0,"""Eight-year-old Kathy Stone disappeared from her own yard one day. A year later, she was found on the side of the road. Many suspected that she had died, but everyone wants to know where she has been. Kathy is so traumatized that she no longer speaks. It is up to her therapist, Robin Hart, who, through play therapy, rushes to learn what had happened to poor Kathy, before she is recaptured by her kidnapper. Little by little, Kathy reveals the truth through dolls and toys. Robin is horrified by Kathy's story.
13 |
14 | Mike Omer's realistic and well-developed characters take the reader on a journey to discover the truth. This is an intriguing story filled with unexpected twists and turns."" --Sandra (Amazon Reader)",4.0,"""I realized liked the storyline for the book, it was so good and well written, it literally kept me wanting more, but unfortunately I felt that it began slow, then sped up, and slowed again and the worst part about it was how confusing it was trying to see what character I was reading in the chapter, it would've been nice author wrote “robin” “Kathy” to give some hint, I think that is what bothered me most, over all I loved the book it, a lot of thrill, mystery, and mind games a couple times I knew who the abductor was then I was proven wrong in the end. I'd recommend this book but with notice about the confusion between the back and forth chapters."" --M. Zambrano (Amazon Reader)",3.0
15 | 4,https://www.amazon.com/Housemaid-absolutely-addictive-psychological-jaw-dropping-ebook/dp/B09TWSRMCB/ref=zg_bs_g_157305011_sccl_6/132-6615511-8040164?psc=1,B09TWSRMCB,The Housemaid,Freida McFadden,"Mystery, Thriller & Suspense",3.99,353.0,2022.0,"“Welcome to the family,” Nina Winchester says as I shake her elegant, manicured hand. I smile politely, gazing around the marble hallway. Working here is my last chance to start fresh. I can pretend to be whoever I like. But I'll soon learn that the Winchesters' secrets are far more dangerous than my own…
16 |
17 | Every day I clean the Winchesters' beautiful house top to bottom. I collect their daughter from school. And I cook a delicious meal for the whole family before heading up to eat alone in my tiny room on the top floor.
18 |
19 | I try to ignore how Nina makes a mess just to watch me clean it up. How she tells strange lies about her own daughter. And how her husband Andrew seems more broken every day. But as I look into Andrew's handsome brown eyes, so full of pain, it's hard not to imagine what it would be like to live Nina's life. The walk-in closet, the fancy car, the perfect husband.
20 |
21 | I only try on one of Nina's pristine white dresses once. Just to see what it's like. But she soon finds out… and by the time I realize my attic bedroom door only locks from the outside, it's far too late.
22 |
23 | But I reassure myself: the Winchesters don't know who I really am.
24 |
25 | They don't know what I'm capable of…","""This book was so much fun to read. I picked it from the list for one of the Kindle challenges and was not disappointed. On the way home from errands one day I wondered what would be next for Millie and Nina. After all, Millie's an ex con and Nina's an ex psych ward patient, so how much trouble could they get into just hanging around the house while Nina's husband Andrew is working. Lots! That's how much.
26 |
27 | Right up until the last few pages I was still being surprised. I will miss these characters.
28 |
29 | And to steal a line from the ABC hit show NYPD Blue, a detective in Internal Affairs told Detective Bobby Simone that everything is a situation. In this book that's an understatement."" --J. Weston (Amazon Reader)",5.0,"""At first, I wasn't sure where the story was going - but as I kept reading, I became more and more intrigued. I couldn't put the book down! It went in a completely different direction than what I predicted. Whatever you THINK you know, you don't. I was literally gasping reading it (I was actually quite expressive while reading the entire book lol). This was such a great read. I'm excited to read the rest of the series! You won't be disappointed at all with this one!! Get your copy now!"" --Lenisha (Amazon Reader)",5.0,"""A down and out young woman gets a dream job with a wealthy family. She is greeted warmly and is quite impressed by the couple and the little daughter. But things aren't as they appear to be. A wife with mental issues, a handsome caring husband, and a bratty child. Hired as a housekeeper and nanny, Millie does her best to handle all the disturbing issues.
30 | I read the book in one day and the twists and turns kept me intrigued…right up to the surprising ending."" --babs (Amazon Reader)",5.0,"""First novel by Freida McFadden. When I downloaded this book on Kindle Unlimited I didn't realize it was a series. It's a book that doesn't require much thinking and I was hooked from the beginning. I found part 1 and part 2 to be quite predictable but part 3 was a shocker. The twists in this story were good except at the very end then the plot kind of collapses.
31 |
32 | It's definitely a popcorn read. It was entertaining, a bit predictable, some light suspense, and an all around easy read with a couple silly parts. I would recommend."" --Mary (Amazon Reader)",4.0,"""I'm honestly between a 2.5 and a 3 star rating for this book. I thought the story-building was okay but I tended to get annoyed with the main character often. I also was not surprised by any of the “plot twists”, I felt like everything was pretty predictable."" --Mariela M. (Amazon Reader)",3.0
33 | 8,https://www.amazon.com/Ritual-Dark-College-Romance-ebook/dp/B09H7Q4B74/ref=zg_bs_g_157305011_sccl_10/132-6615511-8040164?psc=1,B09H7Q4B74,The Ritual,Shantel Tessier,"Mystery, Thriller & Suspense",4.99,606.0,2021.0,"THE CHOSEN ONE
34 |
35 | Barrington University is home of the Lords, a secret society that requires their blood in payment. They are above all—the most powerful men in the world. They devote their lives to violence in exchange for power. And during their senior year, they are offered a chosen one.
36 |
37 | I VOW. YOU VOW. WE VOW.
38 |
39 | People think growing up with money is freeing, but I promise you, it's not. My entire life has been planned out for me. I never got the chance to do what I wanted until Ryat Alexander Archer came along and gave me an option for a better life. He offered me what no one else ever had—freedom.
40 |
41 | I chose to be his. He made me believe that anyway, but it was just another lie. A way that the Lords manipulate you into doing what they want.
42 |
43 | After being sucked into the dark, twisted world of the Lords, I embraced my new role and allowed Ryat to parade me around like the trophy I was to him. But like all things, what started out as a game soon became a fight for survival. And the only way out was death.","""I absolutely loved learning about the Lords, Ryat and Blakely. Yes the steam and sex was great, and right on par for anyone who loves darker kinks, but the drama and the story was so intriguing. For some readers, I can understand it might be triggering. But as someone who has dealt with some of the triggers in the book, it was empowering reading about a female character choosing and understanding the power that comes with owning what you want sexually. Truly a great read!"" --Jordan (Amazon Reader)",5.0,"""Not in my normal reading selection but this one is amazing!! I couldn't put it down! Suspense, touch her and die, HEA, strong main characters. I read a few of the reviews before starting bc I was worried about triggers and if the mfc was weak. Yes read the triggers! Is Blakely weak hell no! She starts out quiet and asking questions but Ryat brings out her strength.
44 | They are definitely a poor couple. I couldn't put this one down and soooo many surprises!!"" --ShyRyan Strong (Amazon Reader)",5.0,"""I have heard so much about this book and series and I kept holding off because a 600 page book is a lot to take on. But this book was so worth the read and I wish I would have sooner. Ryat is not at all what I was expecting him to be. He's possessive and controlling but he's got a hidden sweet side. Surprise twist ending, I honestly think this book could have been longer and not felt like it was too long. I want to know so much more of what happens after this book ends and everything in between with the second epilogue."" --Ashley (Amazon Reader)",5.0,"""This book was….something. I loved the dark mafia hitmen vibes. It was dark without being too brutal. Don't get me wrong, there were some WTF scenes, but it was still never over the limit. Read the trigger warnings.
45 |
46 | The characters all have such a personality! I loved their interactions and dynamics. Both Ryat and Blake were so independent and they truly grew and changed over the course of the book. I loved that they weren't boring.
47 |
48 | The one thing I could not get on board with in this book, though, Is that they kept saying song titles/ artists. TBH, I don't care. Give me a playlist at the beginning of the music is so important. Every time one came up I wanted to groan in frustration. Other than that, minus a few kind of noticeable spelling errors/ missing words, this book was a satisfying read."" --Caroline (Amazon Reader)",4.0,"""I finished it. Almost turned into a DNF about 60% of the way. I was completely content after half of the book was done then it DRAGGED on. Did not need to be 600 pages. Lots of repeating words and guessed plots. Like, yeah there's tons of twists and turns at the end of the book but I was way too tired to care because the beginning was a slow burn.
49 |
50 | 3/5 stars because I finished it finally. I did like the character relationships in it."" --Calysta Brown (Amazon Reader)",3.0
51 | 9,https://www.amazon.com/Inmate-gripping-psychological-thriller-ebook/dp/B0B1XQTZ1R/ref=zg_bs_g_157305011_sccl_3/145-2874000-5475018?psc=1,B0B1XQTZ1R,The Inmate,Freida McFadden,"Mystery, Thriller & Suspense",3.99,388.0,2022.0,"There are three rules Brooke Sullivan must follow as a new nurse practitioner at a men's maximum-security prison:
52 |
53 | 1) Treat all prisoners with respect.
54 |
55 | 2) Never reveal any personal information.
56 |
57 | 3) Never EVER become too friendly with the inmates.
58 |
59 | But none of the staff at the prison knows Brooke has already broken the rules. Nobody knows about her intimate connection to Shane Nelson, one of the penitentiary's most notorious and dangerous inmates.
60 |
61 | And they certainly don't know that Shane was Brooke's high school sweetheart—the star quarterback who is now spending the rest of his life in prison for a series of grisly murders. Or that Brooke's testimony was what put him there.
62 |
63 | But Shane knows.
64 |
65 | And he will never forget.","""This is my 3rd Freida Mcfadden book that I've read and also the 3rd one I haven't been able to put down! I read half of this book in 3 hours. I wanted to space it out and really enjoy it but once I told myself “I'll stop at this chapter” the chapters end in a way where you can't stop! You have to keep reading! She is an amazing author if you love a thriller! I will be reading all of her books and I highly recommend this one! Just when you think you have it figured out… you don't. That's what I love!"" --Courtney Lint (Amazon Reader)",5.0,"""What can I say about this book other than it kept me guessing on who the killer was. Needless to say I was partly right but I didn't guess correctly. And the Epilogue, oh my gosh! I absolutely loved this book and couldn't but it down because I needed to figure out what was going to happen next. Do not hesitate to read this book. It is awesome!"" --Amazon Customer",5.0,"""I have never been a fan of reading but I wanted to give it a go again because it's good for your brain and what not and I decided thrillers were something I might be alright with reading. So I started with this one and I did not expect to pick it up and quite literally not put it down. I didn't expect it to make me love reading and I never expected to be able to read all of that in one sitting but I adore the plot twists and I bought 2 more books by Freida McFadden because it was so good! Recommend reading this!!!"" --Tate Youngs (Amazon Reader)",5.0,"""Yet another book that leaves you guessing until the very end. Her twists always get me. If you like thrillers this is another great, quick read. It'll keep you intrigued to find out who really is at fault."" --Katelynn (Amazon Reader)",4.0,"""The book is a nice read between other novels. The imagery is a bit redundant and could be a bit better. The main character, Brooke is too swayed by others in my opinion. I rolled my eyes often regarding her naivety."" --Monica (Amazon Reader)",3.0
66 | 21,https://www.amazon.com/Serpent-Wings-Night-Crowns-Nyaxia-ebook/dp/B09WRJJKXC/ref=zg_bs_g_668010011_sccl_5/132-6615511-8040164?psc=1,B09WRJJKXC,The Serpent & The Wings of Night,Carissa Broadbent,Science Fiction & Fantasy,4.99,504.0,2022.0,"For humans and vampires, the rules of survival are the same: never trust, never yield, and always – always – guard your heart.
67 |
68 | The adopted human daughter of the Nightborn vampire king, Oraya carved her place in a world designed to kill her. Her only chance to become something more than prey is entering the Kejari: a legendary tournament held by the goddess of death herself.
69 |
70 | But winning won't be easy amongst the most vicious warriors from all three vampire houses. To survive, Oraya is forced to make an alliance with a mysterious rival.
71 |
72 | Everything about Raihn is dangerous. He is a ruthless vampire, an efficient killer, an enemy to her father's crown… and her greatest competition. Yet, what terrifies Oraya most of all is that she finds herself oddly drawn to him.
73 |
74 | But there's no room for compassion in the Kejari. War for the House of Night brews, shattering everything that Oraya thought she knew about her home. And Raihn may understand her more than anyone – but their blossoming attraction could be her downfall, in a kingdom where nothing is more deadly than love.","""Bought this after seeing it online and let me tell you, I was very pleasantly surprised. I was never able to guess where things were going and that's refreshing. The FMC is different than I expected her to be as well, she was almost relatable and I found myself rooting for her more than I usually do. And the twist at the end of the book? Phenomenal. I couldn't put this book down and I cannot wait to tear into the second one."" --Amanda E Cooper (Amazon Reader)",5.0,"""Simply put, I loved this book. I read the entire thing over the course of 48 hours and never lost interest or became bored with the storyline. That in itself for someone that reads more than 50 books a month is hugely impressive. So for those who devour paranormal romance novels with some gnarly and gruesome vampire carnage...make this book your next adventure, I promise you will not be disappointed. As for myself...I am off to start the next one because I need to know how this love/hate relationship between my newly favorite people ends. Happy Reading."" --Christine S (Amazon Reader)",5.0,"""Let me start by saying this book is nothing like ACOTAR, I had seen multiple accounts of people's claims Rahin reminded them of Rhys but not even their wings look the same.
75 |
76 | The first few chapters took me a while to get into. But once I was in, I couldn't put it down. This book was so exciting and full of plot twists, unexpected turn of events and very morally gray characters. Just how I like it.
77 |
78 | Other than the different vampire factions, it doesn't resemble anything I have read before. Highly recommended."" --Monica Restrepo (Amazon Reader)",5.0,"""The beginning was difficult to get through but once you're immersed in the world of the Moon Palace this book gradually draws you more and more in. Kind of like the slow burn of this romance between the two main characters. Some things I saw coming, others completely shocked me. Overall a very entertaining read, can't wait to start the next one."" --Stacey (Amazon Reader)",4.0,"""This book was not bad, the world building could have used some work , I felt like oraya was a little to naive and mentally innocent for someone who loves to kill vampires on her off time. Like sis couldn't piece 2+2 for the life of her. I guess after reading characters like rin fang, aelin, manon, and Jude Duarte, Oraya's inner monologue was giving little confused girl. However, pushing that aside, the book was not bad , I enjoyed it, the ending was predictable but the way in which she executed it was shocking and I will be reading the next book"" --Jaz (Amazon Reader)",3.0
79 | 23,https://www.amazon.com/Ashes-Star-Cursed-King-Crowns-Nyaxia-ebook/dp/B0BCQZP4SX/ref=zg_bs_g_668010011_sccl_12/132-6615511-8040164?psc=1,B0BCQZP4SX,The Ashes & The Star Cursed King,Carissa Broadbent,Science Fiction & Fantasy,4.99,626.0,2023.0,"Love is a sacrifice at the altar of power.
80 |
81 | In the wake of the Kejari, everything Oraya once thought to be true has been destroyed. A prisoner in her own kingdom, grieving the only family she ever had, and reeling from a gutting betrayal, she no longer even knows the truth of her own blood. She's left only with one certainty: she cannot trust anyone, least of all Raihn.
82 |
83 | The House of Night, too, is surrounded by enemies. Raihn's own nobles are none too eager to accept a Turned king, especially one who was once a slave. And the House of Blood digs their claws into the kingdom, threatening to tear it apart from the inside.
84 |
85 | When Raihn offers Oraya a secret alliance, taking the deal is her only chance at reclaiming her kingdom–and gaining her vengeance against the lover who betrayed her. But to do so, she'll need to harness a devastating ancient power, intertwined with her father's greatest secrets.
86 |
87 | But with enemies closing in on all sides, nothing is as it seems. As she unravels her past and faces her future, Oraya finds herself forced to choose between the bloody reality of seizing power – and the devastating love that could be her downfall.","""This book did not disappoint!
88 |
89 | I was a little worried when I realized it was dual pov (not normally a fan) but Carissa executed it beautifully! This book continues from where we left off in The Serpent and the Wings of Night, book one in the series. I was heartbroken with how the first book ended and was hoping The Ashes and the Star Cursed King would put my heart back together and BOY did it! I love that we get answers to so many questions and the character development for the main characters was fantastic to witness."" --Bre W. (Amazon Reader)",5.0,"""No spoilers here. But this author understands grief and how grieving people feel and think. The pain the FMC feels about losing her father feels so real to the reader. It made me ugly cry. But the book isn't all sad. It also shows how difficult it is to be vulnerable to another person as the FMC struggles with her feelings for the MMC. The characters are well developed and feel so real. On more than one occasion I felt the author put experiences and feelings into words that perfectly described my real life feelings better than I ever could. This book is an emotional ride but in a good way."" --Country girl (Amazon Reader)",5.0,"""Amazing plot twist with betrayal and heartbreaking secrets coming to light, epic wars with cruel gods. Beautiful character development, found family and passionate romance in this fantastic and fast paced follow up to The Serpent and the Wings of Night. No doubt the best romantasy of 2023. Can't wait for the next instalment 💙"" --Mrs Maartensson (Amazon Reader)",5.0,"""I would really like to give it 4.5star, it was not as amazing as the first book where every word counted. Every event mattered. In this book, I just felt the first 48% dragged on with FL being rather childish and ML really didn't take on his royal role. Having said that, the second 52% redeemed the book in my opinion. You really watch the characters grow from the first half the book while facing incredible odds."" --Nousheen H (Amazon Reader)",4.0,"""The first book was great! I devoured it in a single day! The characters, the plot, the twists and turns, the ending… just great. The second book? Not so much. I couldn't get into it, but I will definitely give it time and try again soon! Carissa is a great author and I wanted to love it! 🫶"" --Caity (Amazon Reader)",3.0
90 | 29,https://www.amazon.com/Court-Ravens-Ruin-Brides-Shadow-ebook/dp/B0BFFJRB2S/ref=zg_bs_g_668010011_sccl_31/132-6615511-8040164?psc=1,B0BFFJRB2S,Court of Ravens and Ruin,Eliza Raine,Science Fiction & Fantasy,2.99,312.0,2022.0,"A defiant human woman. A dark fae Prince. Two enemies bound to a marriage that could destroy their world.
91 |
92 | Reyna was born a valuable slave to the Gold Court, imprisoned her whole life in a glittering palace by sadistic, greedy fae.
93 | When the palace is raided, she takes her opportunity to escape. But the raid is led by her worst nightmare. The Prince of the most feared fae of all; the Shadow Court. And he wants one thing.
94 | Her. The copper-haired, rune-marked human.
95 |
96 | Reyna doesn't know why the Prince has kidnapped her. But when he announces her as his betrothed, she knows that she must escape before she is eternally bound to the monster behind the mask.
97 | Only, when he takes the mask off, he isn't what she expects. He's lethal, beautiful and exudes sin. And he needs her.
98 |
99 | Drawn into a deadly world shrouded in secrets, and desperate to keep her own hidden, Reyna must find a way out. If she doesn't, she risks more than just death. She risks giving everything to her intoxicating captor.","""I absolutely loved this start of the series! The world is introduced: Yggrasil (The tree of life) and along its roots are five different realms with different magic and fae. The humans are slaves in all the realms and the mc is a special kind of slave in the Gold realm. Her kind can wield the magic of gold into staves so that the fae can use magic. One day she gets kidnapped by the shadow court and realizes the world is more than she thought, and filled with more terrors than she could've imagined. She is quickly thrown into a plot of deception and everywhere she goes someone is trying to kill her.
100 | I adored how the author combined the fae world with norse mythology; the names, the gods, the beliefs, Amazing! Can't wait to read the next one! 👏"" --Isabelle (Amazon Reader)",5.0,"""It kept me on my toes the whole time I was reading this book it could not be put down I devoured it all in one day. Just found a new author that I deeply admire and I'm off to the next book"" --Kindle Customer",5.0,"""Keeps you on your toes, interesting world, great characters, enjoyable read. High Fantasy at its best. Has some spice but relatable to the story and not overwhelming or taking over the story.
101 | Quick note for the writer, horses don't ""snicker"" they nicker. Could have been an editing typo, but really needs to be fixed."" --Buffalocolt27 (Amazon Reader)",5.0,"""This is a really good, quick read. I'm certainly hooked and will finish the series but I feel like it could have been longer with a little more detail. It does seem very rushed.
102 | It's very much the “enemies to lovers,” “dark prince,” “fae and human,” “strong, stubborn fmc” trope(s) which is somewhat predictable but not bad. Think of Guild meets ACOTAR meets FBAA. The gold, the stubborn human falling for the enemy fae, the “chosen one.”
103 | I feel like ending on a cliffhanger is definitely utilized to get the reader to continue the next book to make up for how rushed everything else is. Overall, 4/5 and I will be reading on though slightly disappointed."" --Jimmie (Amazon Reader)",4.0,"""All 4 books are quick reads. There were a few grammar errors, and a few confusing transitions throughout the series. The plot is interesting, but becomes tedious with all the secrets no one can expose. This series has the main FMC having an enemies to (only 1) lover, and there is at least 1 spice scene in each novel. The spice is rated one pepper out of 5. Having undead (or zombie like) creatures in a fae novel was a new one for me."" --Sound Judgement (Amazon Reader)",3.0
104 | 45,https://www.amazon.com/Dopamine-Detox-Remove-Distractions-Productivity-ebook/dp/B098MHBF23/ref=zg_bs_g_156563011_sccl_23/132-6615511-8040164?psc=1,B098MHBF23,Dopamine Detox,Thibaut Meurisse,Self-Help,2.99,62.0,2021.0,"Reclaim your focus in 48 hours or less.
105 | Do you keep procrastinating? Do you feel restless and unable to focus on your work? Do you have trouble getting excited about major goals?
106 |
107 | If so, you might need a dopamine detox.
108 |
109 | In today's world where distractions are everywhere, the ability to focus has become more and more difficult to achieve. We are constantly being stimulated, feeling restless, often without knowing why.
110 |
111 | When the time comes to work, we suddenly find an excess of other things to do. Instead of working toward our goals, we go for a walk, grab a coffee, or check our emails. Everything seems like a great idea—everything except the very things we should be doing.
112 |
113 | Do you recognize yourself in the above situation?
114 |
115 | If so, don't worry. You're simply overstimulated.
116 |
117 | Dopamine Detox will help you lower your level of stimulation and regain focus in 48 hours or less,so that you can tackle your key tasks.
118 |
119 | More specifically, in Dopamine Detox you'll discover:
120 |
121 | what dopamine is and how it works.
122 | the main benefits of completing a dopamine detox.
123 | 3 simple steps to implement a successful detox in the next 48 hours.
124 | practical exercises to eliminate distractions and boost your focus.
125 | simple tools and techniques to avoid overstimulation and help you stay focused, and much more.
126 | Dopamine Detox is your must-read, must-follow guide to help you remove distractions so you can finally work on your goals with ease. If you like easy-to-understand strategies, practical exercises, and no-nonsense teaching, you will love this book.","""You've likely heard the phrase “chew up the meat and spit out the bones”, in other words, take away the important or relevant bits and leave the rest that don't matter… this book is all meat.
127 | It's short bc it's poignant. Great practical advice and easy to implement."" --Delyn (Amazon Reader)",5.0,"""Love this book because it doesn't have all the fluff no one cares about. It explains the issue of overstimulation and how you can combat it. There is even workbook pages in the back."" --Daniel Manz (Amazon Reader)",5.0,"""I feel like this book touched on a lot of issues I experience personally, I didn't know that my experience was so similar to others who procrastinate. The steps in the book are very simple but effective, it's a great read for anyone having trouble doing the tough tasks, that we so often put off."" --Jason (Amazon Reader)",5.0,"""Author sets up good habits and reasons why overstimulation in todays world is affecting our lives greater than what we can imagine. Author does a good job in raising our consciousness when it comes to social media or anything else involving overstimulation."" --Roy Saenz (Amazon Reader)",4.0,"""A quick and useful guide to help live a more productive life. Reinforcing what we know about distractions and technology, and how to
128 | overcome its grip on our lives."" --Amanda Magro (Amazon Reader)",3.0
129 | 46,https://www.amazon.com/Dont-Believe-Everything-You-Think-ebook/dp/B09WQ218GR/ref=zg_bs_g_156563011_sccl_26/145-2874000-5475018?psc=1,B09WQ218GR,Don't Believe Everything You Think,Joseph Nguyen,Self-Help,4.99,126.0,2022.0,"Learn how to overcome anxiety, self-doubt & self-sabotage without needing to rely on motivation or willpower.
130 |
131 | In this book, you'll discover the root cause of all psychological and emotional suffering and how to achieve freedom of mind to effortlessly create the life you've always wanted to live.
132 |
133 | Although pain is inevitable, suffering is optional.
134 |
135 | This book offers a completely new paradigm and understanding of where our human experience comes from, allowing us to end our own suffering and create how we want to feel at any moment.
136 |
137 | In This Book, You'll Discover:
138 |
139 | The root cause of all psychological and emotional suffering and how to end it
140 | How to become unaffected by negative thoughts and feelings
141 | How to experience unconditional love, peace, and joy in the present, no matter what our external circumstances look like
142 | How to instantly create a new experience of life if you don't like the one you're in right now
143 | How to break free from a negative thought loop when we inevitably get caught in one
144 | How to let go of anxiety, self-doubt, self-sabotage, and any self-destructive habits
145 | How to effortlessly create from a state of abundance, flow, and ease
146 | How to develop the superpower of being okay with not knowing and uncertainty
147 | How to access your intuition and inner wisdom that goes beyond the limitations of thinking
148 |
149 | No matter what has happened to you, where you are from, or what you have done, you can still find total peace, unconditional love, complete fulfillment, and an abundance of joy in your life.
150 |
151 | No person is an exception to this. Darkness only exists because of the light, which means even in our darkest hour, light must exist.
152 |
153 | Within the pages of this book, contains timeless wisdom to empower you with the understanding of our mind's infinite potential to create any experience of life that we want no matter the external circumstances.
154 |
155 | ‘Don't Believe Everything You Think' is not about rewiring your brain, rewriting your past, positive thinking or anything of the sort.
156 |
157 | We cannot solve our problems with the same level of consciousness that created them. Tactics are temporary. An expansion of consciousness is permanent.
158 |
159 | This book was written to help you go beyond your thinking and discover the truth of what you already intuitively know deep inside your soul.","""I enjoyed this quick-read. It was more of an intro to a zen way of thinking, enlightenment. It seemed like a lot of the same words repeating, but nonetheless it was still interesting and an easy read. If you're looking for ways to stop overthinking or are getting into looking for zen, and peacefulness in your mind, this is a good book for you."" --Haley Jean (Amazon Reader)",5.0,"""I truly felt like a weight was lifted off of my shoulders after reading this book. Simple and straightforward. To think life could be so simple. Just let go of your thinking and enjoy the present moment. I would recommend this to anyone who suffers from overthinking."" --Nefertima (Amazon Reader)",5.0,"""I love that this author used easy to understand language to explain how our thoughts cause all of our problems! He did a great job using examples and providing steps to help you get on the journey to having a peaceful mind."" --Kindle Customer",5.0,"""The book is full of valuable information, and the author's enthusiasm to share a path to greater happiness with his readers is clear. I've been trying the practice for three days now, and so far it works. I think I will take a few minutes each morning to go outside and just look/listen...no thinking! A quiet contentment arises when I just allow a ""first thought"" to hang there without commenting. Works with hard emotions too, if you have the guts to resist trying to talk yourself out of them.
160 |
161 | The writing isn't elegant, but that's beside the point. Also, the parts about the Universe might be a bit much for someone who hasn't yet investigated reality beyond materialism, but I found it to be enlightening. Thank you Joseph"" --""lparks0111"" (Amazon Reader)",4.0,"""This is likely most suited to people who are more analytically-minded. For those on the more creative, artistic side - much of the book is nothing new. I can see that for some, it would be valuable - but for me it wasn't ""speaking my language""."" --D. Harrison (Amazon Reader)",3.0
162 | 47,https://www.amazon.com/Art-Letting-GO-Forward-Emotional-ebook/dp/B09T66MSLN/ref=zg_bs_g_156563011_sccl_31/145-2874000-5475018?psc=1,B09T66MSLN,The Art of Letting Go,Damon Zahariades,Self-Help,2.99,196.0,2022.0,"Finally Let Go of Your Negative Thoughts and Enjoy the Emotional Freedom You Deserve!
163 | Are you struggling with anger, regrets, and resentment? Do you feel emotionally exhausted, stressed, and discouraged by painful memories? Are you holding on to things that are making you feel miserable?
164 |
165 | If so, THE ART OF LETTING GO is for you.
166 |
167 | Imagine being able to let go of the emotional turmoil that's burdening you. Imagine being able to finally release the negative thoughts and painful memories that are weighing you down.
168 |
169 | THE ART OF LETTING GO gives you a complete toolkit that you can use to overcome the emotional anguish that's ruining your quality of life.
170 |
171 | You'll learn numerous strategies you can employ to reverse years of negative mental conditioning. You'll discover how to retrain your brain and jettison crippling thought patterns.
172 |
173 | You'll receive all of the tools you need to finally let go of the emotional anchors that are preventing you from enjoying life to its fullest.
174 |
175 | In THE ART OF LETTING GO, you'll discover:
176 |
177 | the 20 most common things people hold on to (and endure misery as a result)
178 | why it's so difficult to let go of negative thoughts and painful memories
179 | how to revoke your inner critic's privileges and silence its hurtful voice
180 | why we idealize the past and how doing so pushes us to cling to emotional pain in the present (and a technique for short circuiting this process)
181 | how trying to make yourself happy is actually causing you to feel unhappy
182 | one of the most powerful and simplest ways to let things go (and you can use it immediately!)
183 |
184 | PLUS, BONUS MATERIAL: in addition to 21 strategies you can use to confront and finally let go of your negative thoughts and emotions, you'll also receive 3 BONUS strategies. Few people talk about these 3 tactics, but they work wonders.
185 |
186 | Moreover, each strategy comes with an exercise designed to give you an opportunity to put it to immediate use.
187 |
188 | If you're tired of feeling burdened by painful memories, bitterness, regret, shame, and other debilitating emotions, it's time to make a positive, rewarding change. Grab your copy of THE ART OF LETTING GO today and finally experience the emotional freedom you deserve.","""Thoughtful analysis and great exercises for letting go of the past. I highly recommend using this book whenever you feel drowned by regret."" --Yvonne Tran (Amazon Reader)",5.0,"""If you're looking to turn the page on your past and move into a healthier state of mind for your future this is a great read. Lots of great tips and exercises to help you move forward from past behaviors that you want to shed."" --trefault (Amazon Reader)",5.0,"""I've read quite a few books of this genre, but this is the first one I've found that explains how our emotions, once necessary for survival, can work against us, and how to reset thought patterns that are no longer in our best interest. There are numerous exercises, and many of them have examples, making it easy to get started. The book is comprehensive, but I'd love to meet the author and pick his brain even further."" --Kathryn Brooks (Amazon Reader)",5.0,"""I really enjoyed this book and the lessons. I like that it gave us time frames to focus on the lesson, encouraging us to take our time and not rush through them. I also likes the examples as it helped push my thoughts into gear and to think of more things than I may have on my own. The quotes at the beginning of the chapters were excellent. I saved many of them.
189 | My only negative is some of the content was a little redundant in the chapters. It felt like a few sentences were just reworded to add length."" --William (Amazon Reader)",4.0,"""This is the second or third book that I read from this author and I found it quite forgettable, just as his other ones. The information is always a personal view and conclusions from the author rather than a researched and backed analysis of the subject being presented. Every piece of advice or information can be derived from common sense with very little insight or novelty for someone with a slightly over average skill for overcoming negative situations. I can't imagine what kind of individual would benefit from this book other than the author himself. I don't recommend this nor other books by this author."" --Ignacio Zamora (Amazon Reader)",3.0
190 |
--------------------------------------------------------------------------------
/examples/example_data/texts/descriptions.csv:
--------------------------------------------------------------------------------
1 | id,description
2 | 3,"After a year in captivity, a kidnapped child escapes—only to reveal horrific truths that lead her psychologist on a race against time in this thriller from New York Times bestselling author Mike Omer.
3 |
4 | When eight-year-old Kathy Stone turns up on the side of the road a year after her abduction, the world awaits her harrowing story. But Kathy doesn't say a word. Traumatized by her ordeal, she doesn't speak at all, not even to her own parents.
5 |
6 | Child therapist Robin Hart is the only one who's had success connecting with the girl. Robin has been using play therapy to help Kathy process her memories. But as their work continues, Kathy's playtime takes a grim turn: a doll stabs another doll, a tiny figurine is chained to a plastic toy couch. All of these horrifying moments, enacted within a Victorian doll house. Every session, another toy dies.
7 |
8 | But the most disturbing detail? Kathy seems to be playacting real unsolved murders.
9 |
10 | Soon Robin wonders if Kathy not only holds the key to the murders of the past but if she knows something about the murders of the future. Can Robin unlock the secrets in Kathy's brain and stop a serial killer before he strikes again? Or is Robin's work with Kathy putting her in the killer's sights?"
11 | 4,"“Welcome to the family,” Nina Winchester says as I shake her elegant, manicured hand. I smile politely, gazing around the marble hallway. Working here is my last chance to start fresh. I can pretend to be whoever I like. But I'll soon learn that the Winchesters' secrets are far more dangerous than my own…
12 |
13 | Every day I clean the Winchesters' beautiful house top to bottom. I collect their daughter from school. And I cook a delicious meal for the whole family before heading up to eat alone in my tiny room on the top floor.
14 |
15 | I try to ignore how Nina makes a mess just to watch me clean it up. How she tells strange lies about her own daughter. And how her husband Andrew seems more broken every day. But as I look into Andrew's handsome brown eyes, so full of pain, it's hard not to imagine what it would be like to live Nina's life. The walk-in closet, the fancy car, the perfect husband.
16 |
17 | I only try on one of Nina's pristine white dresses once. Just to see what it's like. But she soon finds out… and by the time I realize my attic bedroom door only locks from the outside, it's far too late.
18 |
19 | But I reassure myself: the Winchesters don't know who I really am.
20 |
21 | They don't know what I'm capable of…"
22 | 8,"THE CHOSEN ONE
23 |
24 | Barrington University is home of the Lords, a secret society that requires their blood in payment. They are above all—the most powerful men in the world. They devote their lives to violence in exchange for power. And during their senior year, they are offered a chosen one.
25 |
26 | I VOW. YOU VOW. WE VOW.
27 |
28 | People think growing up with money is freeing, but I promise you, it's not. My entire life has been planned out for me. I never got the chance to do what I wanted until Ryat Alexander Archer came along and gave me an option for a better life. He offered me what no one else ever had—freedom.
29 |
30 | I chose to be his. He made me believe that anyway, but it was just another lie. A way that the Lords manipulate you into doing what they want.
31 |
32 | After being sucked into the dark, twisted world of the Lords, I embraced my new role and allowed Ryat to parade me around like the trophy I was to him. But like all things, what started out as a game soon became a fight for survival. And the only way out was death."
33 | 9,"There are three rules Brooke Sullivan must follow as a new nurse practitioner at a men's maximum-security prison:
34 |
35 | 1) Treat all prisoners with respect.
36 |
37 | 2) Never reveal any personal information.
38 |
39 | 3) Never EVER become too friendly with the inmates.
40 |
41 | But none of the staff at the prison knows Brooke has already broken the rules. Nobody knows about her intimate connection to Shane Nelson, one of the penitentiary's most notorious and dangerous inmates.
42 |
43 | And they certainly don't know that Shane was Brooke's high school sweetheart—the star quarterback who is now spending the rest of his life in prison for a series of grisly murders. Or that Brooke's testimony was what put him there.
44 |
45 | But Shane knows.
46 |
47 | And he will never forget."
48 | 21,"For humans and vampires, the rules of survival are the same: never trust, never yield, and always – always – guard your heart.
49 |
50 | The adopted human daughter of the Nightborn vampire king, Oraya carved her place in a world designed to kill her. Her only chance to become something more than prey is entering the Kejari: a legendary tournament held by the goddess of death herself.
51 |
52 | But winning won't be easy amongst the most vicious warriors from all three vampire houses. To survive, Oraya is forced to make an alliance with a mysterious rival.
53 |
54 | Everything about Raihn is dangerous. He is a ruthless vampire, an efficient killer, an enemy to her father's crown… and her greatest competition. Yet, what terrifies Oraya most of all is that she finds herself oddly drawn to him.
55 |
56 | But there's no room for compassion in the Kejari. War for the House of Night brews, shattering everything that Oraya thought she knew about her home. And Raihn may understand her more than anyone – but their blossoming attraction could be her downfall, in a kingdom where nothing is more deadly than love."
57 | 23,"Love is a sacrifice at the altar of power.
58 |
59 | In the wake of the Kejari, everything Oraya once thought to be true has been destroyed. A prisoner in her own kingdom, grieving the only family she ever had, and reeling from a gutting betrayal, she no longer even knows the truth of her own blood. She's left only with one certainty: she cannot trust anyone, least of all Raihn.
60 |
61 | The House of Night, too, is surrounded by enemies. Raihn's own nobles are none too eager to accept a Turned king, especially one who was once a slave. And the House of Blood digs their claws into the kingdom, threatening to tear it apart from the inside.
62 |
63 | When Raihn offers Oraya a secret alliance, taking the deal is her only chance at reclaiming her kingdom–and gaining her vengeance against the lover who betrayed her. But to do so, she'll need to harness a devastating ancient power, intertwined with her father's greatest secrets.
64 |
65 | But with enemies closing in on all sides, nothing is as it seems. As she unravels her past and faces her future, Oraya finds herself forced to choose between the bloody reality of seizing power – and the devastating love that could be her downfall."
66 | 29,"A defiant human woman. A dark fae Prince. Two enemies bound to a marriage that could destroy their world.
67 |
68 | Reyna was born a valuable slave to the Gold Court, imprisoned her whole life in a glittering palace by sadistic, greedy fae.
69 | When the palace is raided, she takes her opportunity to escape. But the raid is led by her worst nightmare. The Prince of the most feared fae of all; the Shadow Court. And he wants one thing.
70 | Her. The copper-haired, rune-marked human.
71 |
72 | Reyna doesn't know why the Prince has kidnapped her. But when he announces her as his betrothed, she knows that she must escape before she is eternally bound to the monster behind the mask.
73 | Only, when he takes the mask off, he isn't what she expects. He's lethal, beautiful and exudes sin. And he needs her.
74 |
75 | Drawn into a deadly world shrouded in secrets, and desperate to keep her own hidden, Reyna must find a way out. If she doesn't, she risks more than just death. She risks giving everything to her intoxicating captor."
76 | 45,"Reclaim your focus in 48 hours or less.
77 | Do you keep procrastinating? Do you feel restless and unable to focus on your work? Do you have trouble getting excited about major goals?
78 |
79 | If so, you might need a dopamine detox.
80 |
81 | In today's world where distractions are everywhere, the ability to focus has become more and more difficult to achieve. We are constantly being stimulated, feeling restless, often without knowing why.
82 |
83 | When the time comes to work, we suddenly find an excess of other things to do. Instead of working toward our goals, we go for a walk, grab a coffee, or check our emails. Everything seems like a great idea—everything except the very things we should be doing.
84 |
85 | Do you recognize yourself in the above situation?
86 |
87 | If so, don't worry. You're simply overstimulated.
88 |
89 | Dopamine Detox will help you lower your level of stimulation and regain focus in 48 hours or less,so that you can tackle your key tasks.
90 |
91 | More specifically, in Dopamine Detox you'll discover:
92 |
93 | what dopamine is and how it works.
94 | the main benefits of completing a dopamine detox.
95 | 3 simple steps to implement a successful detox in the next 48 hours.
96 | practical exercises to eliminate distractions and boost your focus.
97 | simple tools and techniques to avoid overstimulation and help you stay focused, and much more.
98 | Dopamine Detox is your must-read, must-follow guide to help you remove distractions so you can finally work on your goals with ease. If you like easy-to-understand strategies, practical exercises, and no-nonsense teaching, you will love this book."
99 | 46,"Learn how to overcome anxiety, self-doubt & self-sabotage without needing to rely on motivation or willpower.
100 |
101 | In this book, you'll discover the root cause of all psychological and emotional suffering and how to achieve freedom of mind to effortlessly create the life you've always wanted to live.
102 |
103 | Although pain is inevitable, suffering is optional.
104 |
105 | This book offers a completely new paradigm and understanding of where our human experience comes from, allowing us to end our own suffering and create how we want to feel at any moment.
106 |
107 | In This Book, You'll Discover:
108 |
109 | The root cause of all psychological and emotional suffering and how to end it
110 | How to become unaffected by negative thoughts and feelings
111 | How to experience unconditional love, peace, and joy in the present, no matter what our external circumstances look like
112 | How to instantly create a new experience of life if you don't like the one you're in right now
113 | How to break free from a negative thought loop when we inevitably get caught in one
114 | How to let go of anxiety, self-doubt, self-sabotage, and any self-destructive habits
115 | How to effortlessly create from a state of abundance, flow, and ease
116 | How to develop the superpower of being okay with not knowing and uncertainty
117 | How to access your intuition and inner wisdom that goes beyond the limitations of thinking
118 |
119 | No matter what has happened to you, where you are from, or what you have done, you can still find total peace, unconditional love, complete fulfillment, and an abundance of joy in your life.
120 |
121 | No person is an exception to this. Darkness only exists because of the light, which means even in our darkest hour, light must exist.
122 |
123 | Within the pages of this book, contains timeless wisdom to empower you with the understanding of our mind's infinite potential to create any experience of life that we want no matter the external circumstances.
124 |
125 | ‘Don't Believe Everything You Think' is not about rewiring your brain, rewriting your past, positive thinking or anything of the sort.
126 |
127 | We cannot solve our problems with the same level of consciousness that created them. Tactics are temporary. An expansion of consciousness is permanent.
128 |
129 | This book was written to help you go beyond your thinking and discover the truth of what you already intuitively know deep inside your soul."
130 | 47,"Finally Let Go of Your Negative Thoughts and Enjoy the Emotional Freedom You Deserve!
131 | Are you struggling with anger, regrets, and resentment? Do you feel emotionally exhausted, stressed, and discouraged by painful memories? Are you holding on to things that are making you feel miserable?
132 |
133 | If so, THE ART OF LETTING GO is for you.
134 |
135 | Imagine being able to let go of the emotional turmoil that's burdening you. Imagine being able to finally release the negative thoughts and painful memories that are weighing you down.
136 |
137 | THE ART OF LETTING GO gives you a complete toolkit that you can use to overcome the emotional anguish that's ruining your quality of life.
138 |
139 | You'll learn numerous strategies you can employ to reverse years of negative mental conditioning. You'll discover how to retrain your brain and jettison crippling thought patterns.
140 |
141 | You'll receive all of the tools you need to finally let go of the emotional anchors that are preventing you from enjoying life to its fullest.
142 |
143 | In THE ART OF LETTING GO, you'll discover:
144 |
145 | the 20 most common things people hold on to (and endure misery as a result)
146 | why it's so difficult to let go of negative thoughts and painful memories
147 | how to revoke your inner critic's privileges and silence its hurtful voice
148 | why we idealize the past and how doing so pushes us to cling to emotional pain in the present (and a technique for short circuiting this process)
149 | how trying to make yourself happy is actually causing you to feel unhappy
150 | one of the most powerful and simplest ways to let things go (and you can use it immediately!)
151 |
152 | PLUS, BONUS MATERIAL: in addition to 21 strategies you can use to confront and finally let go of your negative thoughts and emotions, you'll also receive 3 BONUS strategies. Few people talk about these 3 tactics, but they work wonders.
153 |
154 | Moreover, each strategy comes with an exercise designed to give you an opportunity to put it to immediate use.
155 |
156 | If you're tired of feeling burdened by painful memories, bitterness, regret, shame, and other debilitating emotions, it's time to make a positive, rewarding change. Grab your copy of THE ART OF LETTING GO today and finally experience the emotional freedom you deserve."
157 |
--------------------------------------------------------------------------------
/examples/example_data/texts/reviews.csv:
--------------------------------------------------------------------------------
1 | id,user_review_1,user_review_2,user_review_3,user_review_4,user_review_5
2 | 3,"""This was almost an Amazon First Read's pick for me but I grabbed a different one instead. I couldn't stop thinking about the sample I'd read from it though and ended up buying it anyway and waiting for the December release. Today I remembered I had access to it and started reading and didn't put it down except for two dog potty breaks and a puppy bath. I just finished reading it this afternoon and was so satisfied with the entire book. It kept me on the edge of my seat and had the perfect mix of tension and relief. Thoroughly enjoyed this thriller and would recommend it to anyone who enjoys true crime reads or thriller novels and is looking for another new book to read."" --Meghan Miller (Amazon Reader)","""I don't leave reviews very often, but just finished this book last night. I've read other books by Mr Omer and enjoyed them, but this one - this one is in a class all its own. It starts out pretty laid back but builds as pages turn. I actually had to stay up to the wee hours of the morning to finish it and find out the who what where and why of the abduction. A great read, perhaps because it didn't follow the standard tropes of its genre and consequently surprises the reader as they get drawn in ever deeper to the characters and the story itself.
3 |
4 | Way to go Mr. Omer! You managed to totally wreck my sleep patterns - something most books don't accomplish. LMAO"" --Karen DeCrane (Amazon Reader)","""It took me a while at the beginning to piece the non-linear chapters together but once I did, I found this book to be extremely thought-provoking, realistic and trying to figure out who the bad guy was. When I got close to the end, and the romance was beginning I thought oh it's just another case solved now two people fall in love and live happily ever after but it turns out there was a twist to the plot, which Turned out to be another story in itself, and even though they still fell in love at the end, it was one page and wasn't cheesy"" --D. Burton (Amazon Reader)","""Eight-year-old Kathy Stone disappeared from her own yard one day. A year later, she was found on the side of the road. Many suspected that she had died, but everyone wants to know where she has been. Kathy is so traumatized that she no longer speaks. It is up to her therapist, Robin Hart, who, through play therapy, rushes to learn what had happened to poor Kathy, before she is recaptured by her kidnapper. Little by little, Kathy reveals the truth through dolls and toys. Robin is horrified by Kathy's story.
5 |
6 | Mike Omer's realistic and well-developed characters take the reader on a journey to discover the truth. This is an intriguing story filled with unexpected twists and turns."" --Sandra (Amazon Reader)","""I realized liked the storyline for the book, it was so good and well written, it literally kept me wanting more, but unfortunately I felt that it began slow, then sped up, and slowed again and the worst part about it was how confusing it was trying to see what character I was reading in the chapter, it would've been nice author wrote “robin” “Kathy” to give some hint, I think that is what bothered me most, over all I loved the book it, a lot of thrill, mystery, and mind games a couple times I knew who the abductor was then I was proven wrong in the end. I'd recommend this book but with notice about the confusion between the back and forth chapters."" --M. Zambrano (Amazon Reader)"
7 | 4,"""This book was so much fun to read. I picked it from the list for one of the Kindle challenges and was not disappointed. On the way home from errands one day I wondered what would be next for Millie and Nina. After all, Millie's an ex con and Nina's an ex psych ward patient, so how much trouble could they get into just hanging around the house while Nina's husband Andrew is working. Lots! That's how much.
8 |
9 | Right up until the last few pages I was still being surprised. I will miss these characters.
10 |
11 | And to steal a line from the ABC hit show NYPD Blue, a detective in Internal Affairs told Detective Bobby Simone that everything is a situation. In this book that's an understatement."" --J. Weston (Amazon Reader)","""At first, I wasn't sure where the story was going - but as I kept reading, I became more and more intrigued. I couldn't put the book down! It went in a completely different direction than what I predicted. Whatever you THINK you know, you don't. I was literally gasping reading it (I was actually quite expressive while reading the entire book lol). This was such a great read. I'm excited to read the rest of the series! You won't be disappointed at all with this one!! Get your copy now!"" --Lenisha (Amazon Reader)","""A down and out young woman gets a dream job with a wealthy family. She is greeted warmly and is quite impressed by the couple and the little daughter. But things aren't as they appear to be. A wife with mental issues, a handsome caring husband, and a bratty child. Hired as a housekeeper and nanny, Millie does her best to handle all the disturbing issues.
12 | I read the book in one day and the twists and turns kept me intrigued…right up to the surprising ending."" --babs (Amazon Reader)","""First novel by Freida McFadden. When I downloaded this book on Kindle Unlimited I didn't realize it was a series. It's a book that doesn't require much thinking and I was hooked from the beginning. I found part 1 and part 2 to be quite predictable but part 3 was a shocker. The twists in this story were good except at the very end then the plot kind of collapses.
13 |
14 | It's definitely a popcorn read. It was entertaining, a bit predictable, some light suspense, and an all around easy read with a couple silly parts. I would recommend."" --Mary (Amazon Reader)","""I'm honestly between a 2.5 and a 3 star rating for this book. I thought the story-building was okay but I tended to get annoyed with the main character often. I also was not surprised by any of the “plot twists”, I felt like everything was pretty predictable."" --Mariela M. (Amazon Reader)"
15 | 8,"""I absolutely loved learning about the Lords, Ryat and Blakely. Yes the steam and sex was great, and right on par for anyone who loves darker kinks, but the drama and the story was so intriguing. For some readers, I can understand it might be triggering. But as someone who has dealt with some of the triggers in the book, it was empowering reading about a female character choosing and understanding the power that comes with owning what you want sexually. Truly a great read!"" --Jordan (Amazon Reader)","""Not in my normal reading selection but this one is amazing!! I couldn't put it down! Suspense, touch her and die, HEA, strong main characters. I read a few of the reviews before starting bc I was worried about triggers and if the mfc was weak. Yes read the triggers! Is Blakely weak hell no! She starts out quiet and asking questions but Ryat brings out her strength.
16 | They are definitely a poor couple. I couldn't put this one down and soooo many surprises!!"" --ShyRyan Strong (Amazon Reader)","""I have heard so much about this book and series and I kept holding off because a 600 page book is a lot to take on. But this book was so worth the read and I wish I would have sooner. Ryat is not at all what I was expecting him to be. He's possessive and controlling but he's got a hidden sweet side. Surprise twist ending, I honestly think this book could have been longer and not felt like it was too long. I want to know so much more of what happens after this book ends and everything in between with the second epilogue."" --Ashley (Amazon Reader)","""This book was….something. I loved the dark mafia hitmen vibes. It was dark without being too brutal. Don't get me wrong, there were some WTF scenes, but it was still never over the limit. Read the trigger warnings.
17 |
18 | The characters all have such a personality! I loved their interactions and dynamics. Both Ryat and Blake were so independent and they truly grew and changed over the course of the book. I loved that they weren't boring.
19 |
20 | The one thing I could not get on board with in this book, though, Is that they kept saying song titles/ artists. TBH, I don't care. Give me a playlist at the beginning of the music is so important. Every time one came up I wanted to groan in frustration. Other than that, minus a few kind of noticeable spelling errors/ missing words, this book was a satisfying read."" --Caroline (Amazon Reader)","""I finished it. Almost turned into a DNF about 60% of the way. I was completely content after half of the book was done then it DRAGGED on. Did not need to be 600 pages. Lots of repeating words and guessed plots. Like, yeah there's tons of twists and turns at the end of the book but I was way too tired to care because the beginning was a slow burn.
21 |
22 | 3/5 stars because I finished it finally. I did like the character relationships in it."" --Calysta Brown (Amazon Reader)"
23 | 9,"""This is my 3rd Freida Mcfadden book that I've read and also the 3rd one I haven't been able to put down! I read half of this book in 3 hours. I wanted to space it out and really enjoy it but once I told myself “I'll stop at this chapter” the chapters end in a way where you can't stop! You have to keep reading! She is an amazing author if you love a thriller! I will be reading all of her books and I highly recommend this one! Just when you think you have it figured out… you don't. That's what I love!"" --Courtney Lint (Amazon Reader)","""What can I say about this book other than it kept me guessing on who the killer was. Needless to say I was partly right but I didn't guess correctly. And the Epilogue, oh my gosh! I absolutely loved this book and couldn't but it down because I needed to figure out what was going to happen next. Do not hesitate to read this book. It is awesome!"" --Amazon Customer","""I have never been a fan of reading but I wanted to give it a go again because it's good for your brain and what not and I decided thrillers were something I might be alright with reading. So I started with this one and I did not expect to pick it up and quite literally not put it down. I didn't expect it to make me love reading and I never expected to be able to read all of that in one sitting but I adore the plot twists and I bought 2 more books by Freida McFadden because it was so good! Recommend reading this!!!"" --Tate Youngs (Amazon Reader)","""Yet another book that leaves you guessing until the very end. Her twists always get me. If you like thrillers this is another great, quick read. It'll keep you intrigued to find out who really is at fault."" --Katelynn (Amazon Reader)","""The book is a nice read between other novels. The imagery is a bit redundant and could be a bit better. The main character, Brooke is too swayed by others in my opinion. I rolled my eyes often regarding her naivety."" --Monica (Amazon Reader)"
24 | 21,"""Bought this after seeing it online and let me tell you, I was very pleasantly surprised. I was never able to guess where things were going and that's refreshing. The FMC is different than I expected her to be as well, she was almost relatable and I found myself rooting for her more than I usually do. And the twist at the end of the book? Phenomenal. I couldn't put this book down and I cannot wait to tear into the second one."" --Amanda E Cooper (Amazon Reader)","""Simply put, I loved this book. I read the entire thing over the course of 48 hours and never lost interest or became bored with the storyline. That in itself for someone that reads more than 50 books a month is hugely impressive. So for those who devour paranormal romance novels with some gnarly and gruesome vampire carnage...make this book your next adventure, I promise you will not be disappointed. As for myself...I am off to start the next one because I need to know how this love/hate relationship between my newly favorite people ends. Happy Reading."" --Christine S (Amazon Reader)","""Let me start by saying this book is nothing like ACOTAR, I had seen multiple accounts of people's claims Rahin reminded them of Rhys but not even their wings look the same.
25 |
26 | The first few chapters took me a while to get into. But once I was in, I couldn't put it down. This book was so exciting and full of plot twists, unexpected turn of events and very morally gray characters. Just how I like it.
27 |
28 | Other than the different vampire factions, it doesn't resemble anything I have read before. Highly recommended."" --Monica Restrepo (Amazon Reader)","""The beginning was difficult to get through but once you're immersed in the world of the Moon Palace this book gradually draws you more and more in. Kind of like the slow burn of this romance between the two main characters. Some things I saw coming, others completely shocked me. Overall a very entertaining read, can't wait to start the next one."" --Stacey (Amazon Reader)","""This book was not bad, the world building could have used some work , I felt like oraya was a little to naive and mentally innocent for someone who loves to kill vampires on her off time. Like sis couldn't piece 2+2 for the life of her. I guess after reading characters like rin fang, aelin, manon, and Jude Duarte, Oraya's inner monologue was giving little confused girl. However, pushing that aside, the book was not bad , I enjoyed it, the ending was predictable but the way in which she executed it was shocking and I will be reading the next book"" --Jaz (Amazon Reader)"
29 | 23,"""This book did not disappoint!
30 |
31 | I was a little worried when I realized it was dual pov (not normally a fan) but Carissa executed it beautifully! This book continues from where we left off in The Serpent and the Wings of Night, book one in the series. I was heartbroken with how the first book ended and was hoping The Ashes and the Star Cursed King would put my heart back together and BOY did it! I love that we get answers to so many questions and the character development for the main characters was fantastic to witness."" --Bre W. (Amazon Reader)","""No spoilers here. But this author understands grief and how grieving people feel and think. The pain the FMC feels about losing her father feels so real to the reader. It made me ugly cry. But the book isn't all sad. It also shows how difficult it is to be vulnerable to another person as the FMC struggles with her feelings for the MMC. The characters are well developed and feel so real. On more than one occasion I felt the author put experiences and feelings into words that perfectly described my real life feelings better than I ever could. This book is an emotional ride but in a good way."" --Country girl (Amazon Reader)","""Amazing plot twist with betrayal and heartbreaking secrets coming to light, epic wars with cruel gods. Beautiful character development, found family and passionate romance in this fantastic and fast paced follow up to The Serpent and the Wings of Night. No doubt the best romantasy of 2023. Can't wait for the next instalment 💙"" --Mrs Maartensson (Amazon Reader)","""I would really like to give it 4.5star, it was not as amazing as the first book where every word counted. Every event mattered. In this book, I just felt the first 48% dragged on with FL being rather childish and ML really didn't take on his royal role. Having said that, the second 52% redeemed the book in my opinion. You really watch the characters grow from the first half the book while facing incredible odds."" --Nousheen H (Amazon Reader)","""The first book was great! I devoured it in a single day! The characters, the plot, the twists and turns, the ending… just great. The second book? Not so much. I couldn't get into it, but I will definitely give it time and try again soon! Carissa is a great author and I wanted to love it! 🫶"" --Caity (Amazon Reader)"
32 | 29,"""I absolutely loved this start of the series! The world is introduced: Yggrasil (The tree of life) and along its roots are five different realms with different magic and fae. The humans are slaves in all the realms and the mc is a special kind of slave in the Gold realm. Her kind can wield the magic of gold into staves so that the fae can use magic. One day she gets kidnapped by the shadow court and realizes the world is more than she thought, and filled with more terrors than she could've imagined. She is quickly thrown into a plot of deception and everywhere she goes someone is trying to kill her.
33 | I adored how the author combined the fae world with norse mythology; the names, the gods, the beliefs, Amazing! Can't wait to read the next one! 👏"" --Isabelle (Amazon Reader)","""It kept me on my toes the whole time I was reading this book it could not be put down I devoured it all in one day. Just found a new author that I deeply admire and I'm off to the next book"" --Kindle Customer","""Keeps you on your toes, interesting world, great characters, enjoyable read. High Fantasy at its best. Has some spice but relatable to the story and not overwhelming or taking over the story.
34 | Quick note for the writer, horses don't ""snicker"" they nicker. Could have been an editing typo, but really needs to be fixed."" --Buffalocolt27 (Amazon Reader)","""This is a really good, quick read. I'm certainly hooked and will finish the series but I feel like it could have been longer with a little more detail. It does seem very rushed.
35 | It's very much the “enemies to lovers,” “dark prince,” “fae and human,” “strong, stubborn fmc” trope(s) which is somewhat predictable but not bad. Think of Guild meets ACOTAR meets FBAA. The gold, the stubborn human falling for the enemy fae, the “chosen one.”
36 | I feel like ending on a cliffhanger is definitely utilized to get the reader to continue the next book to make up for how rushed everything else is. Overall, 4/5 and I will be reading on though slightly disappointed."" --Jimmie (Amazon Reader)","""All 4 books are quick reads. There were a few grammar errors, and a few confusing transitions throughout the series. The plot is interesting, but becomes tedious with all the secrets no one can expose. This series has the main FMC having an enemies to (only 1) lover, and there is at least 1 spice scene in each novel. The spice is rated one pepper out of 5. Having undead (or zombie like) creatures in a fae novel was a new one for me."" --Sound Judgement (Amazon Reader)"
37 | 45,"""You've likely heard the phrase “chew up the meat and spit out the bones”, in other words, take away the important or relevant bits and leave the rest that don't matter… this book is all meat.
38 | It's short bc it's poignant. Great practical advice and easy to implement."" --Delyn (Amazon Reader)","""Love this book because it doesn't have all the fluff no one cares about. It explains the issue of overstimulation and how you can combat it. There is even workbook pages in the back."" --Daniel Manz (Amazon Reader)","""I feel like this book touched on a lot of issues I experience personally, I didn't know that my experience was so similar to others who procrastinate. The steps in the book are very simple but effective, it's a great read for anyone having trouble doing the tough tasks, that we so often put off."" --Jason (Amazon Reader)","""Author sets up good habits and reasons why overstimulation in todays world is affecting our lives greater than what we can imagine. Author does a good job in raising our consciousness when it comes to social media or anything else involving overstimulation."" --Roy Saenz (Amazon Reader)","""A quick and useful guide to help live a more productive life. Reinforcing what we know about distractions and technology, and how to
39 | overcome its grip on our lives."" --Amanda Magro (Amazon Reader)"
40 | 46,"""I enjoyed this quick-read. It was more of an intro to a zen way of thinking, enlightenment. It seemed like a lot of the same words repeating, but nonetheless it was still interesting and an easy read. If you're looking for ways to stop overthinking or are getting into looking for zen, and peacefulness in your mind, this is a good book for you."" --Haley Jean (Amazon Reader)","""I truly felt like a weight was lifted off of my shoulders after reading this book. Simple and straightforward. To think life could be so simple. Just let go of your thinking and enjoy the present moment. I would recommend this to anyone who suffers from overthinking."" --Nefertima (Amazon Reader)","""I love that this author used easy to understand language to explain how our thoughts cause all of our problems! He did a great job using examples and providing steps to help you get on the journey to having a peaceful mind."" --Kindle Customer","""The book is full of valuable information, and the author's enthusiasm to share a path to greater happiness with his readers is clear. I've been trying the practice for three days now, and so far it works. I think I will take a few minutes each morning to go outside and just look/listen...no thinking! A quiet contentment arises when I just allow a ""first thought"" to hang there without commenting. Works with hard emotions too, if you have the guts to resist trying to talk yourself out of them.
41 |
42 | The writing isn't elegant, but that's beside the point. Also, the parts about the Universe might be a bit much for someone who hasn't yet investigated reality beyond materialism, but I found it to be enlightening. Thank you Joseph"" --""lparks0111"" (Amazon Reader)","""This is likely most suited to people who are more analytically-minded. For those on the more creative, artistic side - much of the book is nothing new. I can see that for some, it would be valuable - but for me it wasn't ""speaking my language""."" --D. Harrison (Amazon Reader)"
43 | 47,"""Thoughtful analysis and great exercises for letting go of the past. I highly recommend using this book whenever you feel drowned by regret."" --Yvonne Tran (Amazon Reader)","""If you're looking to turn the page on your past and move into a healthier state of mind for your future this is a great read. Lots of great tips and exercises to help you move forward from past behaviors that you want to shed."" --trefault (Amazon Reader)","""I've read quite a few books of this genre, but this is the first one I've found that explains how our emotions, once necessary for survival, can work against us, and how to reset thought patterns that are no longer in our best interest. There are numerous exercises, and many of them have examples, making it easy to get started. The book is comprehensive, but I'd love to meet the author and pick his brain even further."" --Kathryn Brooks (Amazon Reader)","""I really enjoyed this book and the lessons. I like that it gave us time frames to focus on the lesson, encouraging us to take our time and not rush through them. I also likes the examples as it helped push my thoughts into gear and to think of more things than I may have on my own. The quotes at the beginning of the chapters were excellent. I saved many of them.
44 | My only negative is some of the content was a little redundant in the chapters. It felt like a few sentences were just reworded to add length."" --William (Amazon Reader)","""This is the second or third book that I read from this author and I found it quite forgettable, just as his other ones. The information is always a personal view and conclusions from the author rather than a researched and backed analysis of the subject being presented. Every piece of advice or information can be derived from common sense with very little insight or novelty for someone with a slightly over average skill for overcoming negative situations. I can't imagine what kind of individual would benefit from this book other than the author himself. I don't recommend this nor other books by this author."" --Ignacio Zamora (Amazon Reader)"
45 |
--------------------------------------------------------------------------------
/examples/example_data/texts/titles.csv:
--------------------------------------------------------------------------------
1 | id,title
2 | 3,Please Tell Me
3 | 4,The Housemaid
4 | 8,The Ritual
5 | 9,The Inmate
6 | 21,The Serpent & The Wings of Night
7 | 23,The Ashes & The Star Cursed King
8 | 29,Court of Ravens and Ruin
9 | 45,Dopamine Detox
10 | 46,Don't Believe Everything You Think
11 | 47,The Art of Letting Go
12 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup(
4 | name="deeplogit",
5 | version="0.1.2",
6 | description="Mixed Logit Estimation with Text and Image Embeddings Extracted Using Deep Learning Models",
7 | url="https://github.com/deep-logit-demand/deeplogit",
8 | author="",
9 | author_email="",
10 | license="GPL-3.0",
11 | packages=["deeplogit"],
12 | install_requires=[
13 | "numpy",
14 | "xlogit",
15 | "pandas",
16 | "tensorflow",
17 | "tensorflow_hub",
18 | "torch",
19 | "sentence-transformers",
20 | "keras",
21 | "scikit-learn",
22 | "nltk",
23 | ],
24 | classifiers=[
25 | "Programming Language :: Python :: 3.9",
26 | ],
27 | )
28 |
--------------------------------------------------------------------------------