SelfModifiedDecisionTree 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: c7fb850d256fb116437ab023bfde0bc87f0c9d0c2e757cc13f1719590ad7bd8e
4
+ data.tar.gz: 49a3b8e1208132a2aa06c4c69eeec04952fd00106ffd3a6f9468f59a701a118e
5
+ SHA512:
6
+ metadata.gz: 84a3d84eec538a8b3e5c0638c80e5f5be620a025c2b046b92cc5e13c566a3e35ae40fcce1c0df83cbe50b1496490ce6962707d008712df9a335daaa0b3e2e1e1
7
+ data.tar.gz: 0ad4e36517845354d4ad5e078242b4e198d2906998839d47a44d21f7fb082e5c8d41ee7bad9a91615513284a77311b899b24302f4fb508aaac103fc828d478ad
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2025-08-08
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at TODO: Write your email address. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 TODO: Write your name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # SelfModifiedDecisionTree
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/SelfModifiedDecisionTree`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/SelfModifiedDecisionTree. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/SelfModifiedDecisionTree/blob/master/CODE_OF_CONDUCT.md).
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the SelfModifiedDecisionTree project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/SelfModifiedDecisionTree/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rake/testtask"
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << "test"
8
+ t.libs << "lib"
9
+ t.test_files = FileList["test/**/test_*.rb"]
10
+ end
11
+
12
+ require "rubocop/rake_task"
13
+
14
+ RuboCop::RakeTask.new
15
+
16
+ task default: %i[test rubocop]
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/SelfModifiedDecisionTree/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "SelfModifiedDecisionTree"
7
+ spec.version = SelfModifiedDecisionTree::VERSION
8
+ spec.authors = ["LWFlouisa"]
9
+ spec.email = ["lwflouisa@gmail.com"]
10
+
11
+ spec.summary = "This gem aims to remove vulnerable functionalities like data marshalling to prevent certain types of attacks."
12
+ spec.description = "Marshalled data can be deserialized by malicious users in order to compromise the integrity of AI algorithms. Here my theory is removing marshall reduces the attack surface."
13
+ #spec.homepage = "TODO: Put your gem's website or public repo URL here."
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.2.3"
16
+
17
+ # Specify which files should be added to the gem when it is released.
18
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
19
+ spec.files = Dir.chdir(__dir__) do
20
+ `git ls-files -z`.split("\x0").reject do |f|
21
+ (File.expand_path(f) == __FILE__) ||
22
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git .circleci appveyor Gemfile])
23
+ end
24
+ end
25
+
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ # Uncomment to register a new dependency of your gem
31
+ # spec.add_dependency "example-gem", "~> 1.0"
32
+
33
+ # For more information and examples about making a new gem, check out our
34
+ # guide at: https://bundler.io/guides/creating_gem.html
35
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SelfModifiedDecisionTree
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,406 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "SelfModifiedDecisionTree/version"
4
+
5
+ #################################################################################################################
6
+ # Modified Naive Bayes #
7
+ #################################################################################################################
8
+ # This is a modified form of naive bayes that eliminates marshall loading and unloading to prevent specific #
9
+ # types of deserialization based attacks. #
10
+ #################################################################################################################
11
+ class RevisedBayes
12
+
13
+ def initialize(*klasses)
14
+ @features_count = {}
15
+
16
+ @klass_count = {}
17
+
18
+ @klasses = klasses
19
+
20
+ klasses.each do |klass|
21
+ @features_count[klass] = Hash.new(0.0)
22
+
23
+ @klass_count[klass] = 0.0
24
+ end
25
+ end
26
+
27
+ def train(klass, *features)
28
+ features.uniq.each do |feature|
29
+
30
+ @features_count[klass][feature] += 1
31
+
32
+ end
33
+
34
+ @klass_count[klass] += 1
35
+ end
36
+
37
+ #P(Class | Item) = P(Item | Class) * P(Class)
38
+ def classify(*features)
39
+ scores = {}
40
+
41
+ @klasses.each do |klass|
42
+ scores[klass] = (prob_of_item_given_a_class(features, klass) * prob_of_class(klass))
43
+ end
44
+
45
+ scores.sort {|a,b| b[1] <=> a[1]}[0]
46
+ end
47
+
48
+ private
49
+
50
+ # P(Item | Class)
51
+ def prob_of_item_given_a_class(features, klass)
52
+ a = features.inject(1.0) do |sum, feature|
53
+ prob = prob_of_feature_given_a_class(feature, klass)
54
+ sum *= prob
55
+ end
56
+ end
57
+
58
+ # P(Feature | Class)
59
+ def prob_of_feature_given_a_class(feature, klass) # The brackets are for assigning arguments for local variables. Ex. get_animal(dog, cat)
60
+
61
+ return assumed_probability if @features_count[klass][feature] == 0
62
+ @features_count[klass][feature] / @klass_count[klass]
63
+ end
64
+
65
+ # P(Class)
66
+ def prob_of_class(klass)
67
+ @klass_count[klass] / total_items
68
+ end
69
+
70
+ def total_items
71
+ @klass_count.inject(0) do |sum, klass|
72
+ sum += klass[1]
73
+ end
74
+ end
75
+
76
+ # If we have only trained a little bit a class may not have had a feature yet
77
+ # give it a probability of 0 may not be true so we produce a assumed probability
78
+ # which gets smaller more we train
79
+ def assumed_probability
80
+ 0.5 / (total_items/2)
81
+ end
82
+
83
+ end
84
+ #################################################################################################################
85
+ # Modified ID3 #
86
+ #################################################################################################################
87
+ # This is a modified version of ID3 that eliminates marshall saving and unloading given that deserialized user #
88
+ # input can be quite dangerous. #
89
+ #################################################################################################################
90
+ class Array
91
+ def classification; collect { |v| v.last }; end
92
+
93
+ # calculate information entropy
94
+ def entropy
95
+ return 0 if empty?
96
+
97
+ info = {}
98
+ total = 0
99
+ each {|i| info[i] = !info[i] ? 1 : (info[i] + 1); total += 1}
100
+
101
+ result = 0
102
+ info.each do |symbol, count|
103
+ result += -count.to_f/total*Math.log(count.to_f/total)/Math.log(2.0) if (count > 0)
104
+ end
105
+ result
106
+ end
107
+ end
108
+
109
+ module DecisionTree
110
+ Node = Struct.new(:attribute, :threshold, :gain)
111
+
112
+ class ID3Tree
113
+ def initialize(attributes, data, default, type)
114
+ @used, @tree, @type = {}, {}, type
115
+ @data, @attributes, @default = data, attributes, default
116
+ end
117
+
118
+ def train(data=@data, attributes=@attributes, default=@default)
119
+ attributes = attributes.map {|e| e.to_s}
120
+ initialize(attributes, data, default, @type)
121
+
122
+ # Remove samples with same attributes leaving most common classification
123
+ data2 = data.inject({}) {|hash, d| hash[d.slice(0..-2)] ||= Hash.new(0); hash[d.slice(0..-2)][d.last] += 1; hash }.map{|key,val| key + [val.sort_by{ |k, v| v }.last.first]}
124
+
125
+ @tree = id3_train(data2, attributes, default)
126
+ end
127
+
128
+ def type(attribute)
129
+ @type.is_a?(Hash) ? @type[attribute.to_sym] : @type
130
+ end
131
+
132
+ def fitness_for(attribute)
133
+ case type(attribute)
134
+ when :discrete; fitness = proc{|a,b,c| id3_discrete(a,b,c)}
135
+ when :continuous; fitness = proc{|a,b,c| id3_continuous(a,b,c)}
136
+ end
137
+ end
138
+
139
+ def id3_train(data, attributes, default, used={})
140
+ return default if data.empty?
141
+
142
+ # return classification if all examples have the same classification
143
+ return data.first.last if data.classification.uniq.size == 1
144
+
145
+ # Choose best attribute:
146
+ # 1. enumerate all attributes
147
+ # 2. Pick best attribute
148
+ # 3. If attributes all score the same, then pick a random one to avoid infinite recursion.
149
+ performance = attributes.collect { |attribute| fitness_for(attribute).call(data, attributes, attribute) }
150
+ max = performance.max { |a,b| a[0] <=> b[0] }
151
+ min = performance.min { |a,b| a[0] <=> b[0] }
152
+ max = performance.shuffle.first if max[0] == min[0]
153
+ best = Node.new(attributes[performance.index(max)], max[1], max[0])
154
+ best.threshold = nil if @type == :discrete
155
+ @used.has_key?(best.attribute) ? @used[best.attribute] += [best.threshold] : @used[best.attribute] = [best.threshold]
156
+ tree, l = {best => {}}, ['>=', '<']
157
+
158
+ fitness = fitness_for(best.attribute)
159
+ case type(best.attribute)
160
+ when :continuous
161
+ data.partition { |d| d[attributes.index(best.attribute)] >= best.threshold }.each_with_index { |examples, i|
162
+ tree[best][String.new(l[i])] = id3_train(examples, attributes, (data.classification.mode rescue 0), &fitness)
163
+ }
164
+ when :discrete
165
+ values = data.collect { |d| d[attributes.index(best.attribute)] }.uniq.sort
166
+ partitions = values.collect { |val| data.select { |d| d[attributes.index(best.attribute)] == val } }
167
+ partitions.each_with_index { |examples, i|
168
+ tree[best][values[i]] = id3_train(examples, attributes-[values[i]], (data.classification.mode rescue 0), &fitness)
169
+ }
170
+ end
171
+
172
+ tree
173
+ end
174
+
175
+ # ID3 for binary classification of continuous variables (e.g. healthy / sick based on temperature thresholds)
176
+ def id3_continuous(data, attributes, attribute)
177
+ values, thresholds = data.collect { |d| d[attributes.index(attribute)] }.uniq.sort, []
178
+ return [-1, -1] if values.size == 1
179
+ values.each_index { |i| thresholds.push((values[i]+(values[i+1].nil? ? values[i] : values[i+1])).to_f / 2) }
180
+ thresholds.pop
181
+ #thresholds -= used[attribute] if used.has_key? attribute
182
+
183
+ gain = thresholds.collect { |threshold|
184
+ sp = data.partition { |d| d[attributes.index(attribute)] >= threshold }
185
+ pos = (sp[0].size).to_f / data.size
186
+ neg = (sp[1].size).to_f / data.size
187
+
188
+ [data.classification.entropy - pos*sp[0].classification.entropy - neg*sp[1].classification.entropy, threshold]
189
+ }.max { |a,b| a[0] <=> b[0] }
190
+
191
+ return [-1, -1] if gain.size == 0
192
+ gain
193
+ end
194
+
195
+ # ID3 for discrete label cases
196
+ def id3_discrete(data, attributes, attribute)
197
+ values = data.collect { |d| d[attributes.index(attribute)] }.uniq.sort
198
+ partitions = values.collect { |val| data.select { |d| d[attributes.index(attribute)] == val } }
199
+ remainder = partitions.collect {|p| (p.size.to_f / data.size) * p.classification.entropy}.inject(0) {|i,s| s+=i }
200
+
201
+ [data.classification.entropy - remainder, attributes.index(attribute)]
202
+ end
203
+
204
+ def predict(test)
205
+ descend(@tree, test)
206
+ end
207
+
208
+ def graph(filename, file_type = "png")
209
+ require 'graphr'
210
+ dgp = DotGraphPrinter.new(build_tree)
211
+ dgp.write_to_file("#{filename}.#{file_type}", file_type)
212
+ end
213
+
214
+ def ruleset
215
+ rs = Ruleset.new(@attributes, @data, @default, @type)
216
+ rs.rules = build_rules
217
+ rs
218
+ end
219
+
220
+ def build_rules(tree=@tree)
221
+ attr = tree.to_a.first
222
+ cases = attr[1].to_a
223
+ rules = []
224
+ cases.each do |c,child|
225
+ if child.is_a?(Hash) then
226
+ build_rules(child).each do |r|
227
+ r2 = r.clone
228
+ r2.premises.unshift([attr.first, c])
229
+ rules << r2
230
+ end
231
+ else
232
+ rules << Rule.new(@attributes, [[attr.first, c]], child)
233
+ end
234
+ end
235
+ rules
236
+ end
237
+
238
+ private
239
+ def descend(tree, test)
240
+ attr = tree.to_a.first
241
+ return @default if !attr
242
+ if type(attr.first.attribute) == :continuous
243
+ return attr[1]['>='] if !attr[1]['>='].is_a?(Hash) and test[@attributes.index(attr.first.attribute)] >= attr.first.threshold
244
+ return attr[1]['<'] if !attr[1]['<'].is_a?(Hash) and test[@attributes.index(attr.first.attribute)] < attr.first.threshold
245
+ return descend(attr[1]['>='],test) if test[@attributes.index(attr.first.attribute)] >= attr.first.threshold
246
+ return descend(attr[1]['<'],test) if test[@attributes.index(attr.first.attribute)] < attr.first.threshold
247
+ else
248
+ return attr[1][test[@attributes.index(attr[0].attribute)]] if !attr[1][test[@attributes.index(attr[0].attribute)]].is_a?(Hash)
249
+ return descend(attr[1][test[@attributes.index(attr[0].attribute)]],test)
250
+ end
251
+ end
252
+
253
+ def build_tree(tree = @tree)
254
+ return [] unless tree.is_a?(Hash)
255
+ return [["Always", @default]] if tree.empty?
256
+
257
+ attr = tree.to_a.first
258
+
259
+ links = attr[1].keys.collect do |key|
260
+ parent_text = "#{attr[0].attribute}\n(#{attr[0].object_id})"
261
+ if attr[1][key].is_a?(Hash) then
262
+ child = attr[1][key].to_a.first[0]
263
+ child_text = "#{child.attribute}\n(#{child.object_id})"
264
+ else
265
+ child = attr[1][key]
266
+ child_text = "#{child}\n(#{child.to_s.clone.object_id})"
267
+ end
268
+ label_text = "#{key} #{type(attr[0].attribute) == :continuous ? attr[0].threshold : ""}"
269
+
270
+ [parent_text, child_text, label_text]
271
+ end
272
+ attr[1].keys.each { |key| links += build_tree(attr[1][key]) }
273
+
274
+ return links
275
+ end
276
+ end
277
+
278
+ class Rule
279
+ attr_accessor :premises
280
+ attr_accessor :conclusion
281
+ attr_accessor :attributes
282
+
283
+ def initialize(attributes,premises=[],conclusion=nil)
284
+ @attributes, @premises, @conclusion = attributes, premises, conclusion
285
+ end
286
+
287
+ def to_s
288
+ str = ''
289
+ @premises.each do |p|
290
+ str += "#{p.first.attribute} #{p.last} #{p.first.threshold}" if p.first.threshold
291
+ str += "#{p.first.attribute} = #{p.last}" if !p.first.threshold
292
+ str += "\n"
293
+ end
294
+ str += "=> #{@conclusion} (#{accuracy})"
295
+ end
296
+
297
+ def predict(test)
298
+ verifies = true;
299
+ @premises.each do |p|
300
+ if p.first.threshold then # Continuous
301
+ if !(p.last == '>=' && test[@attributes.index(p.first.attribute)] >= p.first.threshold) && !(p.last == '<' && test[@attributes.index(p.first.attribute)] < p.first.threshold) then
302
+ verifies = false; break
303
+ end
304
+ else # Discrete
305
+ if test[@attributes.index(p.first.attribute)] != p.last then
306
+ verifies = false; break
307
+ end
308
+ end
309
+ end
310
+ return @conclusion if verifies
311
+ return nil
312
+ end
313
+
314
+ def get_accuracy(data)
315
+ correct = 0; total = 0
316
+ data.each do |d|
317
+ prediction = predict(d)
318
+ correct += 1 if d.last == prediction
319
+ total += 1 if !prediction.nil?
320
+ end
321
+ (correct.to_f + 1) / (total.to_f + 2)
322
+ end
323
+
324
+ def accuracy(data=nil)
325
+ data.nil? ? @accuracy : @accuracy = get_accuracy(data)
326
+ end
327
+ end
328
+
329
+ class Ruleset
330
+ attr_accessor :rules
331
+
332
+ def initialize(attributes, data, default, type)
333
+ @attributes, @default, @type = attributes, default, type
334
+ mixed_data = data.sort_by {rand}
335
+ cut = (mixed_data.size.to_f * 0.67).to_i
336
+ @train_data = mixed_data.slice(0..cut-1)
337
+ @prune_data = mixed_data.slice(cut..-1)
338
+ end
339
+
340
+ def train(train_data=@train_data, attributes=@attributes, default=@default)
341
+ dec_tree = DecisionTree::ID3Tree.new(attributes, train_data, default, @type)
342
+ dec_tree.train
343
+ @rules = dec_tree.build_rules
344
+ @rules.each { |r| r.accuracy(train_data) } # Calculate accuracy
345
+ prune
346
+ end
347
+
348
+ def prune(data=@prune_data)
349
+ @rules.each do |r|
350
+ (1..r.premises.size).each do
351
+ acc1 = r.accuracy(data)
352
+ p = r.premises.pop
353
+ if acc1 > r.get_accuracy(data) then
354
+ r.premises.push(p); break
355
+ end
356
+ end
357
+ end
358
+ @rules = @rules.sort_by{|r| -r.accuracy(data)}
359
+ end
360
+
361
+ def to_s
362
+ str = ''; @rules.each { |rule| str += "#{rule}\n\n" }
363
+ str
364
+ end
365
+
366
+ def predict(test)
367
+ @rules.each do |r|
368
+ prediction = r.predict(test)
369
+ return prediction, r.accuracy unless prediction.nil?
370
+ end
371
+ return @default, 0.0
372
+ end
373
+ end
374
+
375
+ class Bagging
376
+ attr_accessor :classifiers
377
+ def initialize(attributes, data, default, type)
378
+ @classifiers, @type = [], type
379
+ @data, @attributes, @default = data, attributes, default
380
+ end
381
+
382
+ def train(data=@data, attributes=@attributes, default=@default)
383
+ @classifiers = []
384
+ 10.times { @classifiers << Ruleset.new(attributes, data, default, @type) }
385
+ @classifiers.each do |c|
386
+ c.train(data, attributes, default)
387
+ end
388
+ end
389
+
390
+ def predict(test)
391
+ predictions = Hash.new(0)
392
+ @classifiers.each do |c|
393
+ p, accuracy = c.predict(test)
394
+ predictions[p] += accuracy unless p.nil?
395
+ end
396
+ return @default, 0.0 if predictions.empty?
397
+ winner = predictions.sort_by {|k,v| -v}.first
398
+ return winner[0], winner[1].to_f / @classifiers.size.to_f
399
+ end
400
+ end
401
+ end
402
+
403
+ #module SelfModifiedDecisionTree
404
+ # class Error < StandardError; end
405
+ # # Your code goes here...
406
+ #end
@@ -0,0 +1,4 @@
1
+ module SelfModifiedDecisionTree
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,56 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: SelfModifiedDecisionTree
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - LWFlouisa
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2025-08-09 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Marshalled data can be deserialized by malicious users in order to compromise
14
+ the integrity of AI algorithms. Here my theory is removing marshall reduces the
15
+ attack surface.
16
+ email:
17
+ - lwflouisa@gmail.com
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - ".rubocop.yml"
23
+ - CHANGELOG.md
24
+ - CODE_OF_CONDUCT.md
25
+ - LICENSE.txt
26
+ - README.md
27
+ - Rakefile
28
+ - SelfModifiedDecisionTree.gemspec
29
+ - lib/SelfModifiedDecisionTree.rb
30
+ - lib/SelfModifiedDecisionTree/version.rb
31
+ - sig/SelfModifiedDecisionTree.rbs
32
+ homepage:
33
+ licenses:
34
+ - MIT
35
+ metadata: {}
36
+ post_install_message:
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: 3.2.3
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 3.4.20
52
+ signing_key:
53
+ specification_version: 4
54
+ summary: This gem aims to remove vulnerable functionalities like data marshalling
55
+ to prevent certain types of attacks.
56
+ test_files: []