Full Code of dipanjanS/nlp_essentials for AI

master e4793b51aaba cached
8 files
599.1 KB
213.1k tokens
1 requests
Download .txt
Showing preview only (616K chars total). Download the full file or copy to clipboard to get everything.
Repository: dipanjanS/nlp_essentials
Branch: master
Commit: e4793b51aaba
Files: 8
Total size: 599.1 KB

Directory structure:
gitextract_ngxsk4bi/

├── .gitignore
├── LICENSE
├── README.md
└── notebooks/
    ├── 01_Text_Wrangling_Examples.ipynb
    ├── 02_Text_Representation_Statistical_Models.ipynb
    ├── 03_Text_Representation_Embedding_Models.ipynb
    ├── 04_NLP_Applications_Text_Similarity_Content_Recommenders.ipynb
    └── 05_NLP_Applications_Predicting_E_Commerce_Product_Recommendation_Ratings_from_Reviews_.ipynb

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# NLP Essentials

Essential and Fundametal aspects of Natural Language Processing with hands-on examples and case-studies


================================================
FILE: notebooks/01_Text_Wrangling_Examples.ipynb
================================================
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "accelerator": "GPU",
    "anaconda-cloud": {},
    "colab": {
      "name": "01 - Text Wrangling Examples.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.6"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "NtCf5TIaJpEr"
      },
      "source": [
        "# Install Dependencies"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ceSG71XiJoka",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 185
        },
        "outputId": "c1fa4f8d-9143-42bc-ef76-07166fc0710c"
      },
      "source": [
        "import nltk\n",
        "nltk.download('punkt')\n",
        "nltk.download('wordnet')\n",
        "nltk.download('stopwords')\n",
        "nltk.download('averaged_perceptron_tagger')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
            "[nltk_data]   Unzipping tokenizers/punkt.zip.\n",
            "[nltk_data] Downloading package wordnet to /root/nltk_data...\n",
            "[nltk_data]   Unzipping corpora/wordnet.zip.\n",
            "[nltk_data] Downloading package stopwords to /root/nltk_data...\n",
            "[nltk_data]   Unzipping corpora/stopwords.zip.\n",
            "[nltk_data] Downloading package averaged_perceptron_tagger to\n",
            "[nltk_data]     /root/nltk_data...\n",
            "[nltk_data]   Unzipping taggers/averaged_perceptron_tagger.zip.\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 1
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "AgeSwPsGJFWj"
      },
      "source": [
        "# Case Conversion"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "OQp382lJJFWp",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "199a9b30-a3ae-414b-def0-4166e17b7ab8"
      },
      "source": [
        "text = 'The quick brown fox jumped over The Big Dog'\n",
        "text"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The quick brown fox jumped over The Big Dog'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 2
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "FaAwb7HZJFWz",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "e2c4bc72-3743-4176-a42b-9720354716b8"
      },
      "source": [
        "text.lower()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'the quick brown fox jumped over the big dog'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ihX9LwVuJFW4",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "34f136ca-0ea5-4531-e206-2c981ae6d6e3"
      },
      "source": [
        "text.upper()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'THE QUICK BROWN FOX JUMPED OVER THE BIG DOG'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "U24TBZ82JFW8",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "e3fc2b71-b4f1-4ba4-93e9-7581c85d7566"
      },
      "source": [
        "text.title()"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The Quick Brown Fox Jumped Over The Big Dog'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "V3GzHq46JFW_"
      },
      "source": [
        "# Tokenization"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "zIiPr5JBJFXA",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 54
        },
        "outputId": "02958ece-7022-4a28-9591-d8caef757b87"
      },
      "source": [
        "sample_text = (\"US unveils world's most powerful supercomputer, beats China. \" \n",
        "               \"The US has unveiled the world's most powerful supercomputer called 'Summit', \" \n",
        "               \"beating the previous record-holder China's Sunway TaihuLight. With a peak performance \"\n",
        "               \"of 200,000 trillion calculations per second, it is over twice as fast as Sunway TaihuLight, \"\n",
        "               \"which is capable of 93,000 trillion calculations per second. Summit has 4,608 servers, \"\n",
        "               \"which reportedly take up the size of two tennis courts.\")\n",
        "sample_text"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "\"US unveils world's most powerful supercomputer, beats China. The US has unveiled the world's most powerful supercomputer called 'Summit', beating the previous record-holder China's Sunway TaihuLight. With a peak performance of 200,000 trillion calculations per second, it is over twice as fast as Sunway TaihuLight, which is capable of 93,000 trillion calculations per second. Summit has 4,608 servers, which reportedly take up the size of two tennis courts.\""
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "i2m8nEPmJFXD",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 84
        },
        "outputId": "83fe372f-8901-43d1-d6f5-fed5ee27cd91"
      },
      "source": [
        "import nltk\n",
        "\n",
        "nltk.sent_tokenize(sample_text)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[\"US unveils world's most powerful supercomputer, beats China.\",\n",
              " \"The US has unveiled the world's most powerful supercomputer called 'Summit', beating the previous record-holder China's Sunway TaihuLight.\",\n",
              " 'With a peak performance of 200,000 trillion calculations per second, it is over twice as fast as Sunway TaihuLight, which is capable of 93,000 trillion calculations per second.',\n",
              " 'Summit has 4,608 servers, which reportedly take up the size of two tennis courts.']"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "KjVNIwLoJFXG",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 54
        },
        "outputId": "093b33f0-6449-4fd0-c1ed-1dfc9bb6e318"
      },
      "source": [
        "print(nltk.word_tokenize(sample_text))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "['US', 'unveils', 'world', \"'s\", 'most', 'powerful', 'supercomputer', ',', 'beats', 'China', '.', 'The', 'US', 'has', 'unveiled', 'the', 'world', \"'s\", 'most', 'powerful', 'supercomputer', 'called', \"'Summit\", \"'\", ',', 'beating', 'the', 'previous', 'record-holder', 'China', \"'s\", 'Sunway', 'TaihuLight', '.', 'With', 'a', 'peak', 'performance', 'of', '200,000', 'trillion', 'calculations', 'per', 'second', ',', 'it', 'is', 'over', 'twice', 'as', 'fast', 'as', 'Sunway', 'TaihuLight', ',', 'which', 'is', 'capable', 'of', '93,000', 'trillion', 'calculations', 'per', 'second', '.', 'Summit', 'has', '4,608', 'servers', ',', 'which', 'reportedly', 'take', 'up', 'the', 'size', 'of', 'two', 'tennis', 'courts', '.']\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ZjhORAuPJFXL",
        "colab": {}
      },
      "source": [
        "import spacy\n",
        "nlp = spacy.load('en')\n",
        "\n",
        "text_spacy = nlp(sample_text)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "DR6LA_YHJFXN",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 84
        },
        "outputId": "630d9f19-8658-4b3b-bbd8-069fb3594601"
      },
      "source": [
        "[obj.text for obj in text_spacy.sents]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[\"US unveils world's most powerful supercomputer, beats China.\",\n",
              " \"The US has unveiled the world's most powerful supercomputer called 'Summit', beating the previous record-holder China's Sunway TaihuLight.\",\n",
              " 'With a peak performance of 200,000 trillion calculations per second, it is over twice as fast as Sunway TaihuLight, which is capable of 93,000 trillion calculations per second.',\n",
              " 'Summit has 4,608 servers, which reportedly take up the size of two tennis courts.']"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 10
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "DBuAHdR8JFXQ",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 54
        },
        "outputId": "f6acbbf6-e500-42c4-f06d-f1f8942ec548"
      },
      "source": [
        "print([obj.text for obj in text_spacy])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "['US', 'unveils', 'world', \"'s\", 'most', 'powerful', 'supercomputer', ',', 'beats', 'China', '.', 'The', 'US', 'has', 'unveiled', 'the', 'world', \"'s\", 'most', 'powerful', 'supercomputer', 'called', \"'\", 'Summit', \"'\", ',', 'beating', 'the', 'previous', 'record', '-', 'holder', 'China', \"'s\", 'Sunway', 'TaihuLight', '.', 'With', 'a', 'peak', 'performance', 'of', '200,000', 'trillion', 'calculations', 'per', 'second', ',', 'it', 'is', 'over', 'twice', 'as', 'fast', 'as', 'Sunway', 'TaihuLight', ',', 'which', 'is', 'capable', 'of', '93,000', 'trillion', 'calculations', 'per', 'second', '.', 'Summit', 'has', '4,608', 'servers', ',', 'which', 'reportedly', 'take', 'up', 'the', 'size', 'of', 'two', 'tennis', 'courts', '.']\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "fhxnJkIsJFXS"
      },
      "source": [
        "# Removing HTML tags & noise"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "E3qV1WOpJFXT",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 470
        },
        "outputId": "82fbdc9e-df22-410d-bd33-1096b34647e6"
      },
      "source": [
        "import requests\n",
        "\n",
        "data = requests.get('http://www.gutenberg.org/cache/epub/8001/pg8001.html')\n",
        "content = data.text\n",
        "print(content[2745:3948])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<p id=\"id00011\" style=\"margin-top: 2em\">*** START OF THE PROJECT GUTENBERG EBOOK, THE BIBLE, KING JAMES, BOOK 1***</p>\r\n",
            "\r\n",
            "<p id=\"id00012\" style=\"margin-top: 4em\">This eBook was produced by David Widger\r\n",
            "with the help of Derek Andrew's text from January 1992\r\n",
            "and the work of Bryan Taylor in November 2002.</p>\r\n",
            "\r\n",
            "<h1 id=\"id00013\" style=\"margin-top: 5em\">Book 01        Genesis</h1>\r\n",
            "\r\n",
            "<p id=\"id00014\">01:001:001 In the beginning God created the heaven and the earth.</p>\r\n",
            "\r\n",
            "<p id=\"id00015\" style=\"margin-left: 0%; margin-right: 0%\">01:001:002 And the earth was without form, and void; and darkness was\r\n",
            "           upon the face of the deep. And the Spirit of God moved upon\r\n",
            "           the face of the waters.</p>\r\n",
            "\r\n",
            "<p id=\"id00016\">01:001:003 And God said, Let there be light: and there was light.</p>\r\n",
            "\r\n",
            "<p id=\"id00017\">01:001:004 And God saw the light, that it was good: and God divided the<br/>\r\n",
            "\r\n",
            "           light from the darkness.<br/>\r\n",
            "</p>\r\n",
            "\r\n",
            "<p id=\"id00018\">01:001:005 And God called the light Day, and the darkness he called<br/>\r\n",
            "\r\n",
            "           Night. And the evening and the morning were the first day.<br/>\r\n",
            "</p>\r\n",
            "\r\n",
            "<p id=\"id00019\">01:001:006 And God said, Let there be a firmament in the mi\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "E6UAz3mjJFXY",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 269
        },
        "outputId": "0549c5a6-1814-4e82-8046-d32b40647d1f"
      },
      "source": [
        "import re\n",
        "from bs4 import BeautifulSoup\n",
        "\n",
        "def strip_html_tags(text):\n",
        "    soup = BeautifulSoup(text, \"html.parser\")\n",
        "    [s.extract() for s in soup(['iframe', 'script'])]\n",
        "    stripped_text = soup.get_text()\n",
        "    stripped_text = re.sub(r'[\\r|\\n|\\r\\n]+', '\\n', stripped_text)\n",
        "    return stripped_text\n",
        "\n",
        "clean_content = strip_html_tags(content)\n",
        "print(clean_content[1163:1957])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "*** START OF THE PROJECT GUTENBERG EBOOK, THE BIBLE, KING JAMES, BOOK 1***\n",
            "This eBook was produced by David Widger\n",
            "with the help of Derek Andrew's text from January 1992\n",
            "and the work of Bryan Taylor in November 2002.\n",
            "Book 01        Genesis\n",
            "01:001:001 In the beginning God created the heaven and the earth.\n",
            "01:001:002 And the earth was without form, and void; and darkness was\n",
            "           upon the face of the deep. And the Spirit of God moved upon\n",
            "           the face of the waters.\n",
            "01:001:003 And God said, Let there be light: and there was light.\n",
            "01:001:004 And God saw the light, that it was good: and God divided the\n",
            "           light from the darkness.\n",
            "01:001:005 And God called the light Day, and the darkness he called\n",
            "           Night. And the evening and the morning were the first day.\n",
            "\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "9fJi5YyKJFXc"
      },
      "source": [
        "# Removing Accented Characters"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Ps9wmhv9JFXd",
        "colab": {}
      },
      "source": [
        "import unicodedata\n",
        "\n",
        "def remove_accented_chars(text):\n",
        "    text = unicodedata.normalize('NFKD', text).encode('ascii', 'ignore').decode('utf-8', 'ignore')\n",
        "    return text"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Mc7JR8CQJFXh",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "392b46f9-4945-47e0-b942-9d50de2fb3ff"
      },
      "source": [
        "s = 'Sómě Áccěntěd těxt'\n",
        "s"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Sómě Áccěntěd těxt'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "I6a-e-mVJFXm",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "9073d7d9-198f-4c5c-9de9-2539cda1adcd"
      },
      "source": [
        "remove_accented_chars(s)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Some Accented text'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 16
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "gj8CyGmPJFXr"
      },
      "source": [
        "# Removing Special Characters, Numbers and Symbols"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "1dkc4ESDJFXs",
        "colab": {}
      },
      "source": [
        "import re\n",
        "\n",
        "def remove_special_characters(text, remove_digits=False):\n",
        "    pattern = r'[^a-zA-Z0-9\\s]' if not remove_digits else r'[^a-zA-Z\\s]'\n",
        "    text = re.sub(pattern, '', text)\n",
        "    return text\n"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "XUwKvQ-1JFXx",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "deb1477f-9de1-44fc-801b-f80d0930624f"
      },
      "source": [
        "s = \"Well this was fun! See you at 7:30, What do you think!!? #$@@9318@ 🙂🙂🙂\"\n",
        "s"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Well this was fun! See you at 7:30, What do you think!!? #$@@9318@ 🙂🙂🙂'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 18
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Sy9x4XFyJFYL",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "01596e65-1935-4095-b91a-1cd14da1ef48"
      },
      "source": [
        "remove_special_characters(s, remove_digits=True)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Well this was fun See you at  What do you think  '"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "s2vT0GK5JFYQ",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "e8763d3d-6f64-4308-f39d-8487a97ffcf2"
      },
      "source": [
        "remove_special_characters(s)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'Well this was fun See you at 730 What do you think 9318 '"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 20
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "ho6h68QbJFYX"
      },
      "source": [
        "# Expanding Contractions"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "mgGTT1URJFYY",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 353
        },
        "outputId": "2aa9f59a-9d7a-4436-9f90-0ba12a1b6016"
      },
      "source": [
        "!pip install contractions\n",
        "!pip install textsearch"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Collecting contractions\n",
            "  Downloading https://files.pythonhosted.org/packages/85/41/c3dfd5feb91a8d587ed1a59f553f07c05f95ad4e5d00ab78702fbf8fe48a/contractions-0.0.24-py2.py3-none-any.whl\n",
            "Collecting textsearch\n",
            "  Downloading https://files.pythonhosted.org/packages/42/a8/03407021f9555043de5492a2bd7a35c56cc03c2510092b5ec018cae1bbf1/textsearch-0.0.17-py2.py3-none-any.whl\n",
            "Collecting pyahocorasick\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/f4/9f/f0d8e8850e12829eea2e778f1c90e3c53a9a799b7f412082a5d21cd19ae1/pyahocorasick-1.4.0.tar.gz (312kB)\n",
            "\u001b[K     |████████████████████████████████| 317kB 3.8MB/s \n",
            "\u001b[?25hCollecting Unidecode\n",
            "\u001b[?25l  Downloading https://files.pythonhosted.org/packages/d0/42/d9edfed04228bacea2d824904cae367ee9efd05e6cce7ceaaedd0b0ad964/Unidecode-1.1.1-py2.py3-none-any.whl (238kB)\n",
            "\u001b[K     |████████████████████████████████| 245kB 15.6MB/s \n",
            "\u001b[?25hBuilding wheels for collected packages: pyahocorasick\n",
            "  Building wheel for pyahocorasick (setup.py) ... \u001b[?25l\u001b[?25hdone\n",
            "  Created wheel for pyahocorasick: filename=pyahocorasick-1.4.0-cp36-cp36m-linux_x86_64.whl size=81699 sha256=b766a035314d66115551991c1220d24c4a42480cc3e1f4b7ae56a50ba5e9f62a\n",
            "  Stored in directory: /root/.cache/pip/wheels/0a/90/61/87a55f5b459792fbb2b7ba6b31721b06ff5cf6bde541b40994\n",
            "Successfully built pyahocorasick\n",
            "Installing collected packages: pyahocorasick, Unidecode, textsearch, contractions\n",
            "Successfully installed Unidecode-1.1.1 contractions-0.0.24 pyahocorasick-1.4.0 textsearch-0.0.17\n",
            "Requirement already satisfied: textsearch in /usr/local/lib/python3.6/dist-packages (0.0.17)\n",
            "Requirement already satisfied: Unidecode in /usr/local/lib/python3.6/dist-packages (from textsearch) (1.1.1)\n",
            "Requirement already satisfied: pyahocorasick in /usr/local/lib/python3.6/dist-packages (from textsearch) (1.4.0)\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "5xWsgO-jJFYc",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "b02a9709-8e7e-4174-d46c-769d73aeadda"
      },
      "source": [
        "s = \"Y'all can't expand contractions I'd think! You wouldn't be able to. How'd you do it?\"\n",
        "s"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "\"Y'all can't expand contractions I'd think! You wouldn't be able to. How'd you do it?\""
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 22
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "S2QTF2HFJFYi",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 185
        },
        "outputId": "d01e87fb-cc90-4f97-e01c-f8a76d2e1c60"
      },
      "source": [
        "import contractions\n",
        "\n",
        "list(contractions.contractions_dict.items())[:10]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[(\"ain't\", 'are not'),\n",
              " (\"aren't\", 'are not'),\n",
              " (\"can't\", 'can not'),\n",
              " (\"can't've\", 'can not have'),\n",
              " (\"'cause\", 'because'),\n",
              " (\"could've\", 'could have'),\n",
              " (\"couldn't\", 'could not'),\n",
              " (\"couldn't've\", 'could not have'),\n",
              " (\"didn't\", 'did not'),\n",
              " (\"doesn't\", 'does not')]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "KoIGJXqCJFYo",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "1cae6a7b-d520-46eb-ce81-ec50089f7ab3"
      },
      "source": [
        "contractions.fix(s)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'you all can not expand contractions I would think! You would not be able to. how did you do it?'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 24
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "EeUHPmhDJFZC"
      },
      "source": [
        "# Stemming"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "8ndJ4XOKJFZD",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "fb53058e-bbdf-489b-f57d-fbdb7e7395c7"
      },
      "source": [
        "# Porter Stemmer\n",
        "from nltk.stem import PorterStemmer\n",
        "ps = PorterStemmer()\n",
        "\n",
        "ps.stem('jumping'), ps.stem('jumps'), ps.stem('jumped')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "('jump', 'jump', 'jump')"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 25
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "CmWLISH-JFZG",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "4e8dcb51-121a-4f3b-8522-a7db0cf81357"
      },
      "source": [
        "ps.stem('lying')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'lie'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 26
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Q7KRj1jtJFZJ",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "a1944d27-3e35-4a4e-dc10-41f0b15384bc"
      },
      "source": [
        "ps.stem('strange')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'strang'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 27
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "cQNUmpfLJFZu"
      },
      "source": [
        "# Lemmatization"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "16ygP7t1JFZv",
        "colab": {}
      },
      "source": [
        "from nltk.stem import WordNetLemmatizer\n",
        "wnl = WordNetLemmatizer()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "AieUIjYaJFZ3",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 84
        },
        "outputId": "09dc4df1-9ff9-48d4-f11a-cf63cbf6f3d9"
      },
      "source": [
        "help(wnl.lemmatize)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Help on method lemmatize in module nltk.stem.wordnet:\n",
            "\n",
            "lemmatize(word, pos='n') method of nltk.stem.wordnet.WordNetLemmatizer instance\n",
            "\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "_ZPcwz44JFZ7",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 50
        },
        "outputId": "c0b18e8d-d034-4241-fac2-53ff4ef56d1c"
      },
      "source": [
        "# lemmatize nouns\n",
        "print(wnl.lemmatize('cars', 'n'))\n",
        "print(wnl.lemmatize('boxes', 'n'))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "car\n",
            "box\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "KJN-uQ28JFZ_",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 50
        },
        "outputId": "49826ee7-990d-44ee-c0d2-09b58e10fdb4"
      },
      "source": [
        "# lemmatize verbs\n",
        "print(wnl.lemmatize('running', 'v'))\n",
        "print(wnl.lemmatize('ate', 'v'))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "run\n",
            "eat\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "L0u5uZeoJFaF",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 50
        },
        "outputId": "f7cc036f-5b61-4b0d-9ed2-7af8391851b9"
      },
      "source": [
        "# lemmatize adjectives\n",
        "print(wnl.lemmatize('saddest', 'a'))\n",
        "print(wnl.lemmatize('fancier', 'a'))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "sad\n",
            "fancy\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "NhKXkdckJFaN",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 67
        },
        "outputId": "cd37a4a9-c4b2-48a5-a486-869ad8b8fea1"
      },
      "source": [
        "# ineffective lemmatization\n",
        "print(wnl.lemmatize('ate', 'n'))\n",
        "print(wnl.lemmatize('fancier', 'v'))\n",
        "print(wnl.lemmatize('fancier'))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "ate\n",
            "fancier\n",
            "fancier\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Z4g85bOGJFaQ",
        "colab": {}
      },
      "source": [
        "s = 'The brown foxes are quick and they are jumping over the sleeping lazy dogs!'"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NQ1S2ngz7B84",
        "colab_type": "text"
      },
      "source": [
        "### Tokenize"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "0l372SiEJFaU",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "cd2a469c-26ed-4d06-cce1-91b6e29650af"
      },
      "source": [
        "tokens = nltk.word_tokenize(s)\n",
        "print(tokens)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "['The', 'brown', 'foxes', 'are', 'quick', 'and', 'they', 'are', 'jumping', 'over', 'the', 'sleeping', 'lazy', 'dogs', '!']\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "s1FHAghFJFaX",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "765ad93e-2a6a-4666-c649-3c529d8cdf95"
      },
      "source": [
        "lemmatized_text = ' '.join(wnl.lemmatize(token) for token in tokens)\n",
        "lemmatized_text"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The brown fox are quick and they are jumping over the sleeping lazy dog !'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 44
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "d0-fgmbi7E5_",
        "colab_type": "text"
      },
      "source": [
        "### POS Tagging"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "UDffFU3gJFaZ",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 54
        },
        "outputId": "fcfbd8a2-dc38-4578-c479-b4672b58cde3"
      },
      "source": [
        "tagged_tokens = nltk.pos_tag(tokens)\n",
        "print(tagged_tokens)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[('The', 'DT'), ('brown', 'JJ'), ('foxes', 'NNS'), ('are', 'VBP'), ('quick', 'JJ'), ('and', 'CC'), ('they', 'PRP'), ('are', 'VBP'), ('jumping', 'VBG'), ('over', 'IN'), ('the', 'DT'), ('sleeping', 'VBG'), ('lazy', 'JJ'), ('dogs', 'NNS'), ('!', '.')]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9STnRHVt7HRG",
        "colab_type": "text"
      },
      "source": [
        "### Tag conversion to WordNet Tags"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "2S9kS_xPJFaf",
        "colab": {}
      },
      "source": [
        "from nltk.corpus import wordnet\n",
        "\n",
        "def pos_tag_wordnet(tagged_tokens):\n",
        "    tag_map = {'j': wordnet.ADJ, 'v': wordnet.VERB, 'n': wordnet.NOUN, 'r': wordnet.ADV}\n",
        "    new_tagged_tokens = [(word, tag_map.get(tag[0].lower(), wordnet.NOUN))\n",
        "                            for word, tag in tagged_tokens]\n",
        "    return new_tagged_tokens"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "TbijTK6YJFaj",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 54
        },
        "outputId": "c97e38b3-8b0f-43ee-848b-bbbf9449ebfb"
      },
      "source": [
        "wordnet_tokens = pos_tag_wordnet(tagged_tokens)\n",
        "print(wordnet_tokens)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[('The', 'n'), ('brown', 'a'), ('foxes', 'n'), ('are', 'v'), ('quick', 'a'), ('and', 'n'), ('they', 'n'), ('are', 'v'), ('jumping', 'v'), ('over', 'n'), ('the', 'n'), ('sleeping', 'v'), ('lazy', 'a'), ('dogs', 'n'), ('!', 'n')]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qKia_-ov7KLH",
        "colab_type": "text"
      },
      "source": [
        "### Effective Lemmatization"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "tNOpTLDTJFal",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "575e08b1-a48d-40a8-abde-363fd671fa93"
      },
      "source": [
        "lemmatized_text = ' '.join(wnl.lemmatize(word, tag) for word, tag in wordnet_tokens)\n",
        "lemmatized_text"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The brown fox be quick and they be jump over the sleep lazy dog !'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 50
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "9zisZIs1JFan"
      },
      "source": [
        "### Your turn: Define a function such that you put all the above steps together so that it does the following\n",
        "\n",
        "- Function name is __`wordnet_lemmatize_text(...)`__\n",
        "- Input is a variable __`text`__ which should take in a document (bunch of words)\n",
        "- Call the earlier defined functions and utilize them\n",
        "- Return lemmatized text as the output (as a string)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "I6LditBNJFao",
        "colab": {}
      },
      "source": [
        "wnl = WordNetLemmatizer()\n",
        "\n",
        "def wordnet_lemmatize_text(text):\n",
        "    tagged_tokens = nltk.pos_tag(nltk.word_tokenize(text))\n",
        "    wordnet_tokens = pos_tag_wordnet(tagged_tokens)\n",
        "    lemmatized_text = ' '.join(wnl.lemmatize(word, tag) for word, tag in wordnet_tokens)\n",
        "    return lemmatized_text"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "UWQeSVxGJFap"
      },
      "source": [
        "### Your Turn: Now call the function on the below sentence and test it"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "FUvJQk-eJFaq",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "41276cb8-3c6e-4382-9f25-2516899052e2"
      },
      "source": [
        "s"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The brown foxes are quick and they are jumping over the sleeping lazy dogs!'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 52
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "7xE0WwbJJFas",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "638b66b3-02b5-41ff-ec4e-6a2deff153d9"
      },
      "source": [
        "wordnet_lemmatize_text(s)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The brown fox be quick and they be jump over the sleep lazy dog !'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 53
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "KgQJp2SH7OC_",
        "colab_type": "text"
      },
      "source": [
        "## Lemmatization with Spacy"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "3N2ExlFqJFaw",
        "colab": {}
      },
      "source": [
        "import spacy\n",
        "nlp = spacy.load('en', parse=False, tag=False, entity=False)\n",
        "\n",
        "def spacy_lemmatize_text(text):\n",
        "    text = nlp(text)\n",
        "    text = ' '.join([word.lemma_ if word.lemma_ != '-PRON-' else word.text for word in text])\n",
        "    return text"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ga-E47JKJFaz",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "76333567-ae35-46ee-fdf9-260b3926cc31"
      },
      "source": [
        "s"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The brown foxes are quick and they are jumping over the sleeping lazy dogs!'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 55
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "Bb-PrIeqJFa5",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "b5b00364-7d85-4240-cf55-21f8fef8fa5d"
      },
      "source": [
        "spacy_lemmatize_text(s)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'the brown fox be quick and they be jump over the sleep lazy dog !'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 56
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "aQsKAXlvJFa7"
      },
      "source": [
        "# Stopword Removal"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "VkJLKKxrJFa7",
        "colab": {}
      },
      "source": [
        "def remove_stopwords(text, is_lower_case=False, stopwords=None):\n",
        "    if not stopwords:\n",
        "        stopwords = nltk.corpus.stopwords.words('english')\n",
        "    tokens = nltk.word_tokenize(text)\n",
        "    tokens = [token.strip() for token in tokens]\n",
        "    \n",
        "    if is_lower_case:\n",
        "        filtered_tokens = [token for token in tokens if token not in stopwords]\n",
        "    else:\n",
        "        filtered_tokens = [token for token in tokens if token.lower() not in stopwords]\n",
        "    \n",
        "    filtered_text = ' '.join(filtered_tokens)    \n",
        "    return filtered_text"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "veJLEhzKJFa-",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "3272c105-0664-4349-8f42-637cadd56727"
      },
      "source": [
        "stop_words = nltk.corpus.stopwords.words('english')\n",
        "print(stop_words[:10])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', \"you're\"]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "ycusSsPBJFbA",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "186389a0-7131-45eb-a876-6dde01d91fe9"
      },
      "source": [
        "s"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The brown foxes are quick and they are jumping over the sleeping lazy dogs!'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 59
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "oWKjTPnzJFbD",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "16fe7d8e-8248-4415-9ec8-902bd718295c"
      },
      "source": [
        "remove_stopwords(s, is_lower_case=False)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'brown foxes quick jumping sleeping lazy dogs !'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 60
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "4bcnWSnAJFbG"
      },
      "source": [
        "### Your turn: Remove the words 'the' and 'brown' from the stop_words list and call the function with this new list"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "rPAM2rNZJFbH",
        "colab": {}
      },
      "source": [
        "stop_words.remove('the')\n",
        "stop_words.append('brown')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "qk2Y-nbZJFbJ",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "a433ccad-6e6a-4671-b4b7-9723f45153af"
      },
      "source": [
        "remove_stopwords(s, is_lower_case=False, stopwords=stop_words)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'The foxes quick jumping the sleeping lazy dogs !'"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 62
        }
      ]
    }
  ]
}

================================================
FILE: notebooks/02_Text_Representation_Statistical_Models.ipynb
================================================
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "02-Text Representation - Statistical Models.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.6"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "-dWlnZ1vRP6H"
      },
      "source": [
        "# Text Representation with Feature Engineering\n",
        "\n",
        "### Exploring Traditional Statistical Models\n",
        "\n",
        "Feature Engineering is often known as the secret sauce to creating superior and better performing machine learning models. Just one excellent feature could be your ticket to winning a Kaggle challenge! The importance of feature engineering is even more important for unstructured, textual data because we need to convert free flowing text into some numeric representations which can then be understood by machine learning algorithms. \n",
        "\n",
        "Here we will explore the following feature engineering techniques:\n",
        "\n",
        "- Bag of Words Model (TF)\n",
        "- Bag of N-grams Model\n",
        "- TF-IDF Model\n",
        "- Similarity Features"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "NYC_RfbeRP6J"
      },
      "source": [
        "# Prepare a Sample Corpus\n",
        "\n",
        "Let’s now take a sample corpus of documents on which we will run most of our analyses in this article. A corpus is typically a collection of text documents usually belonging to one or more subjects or domains."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "6xn8eDqARP6J",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 284
        },
        "outputId": "8ee06c2b-ddf7-4e5a-a23c-9b8038d3d9b2"
      },
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "\n",
        "pd.options.display.max_colwidth = 200\n",
        "\n",
        "corpus = ['The sky is blue and beautiful.',\n",
        "          'Love this blue and beautiful sky!',\n",
        "          'The quick brown fox jumps over the lazy dog.',\n",
        "          \"A king's breakfast has sausages, ham, bacon, eggs, toast and beans\",\n",
        "          'I love green eggs, ham, sausages and bacon!',\n",
        "          'The brown fox is quick and the blue dog is lazy!',\n",
        "          'The sky is very blue and the sky is very beautiful today',\n",
        "          'The dog is lazy but the brown fox is quick!'    \n",
        "]\n",
        "labels = ['weather', 'weather', 'animals', 'food', 'food', 'animals', 'weather', 'animals']\n",
        "\n",
        "corpus = np.array(corpus)\n",
        "corpus_df = pd.DataFrame({'Document': corpus, \n",
        "                          'Category': labels})\n",
        "corpus_df = corpus_df[['Document', 'Category']]\n",
        "corpus_df"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>Document</th>\n",
              "      <th>Category</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>The sky is blue and beautiful.</td>\n",
              "      <td>weather</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Love this blue and beautiful sky!</td>\n",
              "      <td>weather</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>The quick brown fox jumps over the lazy dog.</td>\n",
              "      <td>animals</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>A king's breakfast has sausages, ham, bacon, eggs, toast and beans</td>\n",
              "      <td>food</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>I love green eggs, ham, sausages and bacon!</td>\n",
              "      <td>food</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>The brown fox is quick and the blue dog is lazy!</td>\n",
              "      <td>animals</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>The sky is very blue and the sky is very beautiful today</td>\n",
              "      <td>weather</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>The dog is lazy but the brown fox is quick!</td>\n",
              "      <td>animals</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "                                                             Document Category\n",
              "0                                      The sky is blue and beautiful.  weather\n",
              "1                                   Love this blue and beautiful sky!  weather\n",
              "2                        The quick brown fox jumps over the lazy dog.  animals\n",
              "3  A king's breakfast has sausages, ham, bacon, eggs, toast and beans     food\n",
              "4                         I love green eggs, ham, sausages and bacon!     food\n",
              "5                    The brown fox is quick and the blue dog is lazy!  animals\n",
              "6            The sky is very blue and the sky is very beautiful today  weather\n",
              "7                         The dog is lazy but the brown fox is quick!  animals"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 1
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "QOMGTkvCRP6N"
      },
      "source": [
        "You can see that we have taken a few sample text documents belonging to different categories for our toy corpus. Before we talk about feature engineering, as always, we need to do some data pre-processing or wrangling to remove unnecessary characters, symbols and tokens."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "nAcT9NHkRP6O"
      },
      "source": [
        "# Simple Text Pre-processing\n",
        "\n",
        "Since the focus of this unit is on feature engineering, we will build a simple text pre-processor which focuses on removing special characters, extra whitespaces, digits, stopwords and lower casing the text corpus."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "vSIxl_PUSCvj",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 101
        },
        "outputId": "6477f365-d714-461e-bac4-cf4bc17705f5"
      },
      "source": [
        "import nltk\n",
        "nltk.download('stopwords')\n",
        "nltk.download('punkt')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[nltk_data] Downloading package stopwords to /root/nltk_data...\n",
            "[nltk_data]   Unzipping corpora/stopwords.zip.\n",
            "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
            "[nltk_data]   Unzipping tokenizers/punkt.zip.\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 2
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "OElcyG9WRP6P",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 118
        },
        "outputId": "fcfae9fa-349d-4e77-9f75-e5f241dfe5d9"
      },
      "source": [
        "import nltk\n",
        "import re\n",
        "\n",
        "stop_words = nltk.corpus.stopwords.words('english')\n",
        "\n",
        "def normalize_document(doc):\n",
        "    # lower case and remove special characters\\whitespaces\n",
        "    doc = re.sub(r'[^a-zA-Z\\s]', '', doc, re.I|re.A)\n",
        "    doc = doc.lower()\n",
        "    doc = doc.strip()\n",
        "    # tokenize document\n",
        "    tokens = nltk.word_tokenize(doc)\n",
        "    # filter stopwords out of document\n",
        "    filtered_tokens = [token for token in tokens if token not in stop_words]\n",
        "    # re-create document from filtered tokens\n",
        "    doc = ' '.join(filtered_tokens)\n",
        "    return doc\n",
        "\n",
        "normalize_corpus = np.vectorize(normalize_document)\n",
        "\n",
        "norm_corpus = normalize_corpus(corpus)\n",
        "norm_corpus"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array(['sky blue beautiful', 'love blue beautiful sky',\n",
              "       'quick brown fox jumps lazy dog',\n",
              "       'kings breakfast sausages ham bacon eggs toast beans',\n",
              "       'love green eggs ham sausages bacon',\n",
              "       'brown fox quick blue dog lazy', 'sky blue sky beautiful today',\n",
              "       'dog lazy brown fox quick'], dtype='<U51')"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "MMBWGlKTRP6T"
      },
      "source": [
        "# Bag of Words Model - TF\n",
        "\n",
        "This is perhaps the most simple vector space representational model for unstructured text. A vector space model is simply a mathematical model to represent unstructured text (or any other data) as numeric vectors, such that each dimension of the vector is a specific feature\\attribute. The bag of words model represents each text document as a numeric vector where each dimension is a specific word from the corpus and the value could be its frequency in the document, occurrence (denoted by 1 or 0) or even weighted values. The model’s name is such because each document is represented literally as a ‘bag’ of its own words, disregarding word orders, sequences and grammar."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "d7mAqxTlRP6U",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 151
        },
        "outputId": "f771b092-0d12-48c5-9182-5beb92643376"
      },
      "source": [
        "from sklearn.feature_extraction.text import CountVectorizer\n",
        "\n",
        "cv = CountVectorizer(min_df=0., max_df=1.)\n",
        "cv_matrix = cv.fit_transform(norm_corpus)\n",
        "cv_matrix = cv_matrix.toarray()\n",
        "cv_matrix"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0],\n",
              "       [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],\n",
              "       [0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0],\n",
              "       [1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0],\n",
              "       [1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n",
              "       [0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0],\n",
              "       [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1],\n",
              "       [0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0]])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "lPp6Bzs7RP6W"
      },
      "source": [
        "Thus you can see that our documents have been converted into numeric vectors such that each document is represented by one vector (row) in the above feature matrix. The following code will help represent this in a more easy to understand format."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "FVsdSiwARP6W",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 284
        },
        "outputId": "03bf4798-1714-41d8-fc3c-6a93d003c393"
      },
      "source": [
        "# get all unique words in the corpus\n",
        "vocab = cv.get_feature_names()\n",
        "# show document feature vectors\n",
        "pd.DataFrame(cv_matrix, columns=vocab)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>bacon</th>\n",
              "      <th>beans</th>\n",
              "      <th>beautiful</th>\n",
              "      <th>blue</th>\n",
              "      <th>breakfast</th>\n",
              "      <th>brown</th>\n",
              "      <th>dog</th>\n",
              "      <th>eggs</th>\n",
              "      <th>fox</th>\n",
              "      <th>green</th>\n",
              "      <th>ham</th>\n",
              "      <th>jumps</th>\n",
              "      <th>kings</th>\n",
              "      <th>lazy</th>\n",
              "      <th>love</th>\n",
              "      <th>quick</th>\n",
              "      <th>sausages</th>\n",
              "      <th>sky</th>\n",
              "      <th>toast</th>\n",
              "      <th>today</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>2</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   bacon  beans  beautiful  blue  breakfast  ...  quick  sausages  sky  toast  today\n",
              "0      0      0          1     1          0  ...      0         0    1      0      0\n",
              "1      0      0          1     1          0  ...      0         0    1      0      0\n",
              "2      0      0          0     0          0  ...      1         0    0      0      0\n",
              "3      1      1          0     0          1  ...      0         1    0      1      0\n",
              "4      1      0          0     0          0  ...      0         1    0      0      0\n",
              "5      0      0          0     1          0  ...      1         0    0      0      0\n",
              "6      0      0          1     1          0  ...      0         0    2      0      1\n",
              "7      0      0          0     0          0  ...      1         0    0      0      0\n",
              "\n",
              "[8 rows x 20 columns]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "A_1k60ZERP6Z"
      },
      "source": [
        "This should make things more clearer! You can clearly see that each column or dimension in the feature vectors represents a word from the corpus and each row represents one of our documents. The value in any cell, represents the number of times that word (represented by column) occurs in the specific document (represented by row). Hence if a corpus of documents consists of N unique words across all the documents, we would have an N-dimensional vector for each of the documents."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0DfPJwSsRP6Z"
      },
      "source": [
        "# Bag of N-Grams Model\n",
        "\n",
        "A word is just a single token, often known as a unigram or 1-gram. We already know that the Bag of Words model doesn’t consider order of words. But what if we also wanted to take into account phrases or collection of words which occur in a sequence? N-grams help us achieve that. An N-gram is basically a collection of word tokens from a text document such that these tokens are contiguous and occur in a sequence. Bi-grams indicate n-grams of order 2 (two words), Tri-grams indicate n-grams of order 3 (three words), and so on. The Bag of N-Grams model is hence just an extension of the Bag of Words model so we can also leverage N-gram based features. The following example depicts bi-gram based features in each document feature vector."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "4n1N32JyRP6a",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 321
        },
        "outputId": "5c091718-a76c-448c-add9-311f32486230"
      },
      "source": [
        "# you can set the n-gram range to 1,2 to get unigrams as well as bigrams\n",
        "bv = CountVectorizer(ngram_range=(2,2))\n",
        "bv_matrix = bv.fit_transform(norm_corpus)\n",
        "\n",
        "bv_matrix = bv_matrix.toarray()\n",
        "vocab = bv.get_feature_names()\n",
        "pd.DataFrame(bv_matrix, columns=vocab)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>bacon eggs</th>\n",
              "      <th>beautiful sky</th>\n",
              "      <th>beautiful today</th>\n",
              "      <th>blue beautiful</th>\n",
              "      <th>blue dog</th>\n",
              "      <th>blue sky</th>\n",
              "      <th>breakfast sausages</th>\n",
              "      <th>brown fox</th>\n",
              "      <th>dog lazy</th>\n",
              "      <th>eggs ham</th>\n",
              "      <th>eggs toast</th>\n",
              "      <th>fox jumps</th>\n",
              "      <th>fox quick</th>\n",
              "      <th>green eggs</th>\n",
              "      <th>ham bacon</th>\n",
              "      <th>ham sausages</th>\n",
              "      <th>jumps lazy</th>\n",
              "      <th>kings breakfast</th>\n",
              "      <th>lazy brown</th>\n",
              "      <th>lazy dog</th>\n",
              "      <th>love blue</th>\n",
              "      <th>love green</th>\n",
              "      <th>quick blue</th>\n",
              "      <th>quick brown</th>\n",
              "      <th>sausages bacon</th>\n",
              "      <th>sausages ham</th>\n",
              "      <th>sky beautiful</th>\n",
              "      <th>sky blue</th>\n",
              "      <th>toast beans</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>1</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   bacon eggs  beautiful sky  ...  sky blue  toast beans\n",
              "0           0              0  ...         1            0\n",
              "1           0              1  ...         0            0\n",
              "2           0              0  ...         0            0\n",
              "3           1              0  ...         0            1\n",
              "4           0              0  ...         0            0\n",
              "5           0              0  ...         0            0\n",
              "6           0              0  ...         1            0\n",
              "7           0              0  ...         0            0\n",
              "\n",
              "[8 rows x 29 columns]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "bW6F4h8QRP6c"
      },
      "source": [
        "This gives us feature vectors for our documents, where each feature consists of a bi-gram representing a sequence of two words and values represent how many times the bi-gram was present for our documents."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "pPwKOnnkRP6d"
      },
      "source": [
        "# TF-IDF Model\n",
        "\n",
        "There are some potential problems which might arise with the Bag of Words model when it is used on large corpora. Since the feature vectors are based on absolute term frequencies, there might be some terms which occur frequently across all documents and these may tend to overshadow other terms in the feature set. The TF-IDF model tries to combat this issue by using a scaling or normalizing factor in its computation. ___TF-IDF___ stands for __Term Frequency-Inverse Document Frequency__, which uses a combination of two metrics in its computation, namely: ___term frequency (tf)___ and ___inverse document frequency (idf)___. This technique was developed for ranking results for queries in search engines and now it is an indispensable model in the world of information retrieval and NLP.\n",
        "\n",
        "Mathematically, we can define TF-IDF as ___tfidf = tf x idf___, which can be expanded further to be represented as follows.\n",
        "\n",
        "![](https://github.com/dipanjanS/nlp_workshop_odsc19/blob/master/Module04%20-%20Text%20Representation/tfidf_eq.png?raw=1)\n",
        "\n",
        "Here, ___tfidf(w, D)___ is the TF-IDF score for word __w__ in document __D__. \n",
        "- The term ___tf(w, D)___ represents the term frequency of the word __w__ in document __D__, which can be obtained from the Bag of Words model. \n",
        "- The term ___idf(w, D)___ is the inverse document frequency for the term __w__, which can be computed as the log transform of the total number of documents in the corpus __C__ divided by the document frequency of the word __w__, which is basically the frequency of documents in the corpus where the word __w__ occurs. \n",
        "\n",
        "There are multiple variants of this model but they all end up giving quite similar results. Let’s apply this on our corpus now!"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "sFp9zDbgRP6d",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 284
        },
        "outputId": "009f142f-1b99-4bfd-9e78-2bbf9db03807"
      },
      "source": [
        "from sklearn.feature_extraction.text import TfidfVectorizer\n",
        "\n",
        "tv = TfidfVectorizer(min_df=0., max_df=1., use_idf=True)\n",
        "tv_matrix = tv.fit_transform(norm_corpus)\n",
        "tv_matrix = tv_matrix.toarray()\n",
        "\n",
        "vocab = tv.get_feature_names()\n",
        "pd.DataFrame(np.round(tv_matrix, 2), columns=vocab)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>bacon</th>\n",
              "      <th>beans</th>\n",
              "      <th>beautiful</th>\n",
              "      <th>blue</th>\n",
              "      <th>breakfast</th>\n",
              "      <th>brown</th>\n",
              "      <th>dog</th>\n",
              "      <th>eggs</th>\n",
              "      <th>fox</th>\n",
              "      <th>green</th>\n",
              "      <th>ham</th>\n",
              "      <th>jumps</th>\n",
              "      <th>kings</th>\n",
              "      <th>lazy</th>\n",
              "      <th>love</th>\n",
              "      <th>quick</th>\n",
              "      <th>sausages</th>\n",
              "      <th>sky</th>\n",
              "      <th>toast</th>\n",
              "      <th>today</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.60</td>\n",
              "      <td>0.53</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.60</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.49</td>\n",
              "      <td>0.43</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.57</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.49</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.53</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>0.32</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.32</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.32</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.32</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.38</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>0.39</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.39</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.47</td>\n",
              "      <td>0.39</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.39</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.39</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.37</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.42</td>\n",
              "      <td>0.42</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.42</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.42</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.42</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.36</td>\n",
              "      <td>0.32</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.72</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.5</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.45</td>\n",
              "      <td>0.45</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.45</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.45</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.45</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.00</td>\n",
              "      <td>0.0</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "   bacon  beans  beautiful  blue  ...  sausages   sky  toast  today\n",
              "0   0.00   0.00       0.60  0.53  ...      0.00  0.60   0.00    0.0\n",
              "1   0.00   0.00       0.49  0.43  ...      0.00  0.49   0.00    0.0\n",
              "2   0.00   0.00       0.00  0.00  ...      0.00  0.00   0.00    0.0\n",
              "3   0.32   0.38       0.00  0.00  ...      0.32  0.00   0.38    0.0\n",
              "4   0.39   0.00       0.00  0.00  ...      0.39  0.00   0.00    0.0\n",
              "5   0.00   0.00       0.00  0.37  ...      0.00  0.00   0.00    0.0\n",
              "6   0.00   0.00       0.36  0.32  ...      0.00  0.72   0.00    0.5\n",
              "7   0.00   0.00       0.00  0.00  ...      0.00  0.00   0.00    0.0\n",
              "\n",
              "[8 rows x 20 columns]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "0jvKPWIwRP6g"
      },
      "source": [
        "The TF-IDF based feature vectors for each of our text documents show scaled and normalized values as compared to the raw Bag of Words model values. "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7xzqFWAkRP6h"
      },
      "source": [
        "# Document Similarity\n",
        "\n",
        "Document similarity is the process of using a distance or similarity based metric that can be used to identify how similar a text document is with any other document(s) based on features extracted from the documents like bag of words or tf-idf.\n",
        "\n",
        "Thus you can see that we can build on top of the tf-idf based features we engineered in the previous section and use them to generate new features which can be useful in domains like search engines, document clustering and information retrieval by leveraging these similarity based features.\n",
        "\n",
        "Pairwise document similarity in a corpus involves computing document similarity for each pair of documents in a corpus. Thus if you have C documents in a corpus, you would end up with a C x C matrix such that each row and column represents the similarity score for a pair of documents, which represent the indices at the row and column, respectively. There are several similarity and distance metrics that are used to compute document similarity. These include cosine distance/similarity, euclidean distance, manhattan distance, BM25 similarity, jaccard distance and so on. In our analysis, we will be using perhaps the most popular and widely used similarity metric,\n",
        "cosine similarity and compare pairwise document similarity based on their TF-IDF feature vectors."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "zyToCxp9RP6i",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 284
        },
        "outputId": "f9fa6f92-dded-4155-86fe-e6ebc8a5e8a7"
      },
      "source": [
        "from sklearn.metrics.pairwise import cosine_similarity\n",
        "\n",
        "similarity_matrix = cosine_similarity(tv_matrix)\n",
        "similarity_df = pd.DataFrame(similarity_matrix)\n",
        "similarity_df"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>0</th>\n",
              "      <th>1</th>\n",
              "      <th>2</th>\n",
              "      <th>3</th>\n",
              "      <th>4</th>\n",
              "      <th>5</th>\n",
              "      <th>6</th>\n",
              "      <th>7</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.820599</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.192353</td>\n",
              "      <td>0.817246</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>0.820599</td>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.225489</td>\n",
              "      <td>0.157845</td>\n",
              "      <td>0.670631</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.791821</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.850516</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.506866</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.225489</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.506866</td>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>0.192353</td>\n",
              "      <td>0.157845</td>\n",
              "      <td>0.791821</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.115488</td>\n",
              "      <td>0.930989</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>0.817246</td>\n",
              "      <td>0.670631</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.115488</td>\n",
              "      <td>1.000000</td>\n",
              "      <td>0.000000</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.850516</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>0.930989</td>\n",
              "      <td>0.000000</td>\n",
              "      <td>1.000000</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "          0         1         2  ...         5         6         7\n",
              "0  1.000000  0.820599  0.000000  ...  0.192353  0.817246  0.000000\n",
              "1  0.820599  1.000000  0.000000  ...  0.157845  0.670631  0.000000\n",
              "2  0.000000  0.000000  1.000000  ...  0.791821  0.000000  0.850516\n",
              "3  0.000000  0.000000  0.000000  ...  0.000000  0.000000  0.000000\n",
              "4  0.000000  0.225489  0.000000  ...  0.000000  0.000000  0.000000\n",
              "5  0.192353  0.157845  0.791821  ...  1.000000  0.115488  0.930989\n",
              "6  0.817246  0.670631  0.000000  ...  0.115488  1.000000  0.000000\n",
              "7  0.000000  0.000000  0.850516  ...  0.930989  0.000000  1.000000\n",
              "\n",
              "[8 rows x 8 columns]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 8
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "Uq737P7GRP6l"
      },
      "source": [
        "Cosine similarity basically gives us a metric representing the cosine of the angle between the feature vector representations of two text documents. Lower the angle between the documents, the closer and more similar they are as depicted in the following figure.\n",
        "\n",
        "![](https://github.com/dipanjanS/nlp_workshop_odsc19/blob/master/Module04%20-%20Text%20Representation/cosine_depiction.png?raw=1)\n",
        "\n",
        "Looking closely at the similarity matrix clearly tells us that documents (0, 1 and 6), (2, 5 and 7) are very similar to one another and documents 3 and 4 are slightly similar to each other but the magnitude is not very strong, however still stronger than the other documents. This must indicate these similar documents have some similar features. This is a perfect example of grouping or clustering that can be solved by unsupervised learning especially when you are dealing with huge corpora of millions of text documents."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "vh3zF8lKRP6n"
      },
      "source": [
        "# Bonus: Clustering using Document Similarity Features\n",
        "\n",
        "We will use a very popular partition based clustering method, K-means clustering to cluster or group these documents based on their similarity based feature representations. In K-means clustering, we have an input parameter k, which specifies the number of clusters it will output using the document features. This clustering method is a centroid based clustering method, where it tries to cluster these documents into clusters of equal variance. It tries to create these clusters by minimizing the within-cluster sum of squares measure, also known as inertia. "
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "l5ff9gMZRP6o",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 284
        },
        "outputId": "865209d2-1755-4cda-82f3-669c7e4e224d"
      },
      "source": [
        "from sklearn.cluster import KMeans\n",
        "\n",
        "km = KMeans(n_clusters=3, random_state=0)\n",
        "km.fit_transform(similarity_matrix)\n",
        "cluster_labels = km.labels_\n",
        "cluster_labels = pd.DataFrame(cluster_labels, columns=['ClusterLabel'])\n",
        "pd.concat([corpus_df, cluster_labels], axis=1)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>Document</th>\n",
              "      <th>Category</th>\n",
              "      <th>ClusterLabel</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>The sky is blue and beautiful.</td>\n",
              "      <td>weather</td>\n",
              "      <td>2</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Love this blue and beautiful sky!</td>\n",
              "      <td>weather</td>\n",
              "      <td>2</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>The quick brown fox jumps over the lazy dog.</td>\n",
              "      <td>animals</td>\n",
              "      <td>1</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>A king's breakfast has sausages, ham, bacon, eggs, toast and beans</td>\n",
              "      <td>food</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>I love green eggs, ham, sausages and bacon!</td>\n",
              "      <td>food</td>\n",
              "      <td>0</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>The brown fox is quick and the blue dog is lazy!</td>\n",
              "      <td>animals</td>\n",
              "      <td>1</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>The sky is very blue and the sky is very beautiful today</td>\n",
              "      <td>weather</td>\n",
              "      <td>2</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>The dog is lazy but the brown fox is quick!</td>\n",
              "      <td>animals</td>\n",
              "      <td>1</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "                                                             Document  ... ClusterLabel\n",
              "0                                      The sky is blue and beautiful.  ...            2\n",
              "1                                   Love this blue and beautiful sky!  ...            2\n",
              "2                        The quick brown fox jumps over the lazy dog.  ...            1\n",
              "3  A king's breakfast has sausages, ham, bacon, eggs, toast and beans  ...            0\n",
              "4                         I love green eggs, ham, sausages and bacon!  ...            0\n",
              "5                    The brown fox is quick and the blue dog is lazy!  ...            1\n",
              "6            The sky is very blue and the sky is very beautiful today  ...            2\n",
              "7                         The dog is lazy but the brown fox is quick!  ...            1\n",
              "\n",
              "[8 rows x 3 columns]"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "S-NsBGloRP6q"
      },
      "source": [
        "We can see from the above output that our documents were correctly assigned to the right clusters!"
      ]
    }
  ]
}

================================================
FILE: notebooks/03_Text_Representation_Embedding_Models.ipynb
================================================
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "03 -Text Representation - Embedding Models.ipynb",
      "provenance": [],
      "collapsed_sections": []
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.6"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "JS9QXHRoRiqc"
      },
      "source": [
        "# Text Representation with Feature Engineering\n",
        "\n",
        "### Exploring Word Embeddings with New Deep Learning Models\n",
        "\n",
        "We have discussed in the previous sub-unit that Feature Engineering is the secret sauce to creating superior and better performing machine learning models. \n",
        "\n",
        "Traditional (count-based) feature engineering strategies for textual data involve models belonging to a family of models popularly known as the Bag of Words model. This includes term frequencies, TF-IDF (term frequency-inverse document frequency), N-grams and so on. While they are effective methods for extracting features from text, due to the inherent nature of the model being just a bag of unstructured words, we lose additional information like the semantics, structure, sequence and context around nearby words in each text document. \n",
        "\n",
        "This forms as enough motivation for us to explore more sophisticated models which can capture this information and give us features which are vector representation of words, popularly known as embeddings.\n",
        "\n",
        "Here we will explore the following feature engineering techniques:\n",
        "\n",
        "- Word2Vec\n",
        "- GloVe\n",
        "- FastText\n",
        "\n",
        "Predictive methods like Neural Network based language models try to predict words from its neighboring words looking at word sequences in the corpus and in the process it learns distributed representations giving us dense word embeddings. We will be focusing on these predictive methods in this article."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "wYUGSn3dRiqd"
      },
      "source": [
        "# Prepare a Sample Corpus\n",
        "\n",
        "Let’s now take a sample corpus of documents on which we will run most of our analyses in this article. A corpus is typically a collection of text documents usually belonging to one or more subjects or domains."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "KH4ZwBgtRiqe",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 284
        },
        "outputId": "c285dcff-5578-4fa8-9ecf-63dba9b4f7ca"
      },
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "\n",
        "pd.options.display.max_colwidth = 200\n",
        "\n",
        "corpus = ['The sky is blue and beautiful.',\n",
        "          'Love this blue and beautiful sky!',\n",
        "          'The quick brown fox jumps over the lazy dog.',\n",
        "          \"A king's breakfast has sausages, ham, bacon, eggs, toast and beans\",\n",
        "          'I love green eggs, ham, sausages and bacon!',\n",
        "          'The brown fox is quick and the blue dog is lazy!',\n",
        "          'The sky is very blue and the sky is very beautiful today',\n",
        "          'The dog is lazy but the brown fox is quick!'    \n",
        "]\n",
        "labels = ['weather', 'weather', 'animals', 'food', 'food', 'animals', 'weather', 'animals']\n",
        "\n",
        "corpus = np.array(corpus)\n",
        "corpus_df = pd.DataFrame({'Document': corpus, \n",
        "                          'Category': labels})\n",
        "corpus_df = corpus_df[['Document', 'Category']]\n",
        "corpus_df"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>Document</th>\n",
              "      <th>Category</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>0</th>\n",
              "      <td>The sky is blue and beautiful.</td>\n",
              "      <td>weather</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>1</th>\n",
              "      <td>Love this blue and beautiful sky!</td>\n",
              "      <td>weather</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>2</th>\n",
              "      <td>The quick brown fox jumps over the lazy dog.</td>\n",
              "      <td>animals</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>3</th>\n",
              "      <td>A king's breakfast has sausages, ham, bacon, eggs, toast and beans</td>\n",
              "      <td>food</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>4</th>\n",
              "      <td>I love green eggs, ham, sausages and bacon!</td>\n",
              "      <td>food</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>5</th>\n",
              "      <td>The brown fox is quick and the blue dog is lazy!</td>\n",
              "      <td>animals</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>6</th>\n",
              "      <td>The sky is very blue and the sky is very beautiful today</td>\n",
              "      <td>weather</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>7</th>\n",
              "      <td>The dog is lazy but the brown fox is quick!</td>\n",
              "      <td>animals</td>\n",
              "    </tr>\n",
              "  </tbody>\n",
              "</table>\n",
              "</div>"
            ],
            "text/plain": [
              "                                                             Document Category\n",
              "0                                      The sky is blue and beautiful.  weather\n",
              "1                                   Love this blue and beautiful sky!  weather\n",
              "2                        The quick brown fox jumps over the lazy dog.  animals\n",
              "3  A king's breakfast has sausages, ham, bacon, eggs, toast and beans     food\n",
              "4                         I love green eggs, ham, sausages and bacon!     food\n",
              "5                    The brown fox is quick and the blue dog is lazy!  animals\n",
              "6            The sky is very blue and the sky is very beautiful today  weather\n",
              "7                         The dog is lazy but the brown fox is quick!  animals"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 1
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "FLojJzK0Riqi"
      },
      "source": [
        "Let's go ahead and pre-process our text data now"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "7KR8w3qbRiqi"
      },
      "source": [
        "# Simple Text Pre-processing\n",
        "\n",
        "Since the focus of this unit is on feature engineering, we will build a simple text pre-processor which focuses on removing special characters, extra whitespaces, digits, stopwords and lower casing the text corpus."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "5YHHrL7VRiqj",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 185
        },
        "outputId": "114e4855-473e-45da-a614-88cc52a190a3"
      },
      "source": [
        "import nltk\n",
        "import re\n",
        "\n",
        "nltk.download('stopwords')\n",
        "nltk.download('punkt')\n",
        "\n",
        "stop_words = nltk.corpus.stopwords.words('english')\n",
        "\n",
        "def normalize_document(doc):\n",
        "    # lower case and remove special characters\\whitespaces\n",
        "    doc = re.sub(r'[^a-zA-Z\\s]', '', doc, re.I|re.A)\n",
        "    doc = doc.lower()\n",
        "    doc = doc.strip()\n",
        "    # tokenize document\n",
        "    tokens = nltk.word_tokenize(doc)\n",
        "    # filter stopwords out of document\n",
        "    filtered_tokens = [token for token in tokens if token not in stop_words]\n",
        "    # re-create document from filtered tokens\n",
        "    doc = ' '.join(filtered_tokens)\n",
        "    return doc\n",
        "\n",
        "normalize_corpus = np.vectorize(normalize_document)\n",
        "\n",
        "norm_corpus = normalize_corpus(corpus)\n",
        "norm_corpus"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[nltk_data] Downloading package stopwords to /root/nltk_data...\n",
            "[nltk_data]   Unzipping corpora/stopwords.zip.\n",
            "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
            "[nltk_data]   Unzipping tokenizers/punkt.zip.\n"
          ],
          "name": "stdout"
        },
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array(['sky blue beautiful', 'love blue beautiful sky',\n",
              "       'quick brown fox jumps lazy dog',\n",
              "       'kings breakfast sausages ham bacon eggs toast beans',\n",
              "       'love green eggs ham sausages bacon',\n",
              "       'brown fox quick blue dog lazy', 'sky blue sky beautiful today',\n",
              "       'dog lazy brown fox quick'], dtype='<U51')"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 2
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "2JCyCJ6GRiql"
      },
      "source": [
        "# The Word2Vec Model\n",
        "\n",
        "This model was created by Google in 2013 and is a predictive deep learning based model to compute and generate high quality, distributed and continuous dense vector representations of words, which capture contextual and semantic similarity. Essentially these are unsupervised models which can take in massive textual corpora, create a vocabulary of possible words and generate dense word embeddings for each word in the vector space representing that vocabulary. \n",
        "\n",
        "Usually you can specify the size of the word embedding vectors and the total number of vectors are essentially the size of the vocabulary. This makes the dimensionality of this dense vector space much lower than the high-dimensional sparse vector space built using traditional Bag of Words models.\n",
        "\n",
        "There are two different model architectures which can be leveraged by Word2Vec to create these word embedding representations. These include,\n",
        "\n",
        "- The Continuous Bag of Words (CBOW) Model\n",
        "- The Skip-gram Model\n",
        "\n",
        "## The Continuous Bag of Words (CBOW) Model\n",
        "\n",
        "The CBOW model architecture tries to predict the current target word (the center word) based on the source context words (surrounding words). \n",
        "\n",
        "Considering a simple sentence, ___“the quick brown fox jumps over the lazy dog”___, this can be pairs of __(context_window, target_word)__ where if we consider a context window of size 2, we have examples like __([quick, fox], brown)__, __([the, brown], quick)__, __([the, dog], lazy)__ and so on. \n",
        "\n",
        "Thus the model tries to predict the __`target_word`__ based on the __`context_window`__ words.\n",
        "\n",
        "![](https://github.com/dipanjanS/nlp_workshop_odsc19/blob/master/Module04%20-%20Text%20Representation/cbow_arch.png?raw=1)\n",
        "\n",
        "\n",
        "## The Skip-gram Model\n",
        "\n",
        "The Skip-gram model architecture usually tries to achieve the reverse of what the CBOW model does. It tries to predict the source context words (surrounding words) given a target word (the center word). \n",
        "\n",
        "Considering our simple sentence from earlier, ___“the quick brown fox jumps over the lazy dog”___. If we used the CBOW model, we get pairs of __(context_window, target_word)__ where if we consider a context window of size 2, we have examples like __([quick, fox], brown)__, __([the, brown], quick)__, __([the, dog], lazy)__ and so on. \n",
        "\n",
        "Now considering that the skip-gram model’s aim is to predict the context from the target word, the model typically inverts the contexts and targets, and tries to predict each context word from its target word. Hence the task becomes to predict the context __[quick, fox]__ given target word __‘brown’__ or __[the, brown]__ given target word __‘quick’__ and so on. \n",
        "\n",
        "Thus the model tries to predict the context_window words based on the target_word.\n",
        "\n",
        "![](https://github.com/dipanjanS/nlp_workshop_odsc19/blob/master/Module04%20-%20Text%20Representation/skipgram_arch.png?raw=1)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "colab_type": "text",
        "id": "BHD8pUx7Riqm"
      },
      "source": [
        "# Robust Word2Vec Model with Gensim\n",
        "\n",
        "The __`gensim`__ framework, created by Radim Řehůřek consists of a robust, efficient and scalable implementation of the Word2Vec model. We will leverage the same on our sample toy corpus. In our workflow, we will tokenize our normalized corpus and then focus on the following four parameters in the Word2Vec model to build it.\n",
        "\n",
        "- __`size`:__ The word embedding dimensionality\n",
        "- __`window`:__ The context window size\n",
        "- __`min_count`:__ The minimum word count\n",
        "- __`sample`:__ The downsample setting for frequent words\n",
        "- __`sg`:__ Training model, 1 for skip-gram otherwise CBOW\n",
        "\n",
        "We will build a simple Word2Vec model on the corpus and visualize the embeddings."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "-tKqisDuRiqm",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 34
        },
        "outputId": "f7106f35-82d8-4e0d-8940-02d524b4879a"
      },
      "source": [
        "import nltk\n",
        "from gensim.models import word2vec\n",
        "\n",
        "tokenized_corpus = [nltk.word_tokenize(doc) for doc in norm_corpus]\n",
        "\n",
        "# Set values for various parameters\n",
        "feature_size = 15    # Word vector dimensionality  \n",
        "window_context = 20  # Context window size                                                                                    \n",
        "min_word_count = 1   # Minimum word count                        \n",
        "sample = 1e-3        # Downsample setting for frequent words\n",
        "sg = 1               # skip-gram model\n",
        "\n",
        "w2v_model = word2vec.Word2Vec(tokenized_corpus, size=feature_size, \n",
        "                              window=window_context, min_count = min_word_count,\n",
        "                              sg=sg, sample=sample, iter=5000)\n",
        "w2v_model"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<gensim.models.word2vec.Word2Vec at 0x7fa2e347da58>"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "6NY4l-zaRiqo",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 378
        },
        "outputId": "bd4ef9b9-421e-494a-9a0f-8e3985fba0a4"
      },
      "source": [
        "import matplotlib.pyplot as plt\n",
        "\n",
        "%matplotlib inline\n",
        "\n",
        "# visualize embeddings\n",
        "from sklearn.manifold import TSNE\n",
        "\n",
        "words = w2v_model.wv.index2word\n",
        "wvs = w2v_model.wv[words]\n",
        "\n",
        "tsne = TSNE(n_components=2, random_state=42, n_iter=5000, perplexity=5)\n",
        "np.set_printoptions(suppress=True)\n",
        "T = tsne.fit_transform(wvs)\n",
        "labels = words\n",
        "\n",
        "plt.figure(figsize=(12, 6))\n",
        "plt.scatter(T[:, 0], T[:, 1], c='orange', edgecolors='r')\n",
        "for label, x, y in zip(labels, T[:, 0], T[:, 1]):\n",
        "    plt.annotate(label, xy=(x+1, y+1), xytext=(0, 0), textcoords='offset points')"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "display_data",
          "data": {
            "image/png": "iVBORw0KGgoAAAANSUhEUgAAAtEAAAFpCAYAAABauHSCAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAADl0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uIDMuMC4zLCBo\ndHRwOi8vbWF0cGxvdGxpYi5vcmcvnQurowAAIABJREFUeJzs3Xucz3X+///byyGSU0U60aivHOeA\nGdkcUiraRGIpbGHxK5FtN9tJrZS2Wvupj1JKIhubXUqlTZtiUaoZzDiEj7RDyRYbMg1leP3+eI/3\nDhGvDDOT2/Vymcu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jvvvsY\nNmwYAAMGDKB9+/ZcfPHFR/1yNm3aRKdOnZg8eTLJycnf237llVdSrlw5qlWrxmmnncYXX3zBu+++\nS6dOnShfvjyVKlXiqquuiu+flJREz549eeGFFyhTxvu3C8rOzqZRo0ZFXUYkJbFmSUef/3eXFN2a\n9bGuGAVMuR3okwd//CMAf8z/vVe1atXiTw4sKCEhgXbt2n1v/eDBgxk8eHChlfzfQve7IfGmX1Ol\nShVq1arFggULaNCgwfcOKfgY8NKlS5OXl/eDb/H6668zb948XnvtNUaOHMmyZcsM05L0E+NItKTo\nSmqf5oM8LvyEHTt4+eWXmTRpElOmTDmsU7Vo0YLXXnuNnTt3kpOTw8yZMwHYs2cPn376KRdffDEP\nP/ww27ZtIycn52heVYmze/du+vfvT8OGDbn88svZsWMH48aNIy0tjeTkZLp06RLvEd67d29uuukm\nmjdvzrnnnsvcuXPp27cv9evXp3fv3ses5ry8PHr27En9+vXp2rUrubm5jBgxgrS0NBo1asSAAQPY\n2+3q448/5tJLLyU5OZkmTZqwdu1awjBk6NChNGrUiMTERKZOnQrEnoTZpk0bunbtSr169ejZsycl\noWuWJEO0pB/j3pGxvswriD0pcAWx5XuLeZ/mgzwunC+/4KSTTmLmzJk8+uijfP3114c8VVpaGh07\ndiQpKYkrrriCxMREqlSpwu7du+nVqxeJiYk0btyYW265hapVqx7tKytR1qxZw80338yKFSuoWrUq\n06dP55prriE9PZ2srCzq16/P+PHj4/tv2bKFhQsX8uijj9KxY0duvfVWVqxYwbJly8jMzDwmNa9e\nvZqBAweycuVKKleuzJNPPsmgQYNIT09n+fLl7NixI/6HVM+ePbn55pvJysrivffe44wzzuCll14i\nMzOTrKwsZs+ezdChQ9m4cSMAS5Ys4bHHHuOjjz7ik08+4d133z0m1yTpyPjvi5Ki29tOruC0iFE/\nrk/zMXWAaSgJF8DysbHpGVWrViU9PR2Ajh07ArHuHAUV7Cd92223MXz4cHJzc2ndujVNmzalbNmy\nLFiw4Ohdw09A7dq1SUlJAaBp06Z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JyaFFixb85je/YfTo0WzdupUyZQ7ZFEtSCWGIlvTj2cngp22/zithejo33HBDvKPK6tWrGT58\neOTTtm7dmnnz5nHWWWfRu3dvJk2a9KNqOr/j5Sy+604SExMZNmwYI0aMYODAgUybNo1ly5bRv3//\neHeXMmXKsGdPbIpRwY4vPXr04NVXX+XEE0/k5z//Oe+8885Bu7z8kD179vD+++/HP5sNGzZQsWJF\n7rjjDp599ll27NhBixYt9hm9llSyGaIlHRk7Gfw0HaDzStu//5VpEybw5ZdfAvDVV1/RuHFj/vnP\nf7Jlyxby8vKYPn16/BTNmzePL7/44ovx9evWraNGjRr079+ffv36xbulRK3p88vXUeH3t9KrVMDQ\noUPj56lWrRo5OTlMmzYtfmhCQgKLFi0C2Gf9J598wrnnnsstt9xCp06dWLp06UG7vKSlpR30Wi+/\n/HIef/zx+HJmZiYAa9euJTExkdtvv520tDRDtPQT4r8rSZK+r2DnFYCG0GDATh6YUJHLL7+cPXv2\nULZsWcaMGcNdd91Fs2bNOOWUU6hXrx5VqlQBYjfX9erVi5EjR9K+ffv4+rlz5/LHP/6RsmXLUrFi\nxcMfid6vpmUVYOjuHZTq24eyick89dRTzJgxg0aNGnH66aeTlpYWP/S2226jW7duPPPMM1x55ZXx\n9X/961/585//TNmyZTn99NO56667OOmkkxg7diz169enbt268S4vZ5111kGvdfTo0dx8880kJSWR\nl5dH69atGTt2LI899hhz5syhVKlSNGzYkCuuuOIIvhRJxYndOSRJ3xeh80pOTg4VK1YkLy+Pzp07\n07dvXzp37kxubi4nnngiQRDw4osv8pe//CXeyvBo13S0HOxaJf10HG53DkeiJUnfV6cWrF7335Fo\nOGjnleHDhzN79mx27tzJ5ZdfztVXXw3AokWLGDRoEGEYUrVqVZ577rljVtPRcrBrlXT8cSRakvR9\ne+cf98mFusTC6oQKRXvjaHGsqRDl5eXZvUMqBhyJliT9eHtD6Yi7Yc362GjvqJFFG1aLY00R3H//\n/bzwwgtUr16dmjVr0rRpU2bOnElKSgoLFizguuuu4/r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4H3iBBs/C2zl6IKmd4rbDrIg4WupaB8zNJ0fH\nUTwUsh34DBifT5oOpnjYbV29x92CnEf1PNf9yzpgXh7PA9aW6vfkp0JMAo6UthnYGcr9mm8A+yLi\nuVKX86iIpBF5BRpJ5wI3UuxV3wzMydO6Z9KV1RxgU+kCmp2BiFgcEW0RMZbid8SmiLiLBs+ipa9E\nn8bLwBBgQ96O2xoRD0bEHkmrgL0U2zwW5O0iJD0EfAwMAJZFxJ5qht58JN0KvASMAD6QtDMipjuP\n6kXEcc91NSS9A0wBLpZ0AHgCeBpYJWk+8CNwR57+ITCD4uHbo8B9dR9wc5sM3A18lXtwAR7HeVRp\nFLA8P0HoHGBVRKyXtN+RvKMAAABwSURBVBdYKekpYAfFHz/k17cldVA8sDu3ikG3mMdo4Cz8HwvN\nzMzMzGrk7RxmZmZmZjXyItrMzMzMrEZeRJuZmZmZ1ciLaDMzMzOzGnkRbWZmZmZWIy+izczMzMxq\n5EW0mZmZmVmNvIg2MzMzM6vRvwEyPu4Vjj3QAAAAAElFTkSuQmCC\n",
            "text/plain": [
              "<Figure size 864x432 with 1 Axes>"
            ]
          },
          "metadata": {
            "tags": []
          }
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "V7h2GmytRiqq",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 85
        },
        "outputId": "1a4fac8b-d815-4444-da85-cfbde23d1482"
      },
      "source": [
        "w2v_model.wv['sky'], w2v_model.wv['sky'].shape"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(array([-0.8185685 ,  0.3990876 ,  0.02527559, -0.46214026,  0.20842107,\n",
              "         0.75595075, -0.6801817 , -0.65128547,  0.23382275,  0.45040986,\n",
              "         0.97311556,  1.0209339 ,  1.1465698 ,  0.6203446 ,  1.0008206 ],\n",
              "       dtype=float32), (15,))"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab_type": "code",
        "id": "3INpkJK4Riqs",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 669
        },
        "outputId": "bebb8557-724d-40c7-bf92-bbeb5e0bf737"
      },
      "source": [
        "vec_df = pd.DataFrame(wvs, index=words)\n",
        "vec_df"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/html": [
              "<div>\n",
              "<style scoped>\n",
              "    .dataframe tbody tr th:only-of-type {\n",
              "        vertical-align: middle;\n",
              "    }\n",
              "\n",
              "    .dataframe tbody tr th {\n",
              "        vertical-align: top;\n",
              "    }\n",
              "\n",
              "    .dataframe thead th {\n",
              "        text-align: right;\n",
              "    }\n",
              "</style>\n",
              "<table border=\"1\" class=\"dataframe\">\n",
              "  <thead>\n",
              "    <tr style=\"text-align: right;\">\n",
              "      <th></th>\n",
              "      <th>0</th>\n",
              "      <th>1</th>\n",
              "      <th>2</th>\n",
              "      <th>3</th>\n",
              "      <th>4</th>\n",
              "      <th>5</th>\n",
              "      <th>6</th>\n",
              "      <th>7</th>\n",
              "      <th>8</th>\n",
              "      <th>9</th>\n",
              "      <th>10</th>\n",
              "      <th>11</th>\n",
              "      <th>12</th>\n",
              "      <th>13</th>\n",
              "      <th>14</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "      <th>sky</th>\n",
              "      <td>-0.818569</td>\n",
              "      <td>0.399088</td>\n",
              "      <td>0.025276</td>\n",
              "      <td>-0.462140</td>\n",
              "      <td>0.208421</td>\n",
              "      <td>0.755951</td>\n",
              "      <td>-0.680182</td>\n",
              "      <td>-0.651285</td>\n",
              "      <td>0.233823</td>\n",
              "      <td>0.450410</td>\n",
              "      <td>0.973116</td>\n",
              "      <td>1.020934</td>\n",
              "      <td>1.146570</td>\n",
              "      <td>0.620345</td>\n",
              "      <td>1.000821</td>\n",
              "    </tr>\n",
              "    <tr>\n",
              "      <th>blue</th>\n",
              "      <td>-0.347705</td>\n",
              "     
Download .txt
gitextract_ngxsk4bi/

├── .gitignore
├── LICENSE
├── README.md
└── notebooks/
    ├── 01_Text_Wrangling_Examples.ipynb
    ├── 02_Text_Representation_Statistical_Models.ipynb
    ├── 03_Text_Representation_Embedding_Models.ipynb
    ├── 04_NLP_Applications_Text_Similarity_Content_Recommenders.ipynb
    └── 05_NLP_Applications_Predicting_E_Commerce_Product_Recommendation_Ratings_from_Reviews_.ipynb
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (664K chars).
[
  {
    "path": ".gitignore",
    "chars": 1799,
    "preview": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packagi"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 122,
    "preview": "# NLP Essentials\n\nEssential and Fundametal aspects of Natural Language Processing with hands-on examples and case-studie"
  },
  {
    "path": "notebooks/01_Text_Wrangling_Examples.ipynb",
    "chars": 49680,
    "preview": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"accelerator\": \"GPU\",\n    \"anaconda-cloud\": {},\n    \"colab"
  },
  {
    "path": "notebooks/02_Text_Representation_Statistical_Models.ipynb",
    "chars": 67184,
    "preview": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"name\": \"02-Text Representation - Statist"
  },
  {
    "path": "notebooks/03_Text_Representation_Embedding_Models.ipynb",
    "chars": 289190,
    "preview": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"colab\": {\n      \"name\": \"03 -Text Representation - Embedd"
  },
  {
    "path": "notebooks/04_NLP_Applications_Text_Similarity_Content_Recommenders.ipynb",
    "chars": 65089,
    "preview": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"accelerator\": \"GPU\",\n    \"colab\": {\n      \"name\": \"04-NLP"
  },
  {
    "path": "notebooks/05_NLP_Applications_Predicting_E_Commerce_Product_Recommendation_Ratings_from_Reviews_.ipynb",
    "chars": 105263,
    "preview": "{\n  \"nbformat\": 4,\n  \"nbformat_minor\": 0,\n  \"metadata\": {\n    \"kernelspec\": {\n      \"display_name\": \"Python 3\",\n      \"l"
  }
]

About this extraction

This page contains the full source code of the dipanjanS/nlp_essentials GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (599.1 KB), approximately 213.1k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!