├── .flake8
├── .github
└── workflows
│ └── unittest.yml
├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── data
└── oos-intent.jsonl
├── docs
├── api
│ ├── component.md
│ ├── extension.md
│ ├── model.md
│ ├── pipeline.md
│ ├── textprep.md
│ └── wabbit.md
├── faq.md
├── guide
│ ├── sklearn.md
│ └── spacy.md
├── images
│ ├── how-it-works.png
│ ├── huge_sparse_array.png
│ ├── make_concat.png
│ ├── minipipe.png
│ └── pipeline.png
├── index.md
├── logo-tokw.png
└── token.png
├── mkdocs.yml
├── setup.py
├── tests
├── __init__.py
├── conftest.py
├── data
│ ├── en.vs5000.model
│ └── nlp.txt
├── pipeline
│ ├── __init__.py
│ ├── test_concat.py
│ ├── test_slice.py
│ └── test_union.py
├── test_common.py
├── test_docs.py
├── test_extension.py
├── test_spacy_models
│ ├── __init__.py
│ └── test_base_usage_architectures.py
├── test_textprep
│ ├── test_hyphen.py
│ ├── test_phonetic.py
│ └── test_sklearn.py
├── test_tfm.py
├── test_tok
│ ├── __init__.py
│ └── test_whitespace.py
└── test_wabbit.py
├── theme
├── token.png
└── token.svg
├── token.png
└── tokenwiser
├── __init__.py
├── __main__.py
├── common.py
├── component
├── __init__.py
└── _sklearn.py
├── extension
├── __init__.py
└── _extension.py
├── model
├── __init__.py
└── sklearnmod.py
├── pipeline
├── __init__.py
├── _concat.py
├── _pipe.py
└── _union.py
├── proj
└── __init__.py
├── textprep
├── __init__.py
├── _cleaner.py
├── _hyphen.py
├── _identity.py
├── _morph.py
├── _phonetic.py
├── _prep.py
├── _sentpiece.py
├── _snowball.py
└── _yake.py
├── tok
├── __init__.py
├── _spacy.py
├── _tok.py
└── _whitespace.py
└── wabbit
├── __init__.py
└── _vowpal.py
/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | per-file-ignores =
3 | clumper/__init__.py: F401
4 | max-line-length = 160
5 | ignore = E203
--------------------------------------------------------------------------------
/.github/workflows/unittest.yml:
--------------------------------------------------------------------------------
1 | name: Python package
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | build:
13 | runs-on: ${{ matrix.os }}
14 | strategy:
15 | matrix:
16 | os: [ubuntu-latest]
17 | python-version: [3.7, 3.8, 3.9]
18 |
19 | steps:
20 | - uses: actions/checkout@v2
21 | - name: Set up Python ${{ matrix.python-version }}
22 | uses: actions/setup-python@v1
23 | with:
24 | python-version: ${{ matrix.python-version }}
25 | - name: Install General Dependencies
26 | run: |
27 | python -m pip install --upgrade pip setuptools wheel
28 | pip install -e ".[dev]"
29 | python -m spacy download en_core_web_sm
30 | - name: Test with pytest
31 | run: |
32 | pytest --verbose tests
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 | .idea
131 | *.ipynb
132 | *.model
133 | *.csv
134 | .DS_Store
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | black:
2 | black tokenwiser tests setup.py --check
3 |
4 | flake:
5 | flake8 tokenwiser tests setup.py
6 |
7 | test:
8 | pytest
9 |
10 | check: black flake test
11 |
12 | install:
13 | python -m pip install -e .
14 |
15 | install-dev:
16 | python -m pip install -e ".[dev]"
17 | pre-commit install
18 |
19 | install-test:
20 | python -m pip install -e ".[test]"
21 | python -m pip install -e ".[all]"
22 |
23 | pypi:
24 | python setup.py sdist
25 | python setup.py bdist_wheel --universal
26 | twine upload dist/*
27 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # tokenwiser
4 |
5 | > Bag of, not words, but tricks!
6 |
7 | This project contains a couple of "tricks" on tokens. It's a collection
8 | of tricks for sparse data that might be trained on a stream of data too.
9 |
10 | While exploring these tricks was super fun, I do feel like there are plenty
11 | of better alternatives than the ideas I explore here. In the end, TfIDF + LogReg
12 | can be "fine" for a bunch of tasks that don't require embeddings.
13 |
14 | And for embeddings ... there's [embetter](https://github.com/koaning/embetter).
15 |
16 | So I archived this repo. Bit of a shame, because I _really_ liked the name of this package.
17 |
--------------------------------------------------------------------------------
/docs/api/component.md:
--------------------------------------------------------------------------------
1 | # `component`
2 |
3 | ```python
4 | from tokenwiser.component import *
5 | ```
6 |
7 | In the `component` submodule you can find spaCy compatible components.
8 |
9 | ::: tokenwiser.component.attach_sklearn_categoriser
10 | rendering:
11 | show_root_full_path: false
12 | show_root_heading: true
13 |
--------------------------------------------------------------------------------
/docs/api/extension.md:
--------------------------------------------------------------------------------
1 | # `extension`
2 |
3 | ```python
4 | from tokenwiser.extension import *
5 | ```
6 |
7 | In the `extension` submodule you can find spaCy compatible extensions.
8 |
9 | ::: tokenwiser.extension.attach_hyphen_extension
10 | rendering:
11 | show_root_full_path: false
12 | show_root_heading: true
13 |
14 |
15 | ::: tokenwiser.extension.sklearn_method
16 | rendering:
17 | show_root_full_path: false
18 | show_root_heading: true
19 |
--------------------------------------------------------------------------------
/docs/api/model.md:
--------------------------------------------------------------------------------
1 | # `model`
2 |
3 | ```python
4 | from tokenwiser.model import *
5 | ```
6 |
7 | In the `model` submodule you can find scikit-learn pipelines that are trainable via spaCy.
8 | These pipelines apply the `.partial_fit().predict()`-design which makes them compliant with
9 | the `spacy train` command.
10 |
11 | ::: tokenwiser.model.SklearnCat
12 | rendering:
13 | show_root_full_path: false
14 | show_root_heading: true
15 |
--------------------------------------------------------------------------------
/docs/api/pipeline.md:
--------------------------------------------------------------------------------
1 | # `pipeline`
2 |
3 | ```python
4 | from tokenwiser.pipeline import *
5 | ```
6 |
7 | In the `pipeline` submodule you can find scikit-learn compatbile
8 | pipelines that extend the standard behavior.
9 |
10 | ::: tokenwiser.pipeline.PartialPipeline
11 | rendering:
12 | show_root_full_path: false
13 | show_root_heading: true
14 |
15 | ::: tokenwiser.pipeline.TextConcat
16 | rendering:
17 | show_root_full_path: false
18 | show_root_heading: true
19 | selection:
20 | members:
21 | - partial_fit
22 |
23 | ::: tokenwiser.pipeline.PartialFeatureUnion
24 | rendering:
25 | show_root_full_path: false
26 | show_root_heading: true
27 |
28 | ::: tokenwiser.pipeline.make_partial_pipeline
29 | rendering:
30 | show_root_full_path: false
31 | show_root_heading: true
32 |
33 | ::: tokenwiser.pipeline.make_concat
34 | rendering:
35 | show_root_full_path: false
36 | show_root_heading: true
37 |
38 | ::: tokenwiser.pipeline.make_partial_union
39 | rendering:
40 | show_root_full_path: false
41 | show_root_heading: true
42 |
--------------------------------------------------------------------------------
/docs/api/textprep.md:
--------------------------------------------------------------------------------
1 | # `textprep`
2 |
3 | ```python
4 | from tokenwiser.textprep import *
5 | ```
6 |
7 | In the `textprep` submodule you can find scikit-learn compatbile
8 | components that transform text into another type of text. The idea
9 | is that this may be combined in interesting ways in CountVectorizers.
10 |
11 | ::: tokenwiser.textprep.Cleaner
12 | rendering:
13 | show_root_full_path: false
14 | show_root_heading: true
15 |
16 | ::: tokenwiser.textprep.Identity
17 | selection:
18 | members:
19 | - no
20 | rendering:
21 | show_root_full_path: false
22 | show_root_heading: true
23 |
24 | ::: tokenwiser.textprep.HyphenTextPrep
25 | selection:
26 | members:
27 | - fit
28 | - transform
29 | rendering:
30 | show_root_full_path: false
31 | show_root_heading: true
32 |
33 | ::: tokenwiser.textprep.SentencePiecePrep
34 | rendering:
35 | show_root_full_path: false
36 | show_root_heading: true
37 |
38 | ::: tokenwiser.textprep.PhoneticTextPrep
39 | rendering:
40 | show_root_full_path: false
41 | show_root_heading: true
42 |
43 | ::: tokenwiser.textprep.YakeTextPrep
44 | rendering:
45 | show_root_full_path: false
46 | show_root_heading: true
47 |
48 | ::: tokenwiser.textprep.SpacyMorphTextPrep
49 | rendering:
50 | show_root_full_path: false
51 | show_root_heading: true
52 |
53 | ::: tokenwiser.textprep.SpacyPosTextPrep
54 | rendering:
55 | show_root_full_path: false
56 | show_root_heading: true
57 |
58 | ::: tokenwiser.textprep.SpacyLemmaTextPrep
59 | rendering:
60 | show_root_full_path: false
61 | show_root_heading: true
62 |
63 | ::: tokenwiser.textprep.SnowballTextPrep
64 | rendering:
65 | show_root_full_path: false
66 | show_root_heading: true
67 |
--------------------------------------------------------------------------------
/docs/api/wabbit.md:
--------------------------------------------------------------------------------
1 | # `wabbit`
2 |
3 | ```python
4 | from tokenwiser.wabbit import *
5 | ```
6 |
7 | In the `wabbit` submodule you can find a scikit-learn
8 | component based on [vowpal wabbit](https://vowpalwabbit.org/).
9 |
10 | ::: tokenwiser.wabbit.VowpalWabbitClassifier
11 | rendering:
12 | show_root_full_path: false
13 | show_root_heading: true
14 |
--------------------------------------------------------------------------------
/docs/faq.md:
--------------------------------------------------------------------------------
1 | ## Why can't I use normal `Pipeline` objects with the spaCy API?
2 |
3 | Scikit-Learn assumes that data is trained via `.fit(X, y).predict(X)`. This is great
4 | when you've got a dataset fully in memory but it's not so great when your dataset is
5 | too big to fit in one go. This is a main reason why spaCy has an `.update()`
6 | API for their trainable pipeline components. It's similar to `.partial_fit(X)` in
7 | scikit-learn. You wouldn't train on a single batch of data. Instead you would iteratively
8 | train on subsets of the dataset.
9 |
10 | A big downside of the `Pipeline` API is that it cannot use `.partial_fit(X)`.
11 | Even if all the components on the inside are compatible, it forces you to use `.fit(X)`.
12 | That is why this library offers a `PartialPipeline`. It only allows for components that have `.partial_fit`
13 | implemented and it's these pipelines that can also comply with spaCy's `.update()`
14 | API.
15 |
16 | Note that all scikit-learn components offered by this library are compatible with
17 | the `PartialPipeline`. This includes everything from the `tokeniser.textprep` submodule.
18 |
19 | ## Can I train spaCy with scikit-learn from Jupyter?
20 |
21 | It's not our favorite way of doing things, but nobody is stopping you.
22 |
23 | ```python
24 | import spacy
25 | from spacy import registry
26 | from spacy.training import Example
27 | from spacy.language import Language
28 |
29 | from tokenwiser.pipeline import PartialPipeline
30 | from tokenwiser.model.sklearnmod import SklearnCat
31 | from sklearn.feature_extraction.text import HashingVectorizer
32 | from sklearn.linear_model import SGDClassifier
33 |
34 | @Language.factory("custom-sklearn-cat")
35 | def make_sklearn_cat(nlp, name, sklearn_model, label, classes):
36 | return SklearnCat(nlp, name, sklearn_model, label, classes)
37 |
38 | @registry.architectures("sklearn_model_basic_sgd.v1")
39 | def make_sklearn_cat_basic_sgd():
40 | """This creates a *partial* pipeline. We can't use a standard pipeline from scikit-learn."""
41 | return PartialPipeline([("hash", HashingVectorizer()), ("lr", SGDClassifier(loss="log"))])
42 |
43 |
44 | nlp = spacy.load("en_core_web_sm")
45 | config = {
46 | "sklearn_model": "@sklearn_model_basic_sgd.v1",
47 | "label": "pos",
48 | "classes": ["pos", "neg"]
49 | }
50 | nlp.add_pipe("custom-sklearn-cat", config=config)
51 |
52 | texts = [
53 | "you are a nice person",
54 | "this is a great movie",
55 | "i do not like cofee",
56 | "i hate tea"
57 | ]
58 | labels = ["pos", "pos", "neg", "neg"]
59 |
60 | # This is the training loop just for out categorizer model.
61 | with nlp.select_pipes(enable="custom-sklearn-cat"):
62 | optimizer = nlp.resume_training()
63 | for loop in range(10):
64 | for t, lab in zip(texts, labels):
65 | doc = nlp.make_doc(t)
66 | example = Example.from_dict(doc, {"cats": {"pos": lab}})
67 | nlp.update([example], sgd=optimizer)
68 |
69 | nlp("you are a nice person").cats # {'pos': 0.9979167909733176}
70 | nlp("coffee i do not like").cats # {'neg': 0.990049724779963}
71 | ```
--------------------------------------------------------------------------------
/docs/guide/sklearn.md:
--------------------------------------------------------------------------------
1 | Scikit-Learn pipelines are amazing but they are not perfect for simple text use-cases.
2 |
3 | - The standard pipeline does not allow for interactive learning. You can
4 | apply `.fit` but that's it. Even if the tools inside of the pipeline have
5 | a `.partial_fit` available, the pipeline doesn't allow it.
6 | - The `CountVectorizer` is great, but we might need some more text-tricks
7 | at our disposal that are specialized towards text to make this object more effective.
8 |
9 | Part of what this library does is give more tools that extend scikit-learn for simple
10 | text classification problems. In this document we will showcase some of the main features.
11 |
12 | ## Text Preparation Tools
13 |
14 | Let's first discuss a basic pipeline for text inside of scikit-learn.
15 |
16 | ### Base Pipeline
17 |
18 | This simplest text classification pipeline in scikit-learn looks like this;
19 |
20 | 
21 |
22 | ```python
23 | from sklearn.pipeline import make_pipeline
24 | from sklearn.feature_extraction.text import CountVectorizer
25 | from sklearn.linear_model import SGDClassifier
26 |
27 | pipe = make_pipeline(
28 | CountVectorizer(),
29 | SGDClassifier()
30 | )
31 | ```
32 |
33 | This pipeline will encode words as sparse features before passing them on to the logistic regression model.
34 | This pattern is very common and has proven to work well enough for many English text classification tasks.
35 |
36 | 
37 |
38 | The nice thing about using a `SGDClassifier` is that we're able to learn from our data even if the dataset
39 | does not fit in memory. We can call `.partial_fit` instead of `.fit` and learn in a more "online" setting.
40 |
41 | That said, there are things we can do even to this pipeline to make it better.
42 |
43 | ### Spelling Errors
44 |
45 | When you are classifying online texts you are often confronted with spelling errors. To
46 | deal with this you'd typically use a [CountVectorizer](https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html)
47 | with a character-level analyzer such that you also encode subwords.
48 |
49 | 
50 |
51 | With all of these subwords around, we'll be more robust against spelling errors.
52 | The downside of this approach is that you might wonder if we really *need* all these subwords. So how about this,
53 | let's add a step that will turn our text into subwords by splitting up hyphens.
54 |
55 | ```python
56 | from tokenwiser.textprep import HyphenTextPrep
57 |
58 | multi = HyphenTextPrep().transform(["geology", "astrology"])
59 |
60 | assert multi == ['geo logy', 'as tro logy']
61 | ```
62 |
63 | The `HyphenTextPrep` preprocessor is a `TextPrep`-object. For all intents and purposes these are
64 | scikit-learn compatible preprocessing components but they all output strings instead of arrays. What's
65 | nice about these though is that you can "retokenize" the original text. This allows you to use the
66 | subtokens as if they were tokens which might help keep your pipelines lightweight while still keeping
67 | them robust against certain spelling errors.
68 |
69 | ### Long Texts
70 |
71 | There are some other tricks that you might want to apply for longer texts. Maybe you want to summarise a text before
72 | vectorizing it. So maybe it'd be nice to use a transformer that keeps only the most important tokens.
73 |
74 | A neat heuristic toolkit for this is [yake](https://github.com/LIAAD/yake) (you can find a demo
75 | [here](http://yake.inesctec.pt/demo/sample/sample1)). This package also features a scikit-learn compatible component for it.
76 |
77 | ```python
78 | from tokenwiser.textprep import YakeTextPrep
79 |
80 | text = [
81 | "Sources tell us that Google is acquiring Kaggle, \
82 | a platform that hosts data science and machine learning"
83 | ]
84 | example = YakeTextPrep(top_n=3, unique=False).transform(text)
85 |
86 | assert example[0] == 'hosts data science acquiring kaggle google is acquiring'
87 | ```
88 |
89 | The idea here is to reduce the text down to only the most important words. Again, this trick
90 | might keep the algorithm lightweight and this trick will go a lot further than most "stopword"-lists.
91 |
92 | ### Bag of Tricks!
93 |
94 | The goal of this library is to host a few meaningful tricks that might be helpful. Here's some more;
95 |
96 | - `Cleaner` lowercase text remove all non alphanumeric characters.
97 | - `Identity` just keeps the text as is, useful when constructing elaborate pipelines.
98 | - `PhoneticTextPrep` translate text into a phonetic encoding.
99 | - `SpacyPosTextPrep` add part of speech infomation to the text using spaCy.
100 | - `SpacyLemmaTextPrep` lemmatize the text using spaCy.
101 |
102 | All of these tools are part of the `textprep` submodule and are documented in detail
103 | [here](https://koaning.github.io/tokenwiser/api/textprep.html).
104 |
105 | ## Pipeline Tools
106 |
107 | Pipeline components are certainly nice. But maybe we can go a step further for text. Maybe
108 | we can make better pipelines for text too!
109 |
110 | ### Concatenate Text
111 |
112 | In scikit-learn you would use `FeatureUnion` or `make_union` to concatenate features in
113 | a pipeline. Ut is assumed that transformers output arrays that need to be concatenated so the
114 | result of a concatenation is always a 2D array. This can be a bit awkward if you're using text preprocessors.
115 |
116 | 
117 |
118 | The reason why we want to keep everything a string is so that the `CountVectorizer` from scikit-learn
119 | can properly encode it. That is why this library comes with a special union
120 | component: `TextConcat`. It concatenates the output of text-prep tools into a string instead of
121 | an array. Note that we also pack a convenient `make_concat` function too.
122 |
123 | ```python
124 | from sklearn.pipeline import make_pipeline
125 |
126 | from tokenwiser.pipeline import make_concat
127 | from tokenwiser.textprep import Cleaner, Identity, HyphenTextPrep
128 |
129 | pipe = make_pipeline(
130 | Cleaner(),
131 | make_concat(Identity(), HyphenTextPrep()),
132 | )
133 |
134 | output = pipe.fit_transform(["hello astrology!!!!"])
135 | assert output == ['hello astrology hel lo astro logy']
136 | ```
137 |
138 | Again, we see that we're taking a text input and that we're generating a text output. The `make_concat`
139 | is making sure that we concatenate strings, not arrays! This is great when we want to follow up with
140 | a `CountVectorizer!
141 |
142 | ```python
143 | from sklearn.pipeline import make_pipeline
144 | from sklearn.linear_model import LogisticRegression
145 | from sklearn.feature_extraction.text import CountVectorizer
146 |
147 | from tokenwiser.pipeline import make_concat
148 | from tokenwiser.textprep import Cleaner, Identity, HyphenTextPrep
149 |
150 | pipe = make_pipeline(
151 | Cleaner(),
152 | make_concat(Identity(), HyphenTextPrep()),
153 | CountVectorizer(),
154 | LogisticRegression()
155 | )
156 | ```
157 |
158 | The mental picture for `pipe`-pipeline looks like the diagram below.
159 |
160 | 
161 |
162 | ### Partial Fit
163 |
164 | We can go a step further though. The scikit-learn pipeline follows the `fit/predict` API. That
165 | means that we cannot use `.partial_fit()`. Even if all the components in the pipeline are compatible
166 | with the `partial_fit/predict` API. That is why this library also introduced components for mini-batch
167 | learning: `PartialPipeline` and `make_partial_pipeline`
168 |
169 | In these scenarios you will need to swap out the `CountVectorizer` with a `HashVectorizer` in order to
170 | be able to learn from new data comming in.
171 |
172 | ```python
173 | from sklearn.linear_model import SGDClassifier
174 | from sklearn.feature_extraction.text import HashingVectorizer
175 |
176 | from tokenwiser.textprep import Cleaner, Identity, HyphenTextPrep
177 | from tokenwiser.pipeline import make_concat, make_partial_pipeline
178 |
179 | pipe = make_partial_pipeline(
180 | Cleaner(),
181 | make_concat(Identity(), HyphenTextPrep()),
182 | HashingVectorizer(),
183 | SGDClassifier()
184 | )
185 | ```
186 |
187 | This `pipe`-Pipeline is scikit-learn compatible for all intents and purposes
188 | but it has the option of learning from batches of data via `partal_fit`. This is great
189 | because it means that you're able to classify text even when it doesn't fit into memory!
190 |
191 | > Note that all of the `TextPrep`-components in this library allow for `partial_fit`.
192 |
193 | To make a `partial_fit` actually work you will need to supply the names of the `classes`
194 | at learning time. Otherwise you might accidentally get a batch that only contains one class
195 | and the algorithm would become numerically unstable.
196 |
197 | ```python
198 | import numpy as np
199 | from sklearn.linear_model import SGDClassifier
200 | from sklearn.feature_extraction.text import HashingVectorizer
201 | from tokenwiser.textprep import Cleaner, Identity, HyphenTextPrep
202 | from tokenwiser.pipeline import make_partial_pipeline, make_partial_union
203 |
204 | pipe = make_partial_pipeline(
205 | Cleaner(),
206 | make_partial_union(
207 | make_partial_pipeline(Identity(), HashingVectorizer()),
208 | make_partial_pipeline(HyphenTextPrep(), HashingVectorizer())
209 | ),
210 | SGDClassifier()
211 | )
212 |
213 | X = [
214 | "i really like this post",
215 | "thanks for that comment",
216 | "i enjoy this friendly forum",
217 | "this is a bad post",
218 | "i dislike this article",
219 | "this is not well written"
220 | ]
221 |
222 | y = np.array([1, 1, 1, 0, 0, 0])
223 |
224 | for loop in range(3):
225 | # It might make sense to loop over the same dataset multiple times
226 | # if the dataset is small. For larger datasets this isn't recommended.
227 | pipe.partial_fit(X, y, classes=[0, 1])
228 |
229 | assert np.all(pipe.predict(X) == np.array([1, 1, 1, 0, 0, 0]))
230 | ```
231 |
232 | ### Concatenate Features
233 |
234 | The standard `FeatureUnion` from scikit-learn also does not allow for `.partial_fit`. So we've
235 | added a `PartialFeatureUnion` class and a `make_partial_union` function to this library as well.
236 |
237 | ```python
238 | import numpy as np
239 | from sklearn.linear_model import SGDClassifier
240 | from sklearn.feature_extraction.text import HashingVectorizer
241 | from tokenwiser.textprep import Cleaner, Identity, HyphenTextPrep
242 | from tokenwiser.pipeline import make_partial_pipeline, make_partial_union
243 |
244 | pipe = make_partial_pipeline(
245 | Cleaner(),
246 | make_partial_union(
247 | make_partial_pipeline(Identity(), HashingVectorizer()),
248 | make_partial_pipeline(HyphenTextPrep(), HashingVectorizer())
249 | ),
250 | SGDClassifier()
251 | )
252 |
253 | X = [
254 | "i really like this post",
255 | "thanks for that comment",
256 | "i enjoy this friendly forum",
257 | "this is a bad post",
258 | "i dislike this article",
259 | "this is not well written"
260 | ]
261 |
262 | y = np.array([1, 1, 1, 0, 0, 0])
263 |
264 | for loop in range(3):
265 | pipe.partial_fit(X, y, classes=[0, 1])
266 |
267 | assert np.all(pipe.predict(X) == np.array([1, 1, 1, 0, 0, 0]))
268 | ```
--------------------------------------------------------------------------------
/docs/guide/spacy.md:
--------------------------------------------------------------------------------
1 | This is where we'll elaborate on the `spaCy` tools.
2 |
3 | Under construction.
--------------------------------------------------------------------------------
/docs/images/how-it-works.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koaning/tokenwiser/1b6a2a28f8e520fd9e8c670cb58a5ceb3f6c08ef/docs/images/how-it-works.png
--------------------------------------------------------------------------------
/docs/images/huge_sparse_array.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koaning/tokenwiser/1b6a2a28f8e520fd9e8c670cb58a5ceb3f6c08ef/docs/images/huge_sparse_array.png
--------------------------------------------------------------------------------
/docs/images/make_concat.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koaning/tokenwiser/1b6a2a28f8e520fd9e8c670cb58a5ceb3f6c08ef/docs/images/make_concat.png
--------------------------------------------------------------------------------
/docs/images/minipipe.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koaning/tokenwiser/1b6a2a28f8e520fd9e8c670cb58a5ceb3f6c08ef/docs/images/minipipe.png
--------------------------------------------------------------------------------
/docs/images/pipeline.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/koaning/tokenwiser/1b6a2a28f8e520fd9e8c670cb58a5ceb3f6c08ef/docs/images/pipeline.png
--------------------------------------------------------------------------------
/docs/index.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |