├── .gitignore
├── LICENSE
├── README.md
├── ch01
├── dtree.py
└── test.py
├── ch02
├── alphabets.txt
├── dtree.py
├── sample.txt
└── test.py
├── ch03
├── dtree.py
└── test.py
├── ch04
├── census.csv
├── dtree.py
└── test.py
├── ch05
├── dtree.py
├── forest.py
├── test.py
└── titanic.py
├── ch06
├── dtree.py
└── test.py
└── ch07
├── dtree.py
├── forest.py
└── test.py
/.gitignore:
--------------------------------------------------------------------------------
1 | **/__pycache__/*
2 | .idea/*
3 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tree-based Machine Learning Algorithms
2 | Source code from the book Tree-based Machine Learning Algorithms by Clinton Sheppard
3 |
4 | Description
5 | ===
6 |
7 |
8 | Get a hands-on introduction to building and using decision trees and random forests. Tree-based machine learning algorithms are used to categorize data based by known outcomes in order to facilitate predicting outcomes in new situations.
9 |
10 | You will learn not only how to use decision trees and random forests for classification and regression, and their respective limitations, but also how the algorithms that build them work. Each chapter introduces a new data concern and then walks you through modifying the code, thus building the engine just-in-time. Along the way you will gain experience making decision trees and random forests work for you.
11 |
12 | Available from major stores including Amazon and Barnes & Noble, in paperback and Kindle formats.
13 |
14 | - https://www.amazon.com/Tree-based-Machine-Learning-Algorithms-Decision/dp/1975860977 ISBN-13: 978-1-975-86097-4 (paperback)
15 | - https://www.amazon.com/dp/B0756FGJCP/ (Kindle Edition)
16 |
17 | Table of Contents
18 | ===
19 |
20 | A brief introduction to decision trees
21 |
22 | Chapter 1: Branching
23 | - uses a greedy algorithm to build a decision tree from data that can be split on a single attribute.
24 |
25 | Chapter 2: Multiple Branches
26 | - examines several ways to split data in order to generate multi-level decision trees.
27 |
28 | Chapter 3: Continuous Attributes
29 | - adds the ability to split numeric attributes using greater-than.
30 |
31 | Chapter 4: Pruning
32 | - explore ways of reducing the amount of error encoded in the tree.
33 |
34 | Chapter 5: Random Forests
35 | - introduces ensemble learning and feature engineering.
36 |
37 | Chapter 6: Regression Trees
38 | - investigates numeric predictions, like age, price, and miles per gallon.
39 |
40 | Chapter 7: Boosting
41 | - adjusts the voting power of the randomly selected decision trees in the random forest in order to improve its ability to predict outcomes.
42 |
43 |
--------------------------------------------------------------------------------
/ch01/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 1 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 |
20 |
21 | def build(data, outcomeLabel):
22 | attrIndexes = [index for index, label in enumerate(data[0]) if
23 | label != outcomeLabel]
24 | outcomeIndex = data[0].index(outcomeLabel)
25 |
26 | nodes = []
27 | lastNodeNumber = 0
28 |
29 | workQueue = [(-1, lastNodeNumber, set(i for i in range(1, len(data))))]
30 | while len(workQueue) > 0:
31 | parentNodeId, nodeId, dataRowIndexes = workQueue.pop()
32 | uniqueOutcomes = set(data[i][outcomeIndex] for i in dataRowIndexes)
33 | if len(uniqueOutcomes) == 1:
34 | nodes.append((nodeId, uniqueOutcomes.pop()))
35 | continue
36 | attrValueResults = []
37 | for attrIndex in attrIndexes:
38 | for rowIndex in dataRowIndexes:
39 | row = data[rowIndex]
40 | value = row[attrIndex]
41 | attrValueResults.append((attrIndex, value))
42 | potentials = [i for i in Counter(attrValueResults).most_common(1)]
43 | attrIndex, attrValue = potentials[0][0]
44 | matches = {rowIndex for rowIndex in dataRowIndexes if
45 | data[rowIndex][attrIndex] == attrValue}
46 | nonMatches = dataRowIndexes - matches
47 | lastNodeNumber += 1
48 | matchId = lastNodeNumber
49 | workQueue.append((nodeId, matchId, matches))
50 | lastNodeNumber += 1
51 | nonMatchId = lastNodeNumber
52 | workQueue.append((nodeId, nonMatchId, nonMatches))
53 | nodes.append((nodeId, attrIndex, attrValue, matchId, nonMatchId))
54 | nodes = sorted(nodes, key=lambda n: n[0])
55 | return DTree(nodes, data[0])
56 |
57 |
58 | class DTree:
59 | def __init__(self, nodes, attrNames):
60 | self._nodes = nodes
61 | self._attrNames = attrNames
62 |
63 | @staticmethod
64 | def _is_leaf(node):
65 | return len(node) == 2
66 |
67 | def __str__(self):
68 | s = ''
69 | for node in self._nodes:
70 | if self._is_leaf(node):
71 | s += '{}: {}\n'.format(node[0], node[1])
72 | else:
73 | nodeId, attrIndex, attrValue, nodeIdIfMatch, \
74 | nodeIdIfNonMatch = node
75 | s += '{}: {}={}, Yes->{}, No->{}\n'.format(
76 | nodeId, self._attrNames[attrIndex], attrValue,
77 | nodeIdIfMatch, nodeIdIfNonMatch)
78 | return s
79 |
80 | def get_prediction(self, data):
81 | currentNode = self._nodes[0]
82 | while True:
83 | if self._is_leaf(currentNode):
84 | return currentNode[1]
85 | nodeId, attrIndex, attrValue, nodeIdIfMatch, \
86 | nodeIdIfNonMatch = currentNode
87 | currentNode = self._nodes[nodeIdIfMatch if
88 | data[attrIndex] == attrValue else nodeIdIfNonMatch]
89 |
--------------------------------------------------------------------------------
/ch01/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 1 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 |
20 | data = [['Name', 'Gender', 'Born'],
21 | ['William', 'male', 'Germany'],
22 | ['Louise', 'female', 'Texas'],
23 | ['Minnie', 'female', 'Texas'],
24 | ['Emma', 'female', 'Texas'],
25 | ['Henry', 'male', 'Germany'],
26 | ]
27 |
28 | outcomeLabel = 'Born'
29 |
30 | tree = dtree.build(data, outcomeLabel)
31 | print(tree)
32 |
33 | testData = ["Alice", "female"]
34 | predicted = tree.get_prediction(testData)
35 | print("predicted: {}".format(predicted))
36 |
--------------------------------------------------------------------------------
/ch02/alphabets.txt:
--------------------------------------------------------------------------------
1 | # source: https://github.com/handcraftsman/TreeBasedMachineLearningAlgorithms/blob/master/ch02/alphabets.txt
2 | Albanian A a B b C c Ç ç D d Dh dh E e Ë ë F f G g Gj gj H h I i J j K k L l Ll ll M m N n Nj nj O o P p Q q R r Rr rr S s Sh sh T t Th th U u V v X x Xh xh Y y Z z Zh zh
3 | Croatian A a B b C c Č č Ć ć D d Dž dž Đ đ E e F f G g H h I i J j K k L l Lj lj M m N n Nj nj O o P p R r S s Š š T t U u V v Z z Ž ž
4 | Czech A a Á á B b C c Č č D d Ď ď E e É é Ě ě F f G g H h Ch ch I i Í í J j K k L l M m N n Ň ň O o Ó ó P p Q q R r Ř ř S s Š š T t Ť ť U u Ú ú Ů ů V v W w X x Y y Ý ý Z z Ž ž
5 | Danish A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Æ æ Ø ø Å å
6 | Dutch A a B b, C c, D d, E e F f, G g, H h, I i J j, K k, L l, M m, N n, O o P p, Q q, R r, S s, T t, U u V v, W w, X x, Y y Z z Á á, Ä ä É é, Ë ë Í í, Ï ï, IJ ij Ó ó, Ö ö Ú ú, Ü ü Ý ý
7 | English A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z
8 | Estonian A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s Š š Z z Ž ž T t U u V v W w Õ õ Ä ä Ö ö Ü ü X x Y y
9 | Finnish A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Å å Ä ä Ö ö
10 | French A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z à â ç è é ë ò ô ö ù
11 | German A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Ä ä Ö ö Ü ü ß
12 | Hungarian A a B b C c Cs cs D d Dz dz Dzs dzs E e F f G g Gy gy H h I i J j K k L l Ly ly M m N n Ny ny O o P p Q q R r S s Sz sz T t Ty ty U u V v W w X x Y y Z z Zs zs Á á É é Í í Ó ó Ö ö Ú ú Ü ü Ő ő Ű ű
13 | Icelandic A a Á á B b D d Ð ð E e É é F f G g H h I i Í í J j K k L l M m N n O o Ó ó P p R r S s T t U u Ú ú V v X x Y y Ý ý Þ þ Æ æ Ö ö
14 | Irish A a B b C c D d E e F f G g H h I i L l M m N n O o P p R r S s T t U u Á á É é Í í Ó ó Ú ú
15 | Italian A a B b C c D d E e F f G g H h I i L l M m N n O o P p Q q R r S s T t U u V v Z z à è é ì í ò ó ù ú
16 | Latvian A a Ā ā B b C c Č č D d E e Ē ē F f G g Ģ ģ H h I i Ī ī J j K k Ķ ķ L l Ļ ļ M m N n Ņ ņ O o P p R r S s Š š T t U u Ū ū V v Z z Ž ž
17 | Lithuanian A a Ą ą B b C c Č č D d E e Ę ę Ė ė F f G g H h I i Į į Y y J j K k L l M m N n O o P p R r S s Š š T t U u Ų ų Ū ū V v Z z Ž ž
18 | Luxembourgish A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z É é Ä ä Ë ë
19 | Maltese A a B b Ċ ċ D d E e F f Ġ ġ G g Għ għ H h Ħ ħ I i Ie ie J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Ż ż Z z
20 | Norwegian A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Æ æ Ø ø Å å
21 | Polish A a Ą ą B b C c Ć ć D d E e Ę ę F f G g H h I i J j K k L l Ł ł M m N n Ń ń O o Ó ó P p R r S s Ś ś T t U u W w Y y Z z Ź ź Ż ż
22 | Portuguese A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Á á À à Â â Ã ã Ç ç É é Ê ê Í í Ó ó Ô ô Õ õ Ú ú
23 | Romanian A a Ă ă Â â B b C c D d E e F f G g H h I i Î î J j K k L l M m N n O o P p Q q R r S s Ș ș T t Ț ț U u V v W w X x Y y Z z
24 | Slovak A a Á á Ä ä B b C c Č č D d Ď ď Dz dz Dž dž E e É é F f G g H h Ch ch I i Í í J j K k L l Ĺ ĺ Ľ ľ M m N n Ň ň O o Ó ó Ô ô P p Q q R r Ŕ ŕ S s Š š T t Ť ť U u Ú ú V v W w X x Y y Ý ý Z z Ž ž
25 | Slovenian A a B b C c Č č D d E e F f G g H h I i J j K k L l M m N n O o P p R r S s Š š T t U u V v Z z Ž ž
26 | Spanish A a B b C c D d E e F f G g H h I i J j K k L l M m N n Ñ ñ O o P p Q q R r S s T t U u V v W w X x Y y Z z Á á É é Í í Ó ó Ú ú Ü ü
27 | Swedish A a B b C c D d E e F f G g H h I i J j K k L l M m N n O o P p Q q R r S s T t U u V v W w X x Y y Z z Å å Ä ä Ö ö
28 | Turkish A a B b C c Ç ç D d E e F f G g Ğ ğ H h I ı İ i J j K k L l M m N n O o Ö ö P p R r S s Ş ş T t U u Ü ü V v Y y Z z
--------------------------------------------------------------------------------
/ch02/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 2 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | def _get_bias(avPair, dataRowIndexes, data, outcomeIndex):
19 | attrIndex, attrValue = avPair
20 | matchIndexes = {i for i in dataRowIndexes if
21 | data[i][attrIndex] == attrValue}
22 | nonMatchIndexes = dataRowIndexes - matchIndexes
23 | matchOutcomes = {data[i][outcomeIndex] for i in matchIndexes}
24 | nonMatchOutcomes = {data[i][outcomeIndex] for i in nonMatchIndexes}
25 | numPureRows = (len(matchIndexes) if len(matchOutcomes) == 1 else 0) \
26 | + (len(nonMatchIndexes) if len(nonMatchOutcomes) == 1
27 | else 0)
28 | percentPure = numPureRows / len(dataRowIndexes)
29 |
30 | numNonPureRows = len(dataRowIndexes) - numPureRows
31 | percentNonPure = 1 - percentPure
32 | split = 1 - abs(len(matchIndexes) - len(nonMatchIndexes)) / len(
33 | dataRowIndexes) - .001
34 | splitBias = split * percentNonPure if numNonPureRows > 0 else 0
35 | return splitBias + percentPure
36 |
37 |
38 | def build(data, outcomeLabel):
39 | attrIndexes = [index for index, label in enumerate(data[0]) if
40 | label != outcomeLabel]
41 | outcomeIndex = data[0].index(outcomeLabel)
42 |
43 | nodes = []
44 | lastNodeNumber = 0
45 |
46 | workQueue = [(-1, lastNodeNumber, set(i for i in range(1, len(data))))]
47 | while len(workQueue) > 0:
48 | parentNodeId, nodeId, dataRowIndexes = workQueue.pop()
49 | uniqueOutcomes = set(data[i][outcomeIndex] for i in dataRowIndexes)
50 | if len(uniqueOutcomes) == 1:
51 | nodes.append((nodeId, uniqueOutcomes.pop()))
52 | continue
53 | uniqueAttributeValuePairs = {(attrIndex, data[rowIndex][attrIndex])
54 | for attrIndex in attrIndexes
55 | for rowIndex in dataRowIndexes}
56 | potentials = sorted((-_get_bias(avPair, dataRowIndexes, data,
57 | outcomeIndex), avPair[0], avPair[1])
58 | for avPair in uniqueAttributeValuePairs)
59 | attrIndex, attrValue = potentials[0][1:]
60 | matches = {rowIndex for rowIndex in dataRowIndexes if
61 | data[rowIndex][attrIndex] == attrValue}
62 | nonMatches = dataRowIndexes - matches
63 | lastNodeNumber += 1
64 | matchId = lastNodeNumber
65 | workQueue.append((nodeId, matchId, matches))
66 | lastNodeNumber += 1
67 | nonMatchId = lastNodeNumber
68 | workQueue.append((nodeId, nonMatchId, nonMatches))
69 | nodes.append((nodeId, attrIndex, attrValue, matchId, nonMatchId,
70 | len(matches), len(nonMatches)))
71 | nodes = sorted(nodes, key=lambda n: n[0])
72 | return DTree(nodes, data[0])
73 |
74 |
75 | class DTree:
76 | def __init__(self, nodes, attrNames):
77 | self._nodes = nodes
78 | self._attrNames = attrNames
79 |
80 | @staticmethod
81 | def _is_leaf(node):
82 | return len(node) == 2
83 |
84 | def __str__(self):
85 | s = ''
86 | for node in self._nodes:
87 | if self._is_leaf(node):
88 | s += '{}: {}\n'.format(node[0], node[1])
89 | else:
90 | nodeId, attrIndex, attrValue, nodeIdIfMatch, \
91 | nodeIdIfNonMatch, matchCount, nonMatchCount = node
92 | s += '{0}: {1}={2}, {5} Yes->{3}, {6} No->{4}\n'.format(
93 | nodeId, self._attrNames[attrIndex], attrValue,
94 | nodeIdIfMatch, nodeIdIfNonMatch, matchCount,
95 | nonMatchCount)
96 | return s
97 |
98 | def get_prediction(self, data):
99 | currentNode = self._nodes[0]
100 | while True:
101 | if self._is_leaf(currentNode):
102 | return currentNode[1]
103 | nodeId, attrIndex, attrValue, nodeIdIfMatch, \
104 | nodeIdIfNonMatch = currentNode[:5]
105 | currentNode = self._nodes[nodeIdIfMatch if
106 | data[attrIndex] == attrValue else nodeIdIfNonMatch]
107 |
--------------------------------------------------------------------------------
/ch02/sample.txt:
--------------------------------------------------------------------------------
1 | štkýck ľudia učia radostné správ
--------------------------------------------------------------------------------
/ch02/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 2 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 |
20 | data = [['Name', 'Gender', 'Marital Status', 'Born'],
21 | ['William', 'male', 'Married', 'Germany'],
22 | ['Louise', 'female', 'Single', 'Texas'],
23 | ['Minnie', 'female', 'Single', 'Texas'],
24 | ['Emma', 'female', 'Single', 'Texas'],
25 | ['Henry', 'male', 'Single', 'Germany'],
26 | ['Theo', 'male', 'Single', 'Texas'],
27 | ]
28 |
29 | outcomeLabel = 'Born'
30 |
31 | tree = dtree.build(data, outcomeLabel)
32 | print(tree)
33 |
34 | testData = ['Sophie', 'female', 'Single']
35 | predicted = tree.get_prediction(testData)
36 | print("predicted: {}".format(predicted))
37 |
--------------------------------------------------------------------------------
/ch03/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 3 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from numbers import Number
19 | import operator
20 | import math
21 |
22 |
23 | def _get_bias(avPair, dataRowIndexes, data, outcomeIndex):
24 | attrIndex, attrValue, isMatch = avPair
25 | matchIndexes = {i for i in dataRowIndexes if
26 | isMatch(data[i][attrIndex], attrValue)}
27 | nonMatchIndexes = dataRowIndexes - matchIndexes
28 | matchOutcomes = {data[i][outcomeIndex] for i in matchIndexes}
29 | nonMatchOutcomes = {data[i][outcomeIndex] for i in nonMatchIndexes}
30 | numPureRows = (len(matchIndexes) if len(matchOutcomes) == 1 else 0) \
31 | + (len(nonMatchIndexes) if len(nonMatchOutcomes) == 1
32 | else 0)
33 | percentPure = numPureRows / len(dataRowIndexes)
34 |
35 | numNonPureRows = len(dataRowIndexes) - numPureRows
36 | percentNonPure = 1 - percentPure
37 | split = 1 - abs(len(matchIndexes) - len(nonMatchIndexes)) / len(
38 | dataRowIndexes) - .001
39 | splitBias = split * percentNonPure if numNonPureRows > 0 else 0
40 | return splitBias + percentPure
41 |
42 |
43 | def build(data, outcomeLabel, continuousAttributes=None):
44 | attrIndexes = [index for index, label in enumerate(data[0]) if
45 | label != outcomeLabel]
46 | outcomeIndex = data[0].index(outcomeLabel)
47 | continuousAttrIndexes = set()
48 | if continuousAttributes is not None:
49 | continuousAttrIndexes = {data[0].index(label) for label in
50 | continuousAttributes}
51 | if len(continuousAttrIndexes) != len(continuousAttributes):
52 | raise Exception(
53 | 'One or more continuous column names are duplicates.')
54 | else:
55 | for attrIndex in attrIndexes:
56 | uniqueValues = {row[attrIndex] for rowIndex, row in
57 | enumerate(data) if rowIndex > 0}
58 | numericValues = {value for value in uniqueValues if
59 | isinstance(value, Number)}
60 | if len(uniqueValues) == len(numericValues):
61 | continuousAttrIndexes.add(attrIndex)
62 |
63 | nodes = []
64 | lastNodeNumber = 0
65 |
66 | workQueue = [(-1, lastNodeNumber, set(i for i in range(1, len(data))))]
67 | while len(workQueue) > 0:
68 | parentNodeId, nodeId, dataRowIndexes = workQueue.pop()
69 | uniqueOutcomes = set(data[i][outcomeIndex] for i in dataRowIndexes)
70 | if len(uniqueOutcomes) == 1:
71 | nodes.append((nodeId, uniqueOutcomes.pop()))
72 | continue
73 | potentials = _get_potentials(attrIndexes, continuousAttrIndexes,
74 | data, dataRowIndexes, outcomeIndex)
75 | attrIndex, attrValue, isMatch = potentials[0][1:]
76 | matches = {rowIndex for rowIndex in dataRowIndexes if
77 | isMatch(data[rowIndex][attrIndex], attrValue)}
78 | nonMatches = dataRowIndexes - matches
79 | lastNodeNumber += 1
80 | matchId = lastNodeNumber
81 | workQueue.append((nodeId, matchId, matches))
82 | lastNodeNumber += 1
83 | nonMatchId = lastNodeNumber
84 | workQueue.append((nodeId, nonMatchId, nonMatches))
85 | nodes.append((nodeId, attrIndex, attrValue, isMatch, matchId,
86 | nonMatchId, len(matches), len(nonMatches)))
87 | nodes = sorted(nodes, key=lambda n: n[0])
88 | return DTree(nodes, data[0])
89 |
90 |
91 | def _get_potentials(attrIndexes, continuousAttrIndexes, data,
92 | dataRowIndexes, outcomeIndex):
93 | uniqueAttributeValuePairs = {
94 | (attrIndex, data[rowIndex][attrIndex], operator.eq)
95 | for attrIndex in attrIndexes
96 | if attrIndex not in continuousAttrIndexes
97 | for rowIndex in dataRowIndexes}
98 | continuousAttributeValuePairs = _get_continuous_av_pairs(
99 | continuousAttrIndexes, data, dataRowIndexes)
100 | uniqueAttributeValuePairs |= continuousAttributeValuePairs
101 | potentials = sorted((-_get_bias(avPair, dataRowIndexes, data,
102 | outcomeIndex),
103 | avPair[0], avPair[1], avPair[2])
104 | for avPair in uniqueAttributeValuePairs)
105 | return potentials
106 |
107 |
108 | def _get_continuous_av_pairs(continuousAttrIndexes, data, dataRowIndexes):
109 | avPairs = set()
110 | for attrIndex in continuousAttrIndexes:
111 | sortedAttrValues = [i for i in sorted(
112 | data[rowIndex][attrIndex] for rowIndex in dataRowIndexes)]
113 | indexes = _get_discontinuity_indexes(
114 | sortedAttrValues,
115 | max(math.sqrt(
116 | len(sortedAttrValues)),
117 | min(10,
118 | len(sortedAttrValues))))
119 | for index in indexes:
120 | avPairs.add((attrIndex, sortedAttrValues[index], operator.gt))
121 | return avPairs
122 |
123 |
124 | def _get_discontinuity_indexes(sortedAttrValues, maxIndexes):
125 | indexes = []
126 | for i in _generate_discontinuity_indexes_center_out(sortedAttrValues):
127 | indexes.append(i)
128 | if len(indexes) >= maxIndexes:
129 | break
130 | return indexes
131 |
132 |
133 | def _generate_discontinuity_indexes_center_out(sortedAttrValues):
134 | center = len(sortedAttrValues) // 2
135 | left = center - 1
136 | right = center + 1
137 | while left >= 0 or right < len(sortedAttrValues):
138 | if left >= 0:
139 | if sortedAttrValues[left] != sortedAttrValues[left + 1]:
140 | yield left
141 | left -= 1
142 | if right < len(sortedAttrValues):
143 | if sortedAttrValues[right - 1] != sortedAttrValues[right]:
144 | yield right - 1
145 | right += 1
146 |
147 |
148 | class DTree:
149 | def __init__(self, nodes, attrNames):
150 | self._nodes = nodes
151 | self._attrNames = attrNames
152 |
153 | @staticmethod
154 | def _is_leaf(node):
155 | return len(node) == 2
156 |
157 | def __str__(self):
158 | s = ''
159 | for node in self._nodes:
160 | if self._is_leaf(node):
161 | s += '{}: {}\n'.format(node[0], node[1])
162 | else:
163 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
164 | nodeIdIfNonMatch, matchCount, nonMatchCount = node
165 | s += '{0}: {1}{7}{2}, {5} Yes->{3}, {6} No->{4}\n'.format(
166 | nodeId, self._attrNames[attrIndex], attrValue,
167 | nodeIdIfMatch, nodeIdIfNonMatch, matchCount,
168 | nonMatchCount, '=' if isMatch == operator.eq else '>')
169 | return s
170 |
171 | def get_prediction(self, data):
172 | currentNode = self._nodes[0]
173 | while True:
174 | if self._is_leaf(currentNode):
175 | return currentNode[1]
176 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
177 | nodeIdIfNonMatch = currentNode[:6]
178 | currentNode = self._nodes[nodeIdIfMatch if
179 | isMatch(data[attrIndex], attrValue) else nodeIdIfNonMatch]
180 |
--------------------------------------------------------------------------------
/ch03/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 3 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 |
20 | data = [['Name', 'Gender', 'Marital Status', 'Age', 'Born'],
21 | ['William', 'male', 'Married', 37, 'Germany'],
22 | ['Louise', 'female', 'Single', 18, 'Germany'],
23 | ['Minnie', 'female', 'Single', 16, 'Texas'],
24 | ['Emma', 'female', 'Single', 14, 'Texas'],
25 | ['Henry', 'male', 'Married', 47, 'Germany'],
26 | ['Theo', 'male', 'Single', 17, 'Texas'],
27 | ]
28 |
29 | outcomeLabel = 'Born'
30 |
31 | tree = dtree.build(data, outcomeLabel)
32 | print(tree)
33 |
34 | testData = ['Sophie', 'female', 'Single', 17]
35 | predicted = tree.get_prediction(testData)
36 | print("predicted: {}".format(predicted))
37 |
--------------------------------------------------------------------------------
/ch04/census.csv:
--------------------------------------------------------------------------------
1 | Name,Gender,Marital Status,Age,Relationship,Born
2 | August,male,Married,32,Head,Germany
3 | Minnie,female,Married,28,Wife,Texas
4 | Emma,female,Single,9,Daughter,Texas
5 | Theo,male,Single,3,Son,Texas
6 | William,male,Married,37,Head,Germany
7 | Sophie,female,Married,22,Wife,Germany
8 | Louise,female,Single,4,Daughter,Texas
9 | Minnie,female,Single,2,Daughter,Texas
10 | Emma,female,Single,1,Daughter,Texas
11 | Henry,male,Married,33,Head,Germany
12 | Henrietta,female,Married,28,Wife,Germany
13 | Henry,male,Single,9,Son,Texas
14 | Frank,male,Single,7,Son,Texas
15 | Hermann,male,Single,4,Son,Texas
16 | Louise,female,Single,3,Daughter,Texas
17 | Charles,male,Single,1,Son,Texas
18 | Hermann,male,Married,39,Head,Germany
19 | Dora,female,Married,31,Wife,Germany
20 | Hennie,female,Single,8,Daughter,Texas
21 | Lisette,female,Single,5,Daughter,Texas
22 | Fritz,male,Single,3,Son,Texas
23 | Minnie,female,Single,3,Daughter,Texas
24 | Charles,male,Married,68,Head,Germany
25 | Louise,female,Married,64,Wife,Germany
26 | Katie,female,Single,21,Daughter,Germany
27 | Charles,male,Single,18,Son,Germany
28 | Henry,male,Single,2,Nephew,Texas
29 | Horace,male,Married,27,Head,Texas
30 | Lucy,female,Married,25,Wife,Texas
31 | Henry,male,Married,61,Head,Germany
32 | Louise,female,Married,51,Wife,Germany
33 | Fritz,male,Single,18,Son,Germany
34 | Otto,male,Single,16,Son,Texas
35 | Bertha,female,Single,15,Daughter,Texas
36 | Nathlie,female,Single,10,Daughter,Texas
37 | Elsa,female,Single,8,Daughter,Texas
38 | August,male,Single,6,Son,Texas
39 | Henry,male,Single,2,Nephew,Texas
40 | William,male,Married,66,Head,Germany
41 | Minnie,female,Married,89,Wife,Germany
42 | Hermann,male,Married,43,Head,Germany
43 | Emily,female,Married,47,Wife,Germany
44 | Henry,male,Single,19,Son,Texas
45 | Olga,female,Single,18,Daughter,Texas
46 | Paul,male,Single,16,Son,Texas
47 | Ernst,male,Single,15,Son,Texas
48 | Emil,male,Single,12,Son,Texas
49 | Ed,male,Single,11,Son,Texas
50 | Otto,male,Single,9,Son,Texas
51 | Ella,female,Single,7,Daughter,Texas
52 | William,male,Married,47,Head,Germany
53 | Emily,female,Married,42,Wife,Germany
54 | Lena,female,Single,15,Daughter,Texas
55 | Christian,male,Single,14,Son,Texas
56 | Bertha,female,Single,12,Daughter,Texas
57 | Ella,female,Single,9,Daughter,Texas
58 | Mollie,female,Single,6,Daughter,Texas
59 | Hettie,female,Single,1,Daughter,Texas
--------------------------------------------------------------------------------
/ch04/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 4 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 | from numbers import Number
20 | import operator
21 | import math
22 | import csv
23 | import random
24 |
25 |
26 | def _get_bias(avPair, dataRowIndexes, data, outcomeIndex, minimumSubsetSize,
27 | validationRowIndexes):
28 | attrIndex, attrValue, isMatch = avPair
29 | if len(validationRowIndexes) > 0:
30 | validationMatchIndexes = {i for i in validationRowIndexes if
31 | isMatch(data[i][attrIndex], attrValue)}
32 | validationNonMatchIndexes = validationRowIndexes - \
33 | validationMatchIndexes
34 | if len(validationMatchIndexes) == 0 or len(
35 | validationNonMatchIndexes) == 0:
36 | return -2
37 | matchIndexes = {i for i in dataRowIndexes if
38 | isMatch(data[i][attrIndex], attrValue)}
39 | nonMatchIndexes = dataRowIndexes - matchIndexes
40 | if len(matchIndexes) < minimumSubsetSize or len(
41 | nonMatchIndexes) < minimumSubsetSize:
42 | return -1
43 | matchOutcomes = {data[i][outcomeIndex] for i in matchIndexes}
44 | nonMatchOutcomes = {data[i][outcomeIndex] for i in nonMatchIndexes}
45 | numPureRows = (len(matchIndexes) if len(matchOutcomes) == 1 else 0) \
46 | + (len(nonMatchIndexes) if len(nonMatchOutcomes) == 1
47 | else 0)
48 | percentPure = numPureRows / len(dataRowIndexes)
49 |
50 | numNonPureRows = len(dataRowIndexes) - numPureRows
51 | percentNonPure = 1 - percentPure
52 | split = 1 - abs(len(matchIndexes) - len(nonMatchIndexes)) / len(
53 | dataRowIndexes) - .001
54 | splitBias = split * percentNonPure if numNonPureRows > 0 else 0
55 | return splitBias + percentPure
56 |
57 |
58 | def build(data, outcomeLabel, continuousAttributes=None,
59 | minimumSubsetSizePercentage=0, validationPercentage=0):
60 | if validationPercentage > 0:
61 | validationPercentage /= 100
62 | validationCount = int(validationPercentage * len(data))
63 | if minimumSubsetSizePercentage > 0:
64 | minimumSubsetSizePercentage /= 100
65 | minimumSubsetSize = int(minimumSubsetSizePercentage * len(data))
66 | attrIndexes = [index for index, label in enumerate(data[0]) if
67 | label != outcomeLabel]
68 | outcomeIndex = data[0].index(outcomeLabel)
69 | continuousAttrIndexes = set()
70 | if continuousAttributes is not None:
71 | continuousAttrIndexes = {data[0].index(label) for label in
72 | continuousAttributes}
73 | if len(continuousAttrIndexes) != len(continuousAttributes):
74 | raise Exception(
75 | 'One or more continuous column names are duplicates.')
76 | else:
77 | for attrIndex in attrIndexes:
78 | uniqueValues = {row[attrIndex] for rowIndex, row in
79 | enumerate(data) if rowIndex > 0}
80 | numericValues = {value for value in uniqueValues if
81 | isinstance(value, Number)}
82 | if len(uniqueValues) == len(numericValues):
83 | continuousAttrIndexes.add(attrIndex)
84 |
85 | nodes = []
86 | lastNodeNumber = 0
87 | dataIndexes = {i for i in range(1, len(data))}
88 | validationIndexes = set()
89 | if validationCount > 0:
90 | validationIndexes = set(
91 | random.sample(range(1, len(data)), validationCount))
92 | dataIndexes -= validationIndexes
93 | workQueue = [(-1, lastNodeNumber, dataIndexes, validationIndexes)]
94 | while len(workQueue) > 0:
95 | parentNodeId, nodeId, dataRowIndexes, validationRowIndexes = \
96 | workQueue.pop()
97 | uniqueOutcomes = Counter(
98 | data[i][outcomeIndex] for i in dataRowIndexes).most_common()
99 | if len(uniqueOutcomes) == 1:
100 | nodes.append((nodeId, uniqueOutcomes.pop(0)[0]))
101 | continue
102 | potentials = _get_potentials(attrIndexes, continuousAttrIndexes,
103 | data, dataRowIndexes, outcomeIndex,
104 | minimumSubsetSize,
105 | validationRowIndexes)
106 | if len(potentials) == 0 or potentials[0][0] > 0:
107 | nodes.append((nodeId, [(n[0], n[1] / len(dataRowIndexes))
108 | for n in uniqueOutcomes]))
109 | continue
110 | attrIndex, attrValue, isMatch = potentials[0][1:]
111 | matches = {rowIndex for rowIndex in dataRowIndexes if
112 | isMatch(data[rowIndex][attrIndex], attrValue)}
113 | nonMatches = dataRowIndexes - matches
114 | validationMatches = {
115 | rowIndex for rowIndex in validationRowIndexes if
116 | isMatch(data[rowIndex][attrIndex], attrValue)}
117 | nonValidationMatches = validationRowIndexes - validationMatches
118 | lastNodeNumber += 1
119 | matchId = lastNodeNumber
120 | workQueue.append((nodeId, matchId, matches, validationMatches))
121 | lastNodeNumber += 1
122 | nonMatchId = lastNodeNumber
123 | workQueue.append((nodeId, nonMatchId, nonMatches,
124 | nonValidationMatches))
125 | nodes.append((nodeId, attrIndex, attrValue, isMatch, matchId,
126 | nonMatchId, len(matches), len(nonMatches)))
127 | nodes = sorted(nodes, key=lambda n: n[0])
128 | return DTree(nodes, data[0])
129 |
130 |
131 | def _get_potentials(attrIndexes, continuousAttrIndexes, data,
132 | dataRowIndexes, outcomeIndex, minimumSubsetSize,
133 | validationRowIndexes):
134 | uniqueAttributeValuePairs = {
135 | (attrIndex, data[rowIndex][attrIndex], operator.eq)
136 | for attrIndex in attrIndexes
137 | if attrIndex not in continuousAttrIndexes
138 | for rowIndex in dataRowIndexes}
139 | continuousAttributeValuePairs = _get_continuous_av_pairs(
140 | continuousAttrIndexes, data, dataRowIndexes)
141 | uniqueAttributeValuePairs |= continuousAttributeValuePairs
142 | potentials = sorted((-_get_bias(avPair, dataRowIndexes, data,
143 | outcomeIndex, minimumSubsetSize,
144 | validationRowIndexes),
145 | avPair[0], avPair[1], avPair[2])
146 | for avPair in uniqueAttributeValuePairs)
147 | return potentials
148 |
149 | def _get_continuous_av_pairs(continuousAttrIndexes, data, dataRowIndexes):
150 | avPairs = set()
151 | for attrIndex in continuousAttrIndexes:
152 | sortedAttrValues = [i for i in sorted(
153 | data[rowIndex][attrIndex] for rowIndex in dataRowIndexes)]
154 | indexes = _get_discontinuity_indexes(
155 | sortedAttrValues,
156 | max(math.sqrt(
157 | len(sortedAttrValues)),
158 | min(10,
159 | len(sortedAttrValues))))
160 | for index in indexes:
161 | avPairs.add((attrIndex, sortedAttrValues[index], operator.gt))
162 | return avPairs
163 |
164 |
165 | def _get_discontinuity_indexes(sortedAttrValues, maxIndexes):
166 | indexes = []
167 | for i in _generate_discontinuity_indexes_center_out(sortedAttrValues):
168 | indexes.append(i)
169 | if len(indexes) >= maxIndexes:
170 | break
171 | return indexes
172 |
173 |
174 | def _generate_discontinuity_indexes_center_out(sortedAttrValues):
175 | center = len(sortedAttrValues) // 2
176 | left = center - 1
177 | right = center + 1
178 | while left >= 0 or right < len(sortedAttrValues):
179 | if left >= 0:
180 | if sortedAttrValues[left] != sortedAttrValues[left + 1]:
181 | yield left
182 | left -= 1
183 | if right < len(sortedAttrValues):
184 | if sortedAttrValues[right - 1] != sortedAttrValues[right]:
185 | yield right - 1
186 | right += 1
187 |
188 |
189 | def read_csv(filepath):
190 | with open(filepath, 'r') as f:
191 | reader = csv.reader(f)
192 | data = list(reader)
193 | return data
194 |
195 |
196 | def prepare_data(data, numericColumnLabels=None):
197 | if numericColumnLabels is not None and len(numericColumnLabels) > 0:
198 | numericColumnIndexes = [data[0].index(label) for label in
199 | numericColumnLabels]
200 | for rowIndex, row in enumerate(data):
201 | if rowIndex == 0:
202 | continue
203 | for numericIndex in numericColumnIndexes:
204 | f = float(data[rowIndex][numericIndex]) if len(
205 | data[rowIndex][numericIndex]) > 0 else 0
206 | i = int(f)
207 | data[rowIndex][numericIndex] = i if i == f else f
208 | return data
209 |
210 |
211 | class DTree:
212 | def __init__(self, nodes, attrNames):
213 | self._nodes = nodes
214 | self._attrNames = attrNames
215 |
216 | @staticmethod
217 | def _is_leaf(node):
218 | return len(node) == 2
219 |
220 | def __str__(self):
221 | s = ''
222 | for node in self._nodes:
223 | if self._is_leaf(node):
224 | s += '{}: {}\n'.format(node[0], node[1])
225 | else:
226 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
227 | nodeIdIfNonMatch, matchCount, nonMatchCount = node
228 | s += '{0}: {1}{7}{2}, {5} Yes->{3}, {6} No->{4}\n'.format(
229 | nodeId, self._attrNames[attrIndex], attrValue,
230 | nodeIdIfMatch, nodeIdIfNonMatch, matchCount,
231 | nonMatchCount, '=' if isMatch == operator.eq else '>')
232 | return s
233 |
234 | def get_prediction(self, data):
235 | currentNode = self._nodes[0]
236 | while True:
237 | if self._is_leaf(currentNode):
238 | node = currentNode[1]
239 | if type(node) is not list:
240 | return node
241 | randPercent = random.uniform(0, 1)
242 | total = 0
243 | for outcome, percentage in node:
244 | total += percentage
245 | if total > randPercent:
246 | return outcome
247 | return node[-1][0]
248 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
249 | nodeIdIfNonMatch = currentNode[:6]
250 | currentNode = self._nodes[nodeIdIfMatch if
251 | isMatch(data[attrIndex], attrValue) else nodeIdIfNonMatch]
252 |
--------------------------------------------------------------------------------
/ch04/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 4 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 |
20 | data = dtree.read_csv('census.csv')
21 | data = dtree.prepare_data(data, ['Age'])
22 |
23 | outcomeLabel = 'Born'
24 |
25 | tree = dtree.build(data, outcomeLabel, validationPercentage=6)
26 | print(tree)
27 |
28 | testData = ['Elizabeth', 'female', 'Married', 19, 'Daughter']
29 | predicted = tree.get_prediction(testData)
30 | print("predicted: {}".format(predicted))
31 |
--------------------------------------------------------------------------------
/ch05/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 5 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 | from numbers import Number
20 | import operator
21 | import math
22 | import csv
23 | import random
24 |
25 |
26 | def _get_bias(avPair, dataRowIndexes, data, outcomeIndex, minimumSubsetSize,
27 | validationRowIndexes):
28 | attrIndex, attrValue, isMatch = avPair
29 | if len(validationRowIndexes) > 0:
30 | validationMatchIndexes = {i for i in validationRowIndexes if
31 | isMatch(data[i][attrIndex], attrValue)}
32 | validationNonMatchIndexes = validationRowIndexes - \
33 | validationMatchIndexes
34 | if len(validationMatchIndexes) == 0 or len(
35 | validationNonMatchIndexes) == 0:
36 | return -2
37 | matchIndexes = {i for i in dataRowIndexes if
38 | isMatch(data[i][attrIndex], attrValue)}
39 | nonMatchIndexes = dataRowIndexes - matchIndexes
40 | if len(matchIndexes) < minimumSubsetSize or len(
41 | nonMatchIndexes) < minimumSubsetSize:
42 | return -1
43 | matchOutcomes = {data[i][outcomeIndex] for i in matchIndexes}
44 | nonMatchOutcomes = {data[i][outcomeIndex] for i in nonMatchIndexes}
45 | numPureRows = (len(matchIndexes) if len(matchOutcomes) == 1 else 0) \
46 | + (len(nonMatchIndexes) if len(nonMatchOutcomes) == 1
47 | else 0)
48 | percentPure = numPureRows / len(dataRowIndexes)
49 |
50 | numNonPureRows = len(dataRowIndexes) - numPureRows
51 | percentNonPure = 1 - percentPure
52 | split = 1 - abs(len(matchIndexes) - len(nonMatchIndexes)) / len(
53 | dataRowIndexes) - .001
54 | splitBias = split * percentNonPure if numNonPureRows > 0 else 0
55 | return splitBias + percentPure
56 |
57 |
58 | def build(data, outcomeLabel, continuousAttributes=None,
59 | minimumSubsetSizePercentage=0, validationPercentage=0,
60 | dataIndexes=None, attrIndexes=None):
61 | if validationPercentage > 0:
62 | validationPercentage /= 100
63 | validationCount = int(validationPercentage *
64 | (len(data) if dataIndexes is None else len(
65 | dataIndexes)))
66 | if minimumSubsetSizePercentage > 0:
67 | minimumSubsetSizePercentage /= 100
68 | minimumSubsetSize = int(minimumSubsetSizePercentage *
69 | (len(data) if dataIndexes is None else len(
70 | dataIndexes)))
71 | if attrIndexes is None:
72 | attrIndexes = [index for index, label in enumerate(data[0]) if
73 | label != outcomeLabel]
74 | outcomeIndex = data[0].index(outcomeLabel)
75 | continuousAttrIndexes = set()
76 | if continuousAttributes is not None:
77 | continuousAttrIndexes = {data[0].index(label) for label in
78 | continuousAttributes}
79 | if len(continuousAttrIndexes) != len(continuousAttributes):
80 | raise Exception(
81 | 'One or more continuous column names are duplicates.')
82 | else:
83 | for attrIndex in attrIndexes:
84 | uniqueValues = {row[attrIndex] for rowIndex, row in
85 | enumerate(data) if rowIndex > 0}
86 | numericValues = {value for value in uniqueValues if
87 | isinstance(value, Number)}
88 | if len(uniqueValues) == len(numericValues):
89 | continuousAttrIndexes.add(attrIndex)
90 |
91 | nodes = []
92 | lastNodeNumber = 0
93 | if dataIndexes is None:
94 | dataIndexes = {i for i in range(1, len(data))}
95 | elif not isinstance(dataIndexes, set):
96 | dataIndexes = {i for i in dataIndexes}
97 | validationIndexes = set()
98 | if validationCount > 0:
99 | validationIndexes = set(
100 | random.sample([i for i in dataIndexes], validationCount))
101 | dataIndexes -= validationIndexes
102 | workQueue = [(-1, lastNodeNumber, dataIndexes, validationIndexes)]
103 | while len(workQueue) > 0:
104 | parentNodeId, nodeId, dataRowIndexes, validationRowIndexes = \
105 | workQueue.pop()
106 | uniqueOutcomes = Counter(
107 | data[i][outcomeIndex] for i in dataRowIndexes).most_common()
108 | if len(uniqueOutcomes) == 1:
109 | nodes.append((nodeId, uniqueOutcomes.pop(0)[0]))
110 | continue
111 | potentials = _get_potentials(attrIndexes, continuousAttrIndexes,
112 | data, dataRowIndexes, outcomeIndex,
113 | minimumSubsetSize,
114 | validationRowIndexes)
115 | if len(potentials) == 0 or potentials[0][0] > 0:
116 | nodes.append((nodeId, [(n[0], n[1] / len(dataRowIndexes))
117 | for n in uniqueOutcomes]))
118 | continue
119 | attrIndex, attrValue, isMatch = potentials[0][1:]
120 | matches = {rowIndex for rowIndex in dataRowIndexes if
121 | isMatch(data[rowIndex][attrIndex], attrValue)}
122 | nonMatches = dataRowIndexes - matches
123 | validationMatches = {
124 | rowIndex for rowIndex in validationRowIndexes if
125 | isMatch(data[rowIndex][attrIndex], attrValue)}
126 | nonValidationMatches = validationRowIndexes - validationMatches
127 | lastNodeNumber += 1
128 | matchId = lastNodeNumber
129 | workQueue.append((nodeId, matchId, matches, validationMatches))
130 | lastNodeNumber += 1
131 | nonMatchId = lastNodeNumber
132 | workQueue.append((nodeId, nonMatchId, nonMatches,
133 | nonValidationMatches))
134 | nodes.append((nodeId, attrIndex, attrValue, isMatch, matchId,
135 | nonMatchId, len(matches), len(nonMatches)))
136 | nodes = sorted(nodes, key=lambda n: n[0])
137 | return DTree(nodes, data[0])
138 |
139 |
140 | def _get_potentials(attrIndexes, continuousAttrIndexes, data,
141 | dataRowIndexes, outcomeIndex, minimumSubsetSize,
142 | validationRowIndexes):
143 | uniqueAttributeValuePairs = {
144 | (attrIndex, data[rowIndex][attrIndex], operator.eq)
145 | for attrIndex in attrIndexes
146 | if attrIndex not in continuousAttrIndexes
147 | for rowIndex in dataRowIndexes}
148 | continuousAttributeValuePairs = _get_continuous_av_pairs(
149 | continuousAttrIndexes, data, dataRowIndexes)
150 | uniqueAttributeValuePairs |= continuousAttributeValuePairs
151 | potentials = sorted((-_get_bias(avPair, dataRowIndexes, data,
152 | outcomeIndex, minimumSubsetSize,
153 | validationRowIndexes),
154 | avPair[0], avPair[1], avPair[2])
155 | for avPair in uniqueAttributeValuePairs)
156 | return potentials
157 |
158 | def _get_continuous_av_pairs(continuousAttrIndexes, data, dataRowIndexes):
159 | avPairs = set()
160 | for attrIndex in continuousAttrIndexes:
161 | sortedAttrValues = [i for i in sorted(
162 | data[rowIndex][attrIndex] for rowIndex in dataRowIndexes)]
163 | indexes = _get_discontinuity_indexes(
164 | sortedAttrValues,
165 | max(math.sqrt(
166 | len(sortedAttrValues)),
167 | min(10,
168 | len(sortedAttrValues))))
169 | for index in indexes:
170 | avPairs.add((attrIndex, sortedAttrValues[index], operator.gt))
171 | return avPairs
172 |
173 |
174 | def _get_discontinuity_indexes(sortedAttrValues, maxIndexes):
175 | indexes = []
176 | for i in _generate_discontinuity_indexes_center_out(sortedAttrValues):
177 | indexes.append(i)
178 | if len(indexes) >= maxIndexes:
179 | break
180 | return indexes
181 |
182 |
183 | def _generate_discontinuity_indexes_center_out(sortedAttrValues):
184 | center = len(sortedAttrValues) // 2
185 | left = center - 1
186 | right = center + 1
187 | while left >= 0 or right < len(sortedAttrValues):
188 | if left >= 0:
189 | if sortedAttrValues[left] != sortedAttrValues[left + 1]:
190 | yield left
191 | left -= 1
192 | if right < len(sortedAttrValues):
193 | if sortedAttrValues[right - 1] != sortedAttrValues[right]:
194 | yield right - 1
195 | right += 1
196 |
197 |
198 | def read_csv(filepath):
199 | with open(filepath, 'r') as f:
200 | reader = csv.reader(f)
201 | data = list(reader)
202 | return data
203 |
204 |
205 | def prepare_data(data, numericColumnLabels=None):
206 | if numericColumnLabels is not None and len(numericColumnLabels) > 0:
207 | numericColumnIndexes = [data[0].index(label) for label in
208 | numericColumnLabels]
209 | for rowIndex, row in enumerate(data):
210 | if rowIndex == 0:
211 | continue
212 | for numericIndex in numericColumnIndexes:
213 | f = float(data[rowIndex][numericIndex]) if len(
214 | data[rowIndex][numericIndex]) > 0 else 0
215 | i = int(f)
216 | data[rowIndex][numericIndex] = i if i == f else f
217 | return data
218 |
219 |
220 | class DTree:
221 | def __init__(self, nodes, attrNames):
222 | self._nodes = nodes
223 | self._attrNames = attrNames
224 |
225 | @staticmethod
226 | def _is_leaf(node):
227 | return len(node) == 2
228 |
229 | def __str__(self):
230 | s = ''
231 | for node in self._nodes:
232 | if self._is_leaf(node):
233 | s += '{}: {}\n'.format(node[0], node[1])
234 | else:
235 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
236 | nodeIdIfNonMatch, matchCount, nonMatchCount = node
237 | s += '{0}: {1}{7}{2}, {5} Yes->{3}, {6} No->{4}\n'.format(
238 | nodeId, self._attrNames[attrIndex], attrValue,
239 | nodeIdIfMatch, nodeIdIfNonMatch, matchCount,
240 | nonMatchCount, '=' if isMatch == operator.eq else '>')
241 | return s
242 |
243 | def get_prediction(self, data):
244 | currentNode = self._nodes[0]
245 | while True:
246 | if self._is_leaf(currentNode):
247 | node = currentNode[1]
248 | if type(node) is not list:
249 | return node
250 | randPercent = random.uniform(0, 1)
251 | total = 0
252 | for outcome, percentage in node:
253 | total += percentage
254 | if total > randPercent:
255 | return outcome
256 | return node[-1][0]
257 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
258 | nodeIdIfNonMatch = currentNode[:6]
259 | currentNode = self._nodes[nodeIdIfMatch if
260 | isMatch(data[attrIndex], attrValue) else nodeIdIfNonMatch]
261 |
--------------------------------------------------------------------------------
/ch05/forest.py:
--------------------------------------------------------------------------------
1 | # File: forest.py
2 | # from chapter 5 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 | import dtree
20 | import math
21 | import random
22 | import statistics
23 |
24 |
25 | class Forest:
26 | def __init__(self, data, outcomeLabel, continuousAttributes=None,
27 | dataRowIndexes=None, columnsNamesToIgnore=None):
28 | self.data = data
29 | self.outcomeLabel = outcomeLabel
30 | self.continuousAttributes = continuousAttributes \
31 | if columnsNamesToIgnore is None \
32 | else [i for i in continuousAttributes if
33 | i not in columnsNamesToIgnore]
34 | self.numRows = math.ceil(math.sqrt(
35 | len(data) if dataRowIndexes is None else len(dataRowIndexes)))
36 | self.outcomeIndex = data[0].index(outcomeLabel)
37 | columnIdsToIgnore = set() if columnsNamesToIgnore is None else set(
38 | data[0].index(s) for s in columnsNamesToIgnore)
39 | columnIdsToIgnore.add(self.outcomeIndex)
40 | self.attrIndexesExceptOutcomeIndex = [i for i in range(0, len(data[0]))
41 | if i not in columnIdsToIgnore]
42 | self.numAttributes = math.ceil(
43 | math.sqrt(len(self.attrIndexesExceptOutcomeIndex)))
44 | self.dataRowIndexes = range(1, len(
45 | data)) if dataRowIndexes is None else dataRowIndexes
46 | self.numTrees = 200
47 | self.populate()
48 |
49 | def _build_tree(self):
50 | return dtree.build(self.data, self.outcomeLabel,
51 | continuousAttributes=self.continuousAttributes,
52 | dataIndexes={i for i in random.sample(
53 | self.dataRowIndexes, self.numRows)},
54 | attrIndexes=[
55 | i for i in random.sample(
56 | self.attrIndexesExceptOutcomeIndex,
57 | self.numAttributes)])
58 |
59 | def populate(self):
60 | self._trees = [self._build_tree() for _ in range(0, self.numTrees)]
61 |
62 | def get_prediction(self, dataItem):
63 | sorted_predictions = self._get_predictions(dataItem)
64 | return sorted_predictions[0][0]
65 |
66 | def _get_predictions(self, dataItem):
67 | predictions = [t.get_prediction(dataItem) for t in self._trees]
68 | return Counter(p for p in predictions).most_common()
69 |
70 |
71 | class Benchmark:
72 | @staticmethod
73 | def run(f):
74 | results = []
75 | for i in range(100):
76 | result = f()
77 | results.append(result)
78 | if i < 10 or i % 10 == 9:
79 | mean = statistics.mean(results)
80 | print("{} {:3.2f} {:3.2f}".format(
81 | 1 + i, mean,
82 | statistics.stdev(results, mean) if i > 1 else 0))
--------------------------------------------------------------------------------
/ch05/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 5 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 | from forest import Forest
20 | import dtree
21 |
22 |
23 | data = dtree.read_csv('..\ch04\census.csv')
24 | continuousColumns = ['Age']
25 | data = dtree.prepare_data(data, continuousColumns)
26 | outcomeLabel = 'Born'
27 |
28 | forest = Forest(data, outcomeLabel, continuousColumns)
29 | testData = ['Elizabeth', 'female', 'Married', 16, 'Daughter']
30 | predicted = forest.get_prediction(testData)
31 | print("predicted: {}".format(predicted))
32 |
33 | forest = Forest(data, outcomeLabel, continuousColumns)
34 | predictions = []
35 | for _ in range(0, 100):
36 | predictions.append(forest.get_prediction(testData))
37 | forest.populate()
38 | counts = Counter(predictions)
39 | print("predictions: {}".format(counts.most_common()))
--------------------------------------------------------------------------------
/ch05/titanic.py:
--------------------------------------------------------------------------------
1 | # File: titanic.py
2 | # from chapter 5 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from forest import Forest
19 | from forest import Benchmark
20 | import dtree
21 | import random
22 |
23 |
24 | continuousColumns = ['PassengerId', 'Pclass', 'Age', 'SibSp', 'Parch', 'Fare']
25 | data = dtree.read_csv('train.csv')
26 | data = dtree.prepare_data(data, continuousColumns)
27 | outcomeLabel = 'Survived'
28 | columnsToIgnore = ['PassengerId', 'Name', 'Ticket', 'Cabin']
29 |
30 |
31 | def predict():
32 | trainingRowIds = random.sample(range(1, len(data)), int(.8 * len(data)))
33 | forest = Forest(data, outcomeLabel, continuousColumns, trainingRowIds, columnsToIgnore)
34 | correct = sum(1 for rowId, row in enumerate(data) if
35 | rowId > 0 and
36 | rowId not in trainingRowIds and
37 | forest.get_prediction(row) == row[1])
38 | return 100 * correct / (len(data) - 1 - len(trainingRowIds))
39 |
40 | Benchmark.run(predict)
--------------------------------------------------------------------------------
/ch06/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 6 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 | from numbers import Number
20 | import operator
21 | import math
22 | import csv
23 | import random
24 |
25 |
26 | def _get_bias(avPair, dataRowIndexes, data, outcomeIndex, minimumSubsetSize,
27 | validationRowIndexes):
28 | attrIndex, attrValue, isMatch = avPair
29 | if len(validationRowIndexes) > 0:
30 | validationMatchIndexes = {i for i in validationRowIndexes if
31 | isMatch(data[i][attrIndex], attrValue)}
32 | validationNonMatchIndexes = validationRowIndexes - \
33 | validationMatchIndexes
34 | if len(validationMatchIndexes) == 0 or len(
35 | validationNonMatchIndexes) == 0:
36 | return -2
37 | matchIndexes = {i for i in dataRowIndexes if
38 | isMatch(data[i][attrIndex], attrValue)}
39 | nonMatchIndexes = dataRowIndexes - matchIndexes
40 | if len(matchIndexes) < minimumSubsetSize or len(
41 | nonMatchIndexes) < minimumSubsetSize:
42 | return -1
43 | matchOutcomes = {data[i][outcomeIndex] for i in matchIndexes}
44 | nonMatchOutcomes = {data[i][outcomeIndex] for i in nonMatchIndexes}
45 | numPureRows = (len(matchIndexes) if len(matchOutcomes) == 1 else 0) \
46 | + (len(nonMatchIndexes) if len(nonMatchOutcomes) == 1
47 | else 0)
48 | percentPure = numPureRows / len(dataRowIndexes)
49 |
50 | numNonPureRows = len(dataRowIndexes) - numPureRows
51 | percentNonPure = 1 - percentPure
52 | split = 1 - abs(len(matchIndexes) - len(nonMatchIndexes)) / len(
53 | dataRowIndexes) - .001
54 | splitBias = split * percentNonPure if numNonPureRows > 0 else 0
55 | return splitBias + percentPure
56 |
57 |
58 | def build(data, outcomeLabel, continuousAttributes=None,
59 | minimumSubsetSizePercentage=0, validationPercentage=0,
60 | dataIndexes=None, attrIndexes=None):
61 | if validationPercentage > 0:
62 | validationPercentage /= 100
63 | validationCount = int(validationPercentage *
64 | (len(data) if dataIndexes is None else len(
65 | dataIndexes)))
66 | if minimumSubsetSizePercentage > 0:
67 | minimumSubsetSizePercentage /= 100
68 | minimumSubsetSize = int(minimumSubsetSizePercentage *
69 | (len(data) if dataIndexes is None else len(
70 | dataIndexes)))
71 | if attrIndexes is None:
72 | attrIndexes = [index for index, label in enumerate(data[0]) if
73 | label != outcomeLabel]
74 | outcomeIndex = data[0].index(outcomeLabel)
75 | continuousAttrIndexes = set()
76 | if continuousAttributes is not None:
77 | continuousAttrIndexes = {data[0].index(label) for label in
78 | continuousAttributes}
79 | if len(continuousAttrIndexes) != len(continuousAttributes):
80 | raise Exception(
81 | 'One or more continuous column names are duplicates.')
82 | else:
83 | for attrIndex in attrIndexes:
84 | uniqueValues = {row[attrIndex] for rowIndex, row in
85 | enumerate(data) if rowIndex > 0}
86 | numericValues = {value for value in uniqueValues if
87 | isinstance(value, Number)}
88 | if len(uniqueValues) == len(numericValues):
89 | continuousAttrIndexes.add(attrIndex)
90 |
91 | if outcomeIndex in continuousAttrIndexes:
92 | continuousAttrIndexes.remove(outcomeIndex)
93 | outcomeIsContinuous = True
94 | else:
95 | outcomeIsContinuous = False
96 |
97 | nodes = []
98 | lastNodeNumber = 0
99 | if dataIndexes is None:
100 | dataIndexes = {i for i in range(1, len(data))}
101 | elif not isinstance(dataIndexes, set):
102 | dataIndexes = {i for i in dataIndexes}
103 | validationIndexes = set()
104 | if validationCount > 0:
105 | validationIndexes = set(
106 | random.sample([i for i in dataIndexes], validationCount))
107 | dataIndexes -= validationIndexes
108 | workQueue = [(-1, lastNodeNumber, dataIndexes, validationIndexes)]
109 | while len(workQueue) > 0:
110 | parentNodeId, nodeId, dataRowIndexes, validationRowIndexes = \
111 | workQueue.pop()
112 | uniqueOutcomes = Counter(
113 | data[i][outcomeIndex] for i in dataRowIndexes).most_common()
114 | if len(uniqueOutcomes) == 1:
115 | nodes.append((nodeId, uniqueOutcomes.pop(0)[0]))
116 | continue
117 | potentials = _get_potentials(attrIndexes, continuousAttrIndexes,
118 | data, dataRowIndexes, outcomeIndex,
119 | minimumSubsetSize,
120 | validationRowIndexes)
121 | if len(potentials) == 0 or potentials[0][0] > 0:
122 | nodes.append((nodeId, [(n[0], n[1] / len(dataRowIndexes))
123 | for n in uniqueOutcomes]))
124 | continue
125 | attrIndex, attrValue, isMatch = potentials[0][1:]
126 | matches = {rowIndex for rowIndex in dataRowIndexes if
127 | isMatch(data[rowIndex][attrIndex], attrValue)}
128 | nonMatches = dataRowIndexes - matches
129 | validationMatches = {
130 | rowIndex for rowIndex in validationRowIndexes if
131 | isMatch(data[rowIndex][attrIndex], attrValue)}
132 | nonValidationMatches = validationRowIndexes - validationMatches
133 | lastNodeNumber += 1
134 | matchId = lastNodeNumber
135 | workQueue.append((nodeId, matchId, matches, validationMatches))
136 | lastNodeNumber += 1
137 | nonMatchId = lastNodeNumber
138 | workQueue.append((nodeId, nonMatchId, nonMatches,
139 | nonValidationMatches))
140 | nodes.append((nodeId, attrIndex, attrValue, isMatch, matchId,
141 | nonMatchId, len(matches), len(nonMatches)))
142 | nodes = sorted(nodes, key=lambda n: n[0])
143 | return DTree(nodes, data[0], outcomeIsContinuous)
144 |
145 |
146 | def _get_potentials(attrIndexes, continuousAttrIndexes, data,
147 | dataRowIndexes, outcomeIndex, minimumSubsetSize,
148 | validationRowIndexes):
149 | uniqueAttributeValuePairs = {
150 | (attrIndex, data[rowIndex][attrIndex], operator.eq)
151 | for attrIndex in attrIndexes
152 | if attrIndex not in continuousAttrIndexes
153 | for rowIndex in dataRowIndexes}
154 | continuousAttributeValuePairs = _get_continuous_av_pairs(
155 | continuousAttrIndexes, data, dataRowIndexes)
156 | uniqueAttributeValuePairs |= continuousAttributeValuePairs
157 | potentials = sorted((-_get_bias(avPair, dataRowIndexes, data,
158 | outcomeIndex, minimumSubsetSize,
159 | validationRowIndexes),
160 | avPair[0], avPair[1], avPair[2])
161 | for avPair in uniqueAttributeValuePairs)
162 | return potentials
163 |
164 | def _get_continuous_av_pairs(continuousAttrIndexes, data, dataRowIndexes):
165 | avPairs = set()
166 | for attrIndex in continuousAttrIndexes:
167 | sortedAttrValues = [i for i in sorted(
168 | data[rowIndex][attrIndex] for rowIndex in dataRowIndexes)]
169 | indexes = _get_discontinuity_indexes(
170 | sortedAttrValues,
171 | max(math.sqrt(
172 | len(sortedAttrValues)),
173 | min(10,
174 | len(sortedAttrValues))))
175 | for index in indexes:
176 | avPairs.add((attrIndex, sortedAttrValues[index], operator.gt))
177 | return avPairs
178 |
179 |
180 | def _get_discontinuity_indexes(sortedAttrValues, maxIndexes):
181 | indexes = []
182 | for i in _generate_discontinuity_indexes_center_out(sortedAttrValues):
183 | indexes.append(i)
184 | if len(indexes) >= maxIndexes:
185 | break
186 | return indexes
187 |
188 |
189 | def _generate_discontinuity_indexes_center_out(sortedAttrValues):
190 | center = len(sortedAttrValues) // 2
191 | left = center - 1
192 | right = center + 1
193 | while left >= 0 or right < len(sortedAttrValues):
194 | if left >= 0:
195 | if sortedAttrValues[left] != sortedAttrValues[left + 1]:
196 | yield left
197 | left -= 1
198 | if right < len(sortedAttrValues):
199 | if sortedAttrValues[right - 1] != sortedAttrValues[right]:
200 | yield right - 1
201 | right += 1
202 |
203 |
204 | def read_csv(filepath):
205 | with open(filepath, 'r') as f:
206 | reader = csv.reader(f)
207 | data = list(reader)
208 | return data
209 |
210 |
211 | def prepare_data(data, numericColumnLabels=None):
212 | if numericColumnLabels is not None and len(numericColumnLabels) > 0:
213 | numericColumnIndexes = [data[0].index(label) for label in
214 | numericColumnLabels]
215 | for rowIndex, row in enumerate(data):
216 | if rowIndex == 0:
217 | continue
218 | for numericIndex in numericColumnIndexes:
219 | f = float(data[rowIndex][numericIndex]) if len(
220 | data[rowIndex][numericIndex]) > 0 else 0
221 | i = int(f)
222 | data[rowIndex][numericIndex] = i if i == f else f
223 | return data
224 |
225 |
226 | class DTree:
227 | def __init__(self, nodes, attrNames, outcomeIsContinuous=False):
228 | self._nodes = nodes
229 | self._attrNames = attrNames
230 | self._outcomeIsContinuous = outcomeIsContinuous
231 |
232 | @staticmethod
233 | def _is_leaf(node):
234 | return len(node) == 2
235 |
236 | def __str__(self):
237 | s = ''
238 | for node in self._nodes:
239 | if self._is_leaf(node):
240 | s += '{}: {}\n'.format(node[0], node[1])
241 | else:
242 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
243 | nodeIdIfNonMatch, matchCount, nonMatchCount = node
244 | s += '{0}: {1}{7}{2}, {5} Yes->{3}, {6} No->{4}\n'.format(
245 | nodeId, self._attrNames[attrIndex], attrValue,
246 | nodeIdIfMatch, nodeIdIfNonMatch, matchCount,
247 | nonMatchCount, '=' if isMatch == operator.eq else '>')
248 | return s
249 |
250 | def get_prediction(self, data):
251 | currentNode = self._nodes[0]
252 | while True:
253 | if self._is_leaf(currentNode):
254 | node = currentNode[1]
255 | if type(node) is not list:
256 | return node
257 | if self._outcomeIsContinuous:
258 | node = sorted(node, key=lambda n: n[0])
259 | randPercent = .5 if self._outcomeIsContinuous else \
260 | random.uniform(0, 1)
261 | total = 0
262 | for outcome, percentage in node:
263 | total += percentage
264 | if total > randPercent:
265 | return outcome
266 | return node[-1][0]
267 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
268 | nodeIdIfNonMatch = currentNode[:6]
269 | currentNode = self._nodes[nodeIdIfMatch if
270 | isMatch(data[attrIndex], attrValue) else nodeIdIfNonMatch]
271 |
--------------------------------------------------------------------------------
/ch06/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 6 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 |
20 |
21 | continuousAttributes = ['Age']
22 | data = dtree.read_csv('..\ch04\census.csv')
23 | data = dtree.prepare_data(data, continuousAttributes)
24 | outcomeLabel = 'Age'
25 |
26 | tree = dtree.build(data, outcomeLabel, continuousAttributes, minimumSubsetSizePercentage=6)
27 | print(tree)
28 |
29 | testData = ['Elizabeth', 'female', 'Single', -1, 'Daughter', 'Germany']
30 |
31 | predicted = tree.get_prediction(testData)
32 | print("predicted: {}".format(predicted))
--------------------------------------------------------------------------------
/ch07/dtree.py:
--------------------------------------------------------------------------------
1 | # File: dtree.py
2 | # from chapter 7 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | from collections import Counter
19 | from numbers import Number
20 | import operator
21 | import math
22 | import csv
23 | import random
24 |
25 |
26 | def _get_bias(avPair, dataRowIndexes, data, outcomeIndex, minimumSubsetSize,
27 | validationRowIndexes):
28 | attrIndex, attrValue, isMatch = avPair
29 | if len(validationRowIndexes) > 0:
30 | validationMatchIndexes = {i for i in validationRowIndexes if
31 | isMatch(data[i][attrIndex], attrValue)}
32 | validationNonMatchIndexes = validationRowIndexes - \
33 | validationMatchIndexes
34 | if len(validationMatchIndexes) == 0 or len(
35 | validationNonMatchIndexes) == 0:
36 | return -2
37 | matchIndexes = {i for i in dataRowIndexes if
38 | isMatch(data[i][attrIndex], attrValue)}
39 | nonMatchIndexes = dataRowIndexes - matchIndexes
40 | if len(matchIndexes) < minimumSubsetSize or len(
41 | nonMatchIndexes) < minimumSubsetSize:
42 | return -1
43 | matchOutcomes = {data[i][outcomeIndex] for i in matchIndexes}
44 | nonMatchOutcomes = {data[i][outcomeIndex] for i in nonMatchIndexes}
45 | numPureRows = (len(matchIndexes) if len(matchOutcomes) == 1 else 0) \
46 | + (len(nonMatchIndexes) if len(nonMatchOutcomes) == 1
47 | else 0)
48 | percentPure = numPureRows / len(dataRowIndexes)
49 |
50 | numNonPureRows = len(dataRowIndexes) - numPureRows
51 | percentNonPure = 1 - percentPure
52 | split = 1 - abs(len(matchIndexes) - len(nonMatchIndexes)) / len(
53 | dataRowIndexes) - .001
54 | splitBias = split * percentNonPure if numNonPureRows > 0 else 0
55 | return splitBias + percentPure
56 |
57 |
58 | def build(data, outcomeLabel, continuousAttributes=None,
59 | minimumSubsetSizePercentage=0, validationPercentage=0,
60 | dataIndexes=None, attrIndexes=None):
61 | if validationPercentage > 0:
62 | validationPercentage /= 100
63 | validationCount = int(validationPercentage *
64 | (len(data) if dataIndexes is None else len(
65 | dataIndexes)))
66 | if minimumSubsetSizePercentage > 0:
67 | minimumSubsetSizePercentage /= 100
68 | minimumSubsetSize = int(minimumSubsetSizePercentage *
69 | (len(data) if dataIndexes is None else len(
70 | dataIndexes)))
71 | if attrIndexes is None:
72 | attrIndexes = [index for index, label in enumerate(data[0]) if
73 | label != outcomeLabel]
74 | outcomeIndex = data[0].index(outcomeLabel)
75 | continuousAttrIndexes = set()
76 | if continuousAttributes is not None:
77 | continuousAttrIndexes = {data[0].index(label) for label in
78 | continuousAttributes}
79 | if len(continuousAttrIndexes) != len(continuousAttributes):
80 | raise Exception(
81 | 'One or more continuous column names are duplicates.')
82 | else:
83 | for attrIndex in attrIndexes:
84 | uniqueValues = {row[attrIndex] for rowIndex, row in
85 | enumerate(data) if rowIndex > 0}
86 | numericValues = {value for value in uniqueValues if
87 | isinstance(value, Number)}
88 | if len(uniqueValues) == len(numericValues):
89 | continuousAttrIndexes.add(attrIndex)
90 |
91 | if outcomeIndex in continuousAttrIndexes:
92 | continuousAttrIndexes.remove(outcomeIndex)
93 | outcomeIsContinuous = True
94 | else:
95 | outcomeIsContinuous = False
96 |
97 | nodes = []
98 | lastNodeNumber = 0
99 | if dataIndexes is None:
100 | dataIndexes = {i for i in range(1, len(data))}
101 | elif not isinstance(dataIndexes, set):
102 | dataIndexes = {i for i in dataIndexes}
103 | validationIndexes = set()
104 | if validationCount > 0:
105 | validationIndexes = set(
106 | random.sample([i for i in dataIndexes], validationCount))
107 | dataIndexes -= validationIndexes
108 | workQueue = [(-1, lastNodeNumber, dataIndexes, validationIndexes)]
109 | while len(workQueue) > 0:
110 | parentNodeId, nodeId, dataRowIndexes, validationRowIndexes = \
111 | workQueue.pop()
112 | uniqueOutcomes = Counter(
113 | data[i][outcomeIndex] for i in dataRowIndexes).most_common()
114 | if len(uniqueOutcomes) == 1:
115 | nodes.append((nodeId, uniqueOutcomes.pop(0)[0]))
116 | continue
117 | potentials = _get_potentials(attrIndexes, continuousAttrIndexes,
118 | data, dataRowIndexes, outcomeIndex,
119 | minimumSubsetSize,
120 | validationRowIndexes)
121 | if len(potentials) == 0 or potentials[0][0] > 0:
122 | nodes.append((nodeId, [(n[0], n[1] / len(dataRowIndexes))
123 | for n in uniqueOutcomes]))
124 | continue
125 | attrIndex, attrValue, isMatch = potentials[0][1:]
126 | matches = {rowIndex for rowIndex in dataRowIndexes if
127 | isMatch(data[rowIndex][attrIndex], attrValue)}
128 | nonMatches = dataRowIndexes - matches
129 | validationMatches = {
130 | rowIndex for rowIndex in validationRowIndexes if
131 | isMatch(data[rowIndex][attrIndex], attrValue)}
132 | nonValidationMatches = validationRowIndexes - validationMatches
133 | lastNodeNumber += 1
134 | matchId = lastNodeNumber
135 | workQueue.append((nodeId, matchId, matches, validationMatches))
136 | lastNodeNumber += 1
137 | nonMatchId = lastNodeNumber
138 | workQueue.append((nodeId, nonMatchId, nonMatches,
139 | nonValidationMatches))
140 | nodes.append((nodeId, attrIndex, attrValue, isMatch, matchId,
141 | nonMatchId, len(matches), len(nonMatches)))
142 | nodes = sorted(nodes, key=lambda n: n[0])
143 | return DTree(nodes, data[0], outcomeIsContinuous)
144 |
145 |
146 | def _get_potentials(attrIndexes, continuousAttrIndexes, data,
147 | dataRowIndexes, outcomeIndex, minimumSubsetSize,
148 | validationRowIndexes):
149 | uniqueAttributeValuePairs = {
150 | (attrIndex, data[rowIndex][attrIndex], operator.eq)
151 | for attrIndex in attrIndexes
152 | if attrIndex not in continuousAttrIndexes
153 | for rowIndex in dataRowIndexes}
154 | continuousAttributeValuePairs = _get_continuous_av_pairs(
155 | continuousAttrIndexes, data, dataRowIndexes)
156 | uniqueAttributeValuePairs |= continuousAttributeValuePairs
157 | potentials = sorted((-_get_bias(avPair, dataRowIndexes, data,
158 | outcomeIndex, minimumSubsetSize,
159 | validationRowIndexes),
160 | avPair[0], avPair[1], avPair[2])
161 | for avPair in uniqueAttributeValuePairs)
162 | return potentials
163 |
164 | def _get_continuous_av_pairs(continuousAttrIndexes, data, dataRowIndexes):
165 | avPairs = set()
166 | for attrIndex in continuousAttrIndexes:
167 | sortedAttrValues = [i for i in sorted(
168 | data[rowIndex][attrIndex] for rowIndex in dataRowIndexes)]
169 | indexes = _get_discontinuity_indexes(
170 | sortedAttrValues,
171 | max(math.sqrt(
172 | len(sortedAttrValues)),
173 | min(10,
174 | len(sortedAttrValues))))
175 | for index in indexes:
176 | avPairs.add((attrIndex, sortedAttrValues[index], operator.gt))
177 | return avPairs
178 |
179 |
180 | def _get_discontinuity_indexes(sortedAttrValues, maxIndexes):
181 | indexes = []
182 | for i in _generate_discontinuity_indexes_center_out(sortedAttrValues):
183 | indexes.append(i)
184 | if len(indexes) >= maxIndexes:
185 | break
186 | return indexes
187 |
188 |
189 | def _generate_discontinuity_indexes_center_out(sortedAttrValues):
190 | center = len(sortedAttrValues) // 2
191 | left = center - 1
192 | right = center + 1
193 | while left >= 0 or right < len(sortedAttrValues):
194 | if left >= 0:
195 | if sortedAttrValues[left] != sortedAttrValues[left + 1]:
196 | yield left
197 | left -= 1
198 | if right < len(sortedAttrValues):
199 | if sortedAttrValues[right - 1] != sortedAttrValues[right]:
200 | yield right - 1
201 | right += 1
202 |
203 |
204 | def read_csv(filepath):
205 | with open(filepath, 'r') as f:
206 | reader = csv.reader(f)
207 | data = list(reader)
208 | return data
209 |
210 |
211 | def prepare_data(data, numericColumnLabels=None):
212 | if numericColumnLabels is not None and len(numericColumnLabels) > 0:
213 | numericColumnIndexes = [data[0].index(label) for label in
214 | numericColumnLabels]
215 | for rowIndex, row in enumerate(data):
216 | if rowIndex == 0:
217 | continue
218 | for numericIndex in numericColumnIndexes:
219 | f = float(data[rowIndex][numericIndex]) if len(
220 | data[rowIndex][numericIndex]) > 0 else 0
221 | i = int(f)
222 | data[rowIndex][numericIndex] = i if i == f else f
223 | return data
224 |
225 |
226 | class DTree:
227 | def __init__(self, nodes, attrNames, outcomeIsContinuous=False):
228 | self._nodes = nodes
229 | self._attrNames = attrNames
230 | self._outcomeIsContinuous = outcomeIsContinuous
231 |
232 | @staticmethod
233 | def _is_leaf(node):
234 | return len(node) == 2
235 |
236 | def __str__(self):
237 | s = ''
238 | for node in self._nodes:
239 | if self._is_leaf(node):
240 | s += '{}: {}\n'.format(node[0], node[1])
241 | else:
242 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
243 | nodeIdIfNonMatch, matchCount, nonMatchCount = node
244 | s += '{0}: {1}{7}{2}, {5} Yes->{3}, {6} No->{4}\n'.format(
245 | nodeId, self._attrNames[attrIndex], attrValue,
246 | nodeIdIfMatch, nodeIdIfNonMatch, matchCount,
247 | nonMatchCount, '=' if isMatch == operator.eq else '>')
248 | return s
249 |
250 | def get_prediction(self, data):
251 | currentNode = self._nodes[0]
252 | while True:
253 | if self._is_leaf(currentNode):
254 | node = currentNode[1]
255 | if type(node) is not list:
256 | return node
257 | if self._outcomeIsContinuous:
258 | node = sorted(node, key=lambda n: n[0])
259 | randPercent = .5 if self._outcomeIsContinuous else \
260 | random.uniform(0, 1)
261 | total = 0
262 | for outcome, percentage in node:
263 | total += percentage
264 | if total > randPercent:
265 | return outcome
266 | return node[-1][0]
267 | nodeId, attrIndex, attrValue, isMatch, nodeIdIfMatch, \
268 | nodeIdIfNonMatch = currentNode[:6]
269 | currentNode = self._nodes[nodeIdIfMatch if
270 | isMatch(data[attrIndex], attrValue) else nodeIdIfNonMatch]
271 |
--------------------------------------------------------------------------------
/ch07/forest.py:
--------------------------------------------------------------------------------
1 | # File: forest.py
2 | # from chapter 7 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 | import math
20 | import random
21 | import statistics
22 | import operator
23 |
24 | class Forest:
25 | def __init__(self, data, outcomeLabel, continuousAttributes=None,
26 | dataRowIndexes=None, columnsNamesToIgnore=None,
27 | boost=False):
28 | self.data = data
29 | self.outcomeLabel = outcomeLabel
30 | self.continuousAttributes = continuousAttributes \
31 | if columnsNamesToIgnore is None \
32 | else [i for i in continuousAttributes if
33 | i not in columnsNamesToIgnore]
34 | self.numRows = math.ceil(math.sqrt(
35 | len(data) if dataRowIndexes is None else len(dataRowIndexes)))
36 | self.outcomeIndex = data[0].index(outcomeLabel)
37 | columnIdsToIgnore = set() if columnsNamesToIgnore is None else set(
38 | data[0].index(s) for s in columnsNamesToIgnore)
39 | columnIdsToIgnore.add(self.outcomeIndex)
40 | self.attrIndexesExceptOutcomeIndex = [i for i in range(0, len(data[0]))
41 | if i not in columnIdsToIgnore]
42 | self.numAttributes = math.ceil(
43 | math.sqrt(len(self.attrIndexesExceptOutcomeIndex)))
44 | self.dataRowIndexes = range(1, len(
45 | data)) if dataRowIndexes is None else dataRowIndexes
46 | self.numTrees = 200
47 | self.boost = boost
48 | self.weights = [.5 for _ in range(0, self.numTrees)]
49 | self.populate()
50 |
51 | def _build_tree(self):
52 | return dtree.build(self.data, self.outcomeLabel,
53 | continuousAttributes=self.continuousAttributes,
54 | dataIndexes={i for i in random.sample(
55 | self.dataRowIndexes, self.numRows)},
56 | attrIndexes=[
57 | i for i in random.sample(
58 | self.attrIndexesExceptOutcomeIndex,
59 | self.numAttributes)])
60 |
61 | def populate(self):
62 | self._trees = [self._build_tree() for _ in range(0, self.numTrees)]
63 |
64 | if not self.boost:
65 | return
66 |
67 | outcomeLabelIndex = self.data[0].index(self.outcomeLabel)
68 | anyChanged = True
69 | roundsRemaining = 10
70 | while anyChanged and roundsRemaining > 0:
71 | anyChanged = False
72 | roundsRemaining -= 1
73 | for dataRowIndex in self.dataRowIndexes:
74 | dataRow = self.data[dataRowIndex]
75 | sorted_predictions, predictions = self._get_predictions(
76 | dataRow)
77 | expectedPrediction = dataRow[outcomeLabelIndex]
78 | if expectedPrediction == sorted_predictions[0][0]:
79 | continue
80 | anyChanged = True
81 | actualPrediction = sorted_predictions[0][0]
82 | lookup = dict(sorted_predictions)
83 | expectedPredictionSum = lookup.get(expectedPrediction)
84 | difference = sorted_predictions[0][1] if \
85 | expectedPredictionSum is None else \
86 | sorted_predictions[0][1] - expectedPredictionSum
87 | maxDifference = difference / len(self.dataRowIndexes)
88 | if maxDifference == 0:
89 | maxDifference = .5 / len(self.dataRowIndexes)
90 | for index, p in enumerate(predictions):
91 | if p == expectedPrediction:
92 | self.weights[index] = min(1, self.weights[
93 | index] + random.uniform(0, maxDifference))
94 | continue
95 | if p == actualPrediction:
96 | self.weights[index] = max(0, self.weights[
97 | index] - random.uniform(0, maxDifference))
98 | if self.weights[index] == 0:
99 | self._trees[index] = self._build_tree()
100 | self.weights[index] = 0.5
101 |
102 | def get_prediction(self, data):
103 | sorted_predictions, _ = self._get_predictions(data)
104 | return sorted_predictions[0][0]
105 |
106 | def _get_predictions(self, data):
107 | predictions = [t.get_prediction(data) for t in self._trees]
108 | counts = {p: 0 for p in set(predictions)}
109 | for index, p in enumerate(predictions):
110 | counts[p] += self.weights[index]
111 | return sorted(counts.items(), key=operator.itemgetter(1),
112 | reverse=True), \
113 | predictions
114 |
115 |
116 | class Benchmark:
117 | @staticmethod
118 | def run(function):
119 | results = []
120 | for i in range(100):
121 | result = function()
122 | results.append(result)
123 | if i < 10 or i % 10 == 9:
124 | mean = statistics.mean(results)
125 | print("{} {:3.2f} {:3.2f}".format(
126 | 1 + i, mean,
127 | statistics.stdev(results, mean) if i > 1 else 0))
--------------------------------------------------------------------------------
/ch07/test.py:
--------------------------------------------------------------------------------
1 | # File: test.py
2 | # from chapter 7 of _Tree-based Machine Learning Algorithms_
3 | #
4 | # Author: Clinton Sheppard
5 | # Copyright (c) 2017 Clinton Sheppard
6 | #
7 | # Licensed under the Apache License, Version 2.0 (the "License").
8 | # You may not use this file except in compliance with the License.
9 | # You may obtain a copy of the License at
10 | # http://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15 | # implied. See the License for the specific language governing
16 | # permissions and limitations under the License.
17 |
18 | import dtree
19 | import random
20 | import forest
21 |
22 | data = dtree.read_csv('mushrooms.csv')
23 | outcomeLabel = 'class'
24 | outcomeLabelIndex = data[0].index(outcomeLabel)
25 | continuousAttributes = []
26 |
27 |
28 | print("-- decision tree")
29 | def predict():
30 | trainingRowIds = random.sample(range(1, len(data)),
31 | int(.01 * len(data)))
32 | tree = dtree.build(data, outcomeLabel, continuousAttributes,
33 | dataIndexes=trainingRowIds)
34 | correct = sum(1 for rowId, row in enumerate(data) if
35 | rowId > 0 and
36 | rowId not in trainingRowIds and
37 | tree.get_prediction(row) == row[outcomeLabelIndex])
38 | return 100 * correct / (len(data) - 1 - len(trainingRowIds))
39 |
40 | forest.Benchmark.run(predict)
41 |
42 |
43 | print("-- random forest")
44 | def predict2():
45 | trainingRowIds = random.sample(range(1, len(data)),
46 | int(.01 * len(data)))
47 | f = forest.Forest(data, outcomeLabel, continuousAttributes,
48 | trainingRowIds)
49 | correct = sum(1 for rowId, row in enumerate(data) if
50 | rowId > 0 and
51 | rowId not in trainingRowIds and
52 | f.get_prediction(row) == row[outcomeLabelIndex])
53 | return 100 * correct / (len(data) - 1 - len(trainingRowIds))
54 |
55 | forest.Benchmark.run(predict2)
56 |
57 |
58 | print("-- boosted random forest")
59 | def predict3():
60 | trainingRowIds = random.sample(range(1, len(data)),
61 | int(.01 * len(data)))
62 | f = forest.Forest(data, outcomeLabel, continuousAttributes,
63 | trainingRowIds, boost=True)
64 |
65 | correct = sum(1 for rowId, row in enumerate(data) if
66 | rowId > 0 and
67 | rowId not in trainingRowIds and
68 | f.get_prediction(row) == row[outcomeLabelIndex])
69 | return 100 * correct / (len(data) - 1 - len(trainingRowIds))
70 |
71 | forest.Benchmark.run(predict3)
72 |
--------------------------------------------------------------------------------