ltntorch 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.
Files changed (41) hide show
  1. checksums.yaml +7 -0
  2. data/AGENTS.md +34 -0
  3. data/CONTRIBUTING.md +66 -0
  4. data/changelog.md +68 -0
  5. data/code_of_conduct.md +84 -0
  6. data/examples/1_binary_classification.rb +108 -0
  7. data/examples/2_multi_class_single_label_classification.rb +130 -0
  8. data/examples/3_multi_class_multi_label_classification.rb +158 -0
  9. data/examples/4_semi_supervised_pattern_recognition.rb +249 -0
  10. data/examples/5_regression.rb +103 -0
  11. data/examples/6_clustering.rb +126 -0
  12. data/examples/7_learning_embeddings_with_ltn.rb +166 -0
  13. data/examples/datasets/crabs.dat +201 -0
  14. data/examples/datasets/iris_test.csv +31 -0
  15. data/examples/datasets/iris_training.csv +121 -0
  16. data/examples/datasets/readme.md +9 -0
  17. data/examples/datasets/real-estate.csv +415 -0
  18. data/examples/support/example.rb +92 -0
  19. data/examples/support/mnist.rb +77 -0
  20. data/lib/ltn/connective.rb +56 -0
  21. data/lib/ltn/constant.rb +30 -0
  22. data/lib/ltn/diag.rb +54 -0
  23. data/lib/ltn/function.rb +28 -0
  24. data/lib/ltn/fuzzy_ops.rb +428 -0
  25. data/lib/ltn/lambda_model.rb +24 -0
  26. data/lib/ltn/ltn_object.rb +47 -0
  27. data/lib/ltn/model_wrapper.rb +72 -0
  28. data/lib/ltn/predicate.rb +38 -0
  29. data/lib/ltn/process_ltn_objects.rb +58 -0
  30. data/lib/ltn/quantifier.rb +176 -0
  31. data/lib/ltn/variable.rb +49 -0
  32. data/lib/ltn/version.rb +8 -0
  33. data/lib/ltn.rb +45 -0
  34. data/license.md +22 -0
  35. data/readme.md +166 -0
  36. data/sig/ltn.rbs +207 -0
  37. data/tutorials/1_grounding_non_logical_symbols.rb +146 -0
  38. data/tutorials/2_grounding_connectives.rb +126 -0
  39. data/tutorials/2b_operators_and_gradients.rb +78 -0
  40. data/tutorials/3_knowledgebase_and_learning.rb +124 -0
  41. metadata +94 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f9989fe438d5906e6c64b19ad2fd67c5b5582a4747ceb9381d2feba4bee35e3c
4
+ data.tar.gz: 9a0740b3c81d2767e2fd3f6ea22c025613830aa4041b9c69af398c2cbe8bd0f9
5
+ SHA512:
6
+ metadata.gz: a1cc22e1a1937a4d9a959a4b6e949cf0b4770e4b484c67d2acd283466870891cdec4798c96497570af62b6aeecdb1bfbc0004e32af3f64fa2cb519b594f047d3
7
+ data.tar.gz: 840e1596485a959e7d08b5628b04d0bd0b78eb98126b9b8fd84a22079f4dca0af402831b34e90e6a136560fbb1ceedb956e2e56bc1c4a6c9c7f783c504b6a709
data/AGENTS.md ADDED
@@ -0,0 +1,34 @@
1
+ # Tech stack
2
+
3
+ The present project does not use mainstream Ruby gems. Instead it uses:
4
+
5
+ - the [sus](https://github.com/socketry/sus) gem for testing (instead of, e.g., Rspec)
6
+ - the [bake](https://github.com/ioquatix/bake) gem for task management (instead of, e.g., rake)
7
+ - the [standard](https://github.com/standardrb/standard) gem for linting/formatting
8
+ - the [covered](https://github.com/socketry/covered) gem for coverage (instead of, e.g., SimpleCov) -- wired into `sus` via `config/sus.rb`; run with `COVERAGE=BriefSummary bundle exec sus` locally, or `bundle exec bake covered:validate --minimum <ratio>` to check the persisted `.covered.db` against a threshold (what CI does)
9
+ - a gems.rb file instead of a Gemfile
10
+
11
+ # Porting notes
12
+
13
+ This library is a port of [LTNtorch](https://github.com/tommasocarraro/LTNtorch) to [torch.rb](https://github.com/ankane/torch.rb). Unless a difference is documented, behavior (including numerical results) should match LTNtorch's: when in doubt, check the Python source.
14
+
15
+ ## torch.rb pitfalls
16
+
17
+ torch.rb 0.27.0 differs from PyTorch in ways that silently change results (see `TODO_torch-rb.md`):
18
+
19
+ - `<`, `<=`, `>`, `>=` and `==` on tensors are not element-wise: use `lt`, `le`, `gt`, `ge`, `eq`.
20
+ - Write float/tensor arithmetic tensor-first (`x * c`, `Torch.rsub(x, 1.0)` for `1.0 - x`): `Float op Tensor` rounds the float to float32.
21
+ - Use `LTN::FuzzyOps.where` instead of `Torch.where`: with 0-dim tensors that do not require grad, `Torch.where` returns float32.
22
+ - `Torch.tensor(data, requires_grad: true)` returns a non-leaf tensor that never receives gradients: use `Torch.tensor(data).requires_grad!(true)`.
23
+ - `Torch.norm(x, dim: 1)` fails: pass `p` explicitly, `Torch.norm(x, 2, dim: 1)`.
24
+ - `Torch.randint` returns float32 (PyTorch: int64): pass `dtype: :int64` for indices or labels. There is no `one_hot`: use `Torch.eye(n)[labels]`.
25
+
26
+ ## LTN pitfalls
27
+
28
+ - `LTN.diag` changes the labels of its variables, so call it before building the formulas that use them, as in `forall.call(LTN.diag(x, y), p.call(x, y))` (where Ruby evaluates the arguments left to right); a formula built earlier keeps the variables' own labels, and the quantifier leaves them free.
29
+
30
+ ## Examples
31
+
32
+ `examples/` and `tutorials/` port LTNtorch's. Each example is a class whose `#run(epochs:)` returns its final metrics (`test/examples.rb` runs them briefly, `benchmark/examples.rb` fully); `LTNExamples.main` runs it with LTNtorch's settings when the file is executed. Coverage (`config/covered.rb`) only measures `lib/`.
33
+
34
+ Reference values come from LTNtorch itself: `test/fixtures/*.py` generate `test/fixtures/*.json` (see their headers), and new behavior should get a fixture case there, float64 and 0-dim variants included.
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,66 @@
1
+ # Contributing to LTNtorch-rb
2
+
3
+ This document covers the practical mechanics of working on this codebase: setup, running tests, linting, and coverage. For the pull request process, the Developer Certificate of Origin, and the code of conduct, see the "Contributing" section of `readme.md` and `code_of_conduct.md`.
4
+
5
+ ## Tech stack
6
+
7
+ This project uses the same, deliberately less-mainstream, tech stack as [reinforce](https://github.com/DSG-UniFE/reinforce) (see `AGENTS.md` for the short version):
8
+
9
+ - [`sus`](https://github.com/socketry/sus), not RSpec, for testing.
10
+ - [`bake`](https://github.com/ioquatix/bake), not Rake, for task running.
11
+ - [`standard`](https://github.com/standardrb/standard) for linting/formatting.
12
+ - [`covered`](https://github.com/socketry/covered), not SimpleCov, for coverage.
13
+ - `gems.rb`, not `Gemfile`. `gems.locked` is intentionally **not** committed: this is a gem, not an application.
14
+
15
+ ## Setup
16
+
17
+ This project depends on [torch.rb](https://github.com/ankane/torch.rb), which needs a matching LibTorch install to compile its native extension. `.github/workflows/ci.yml` is the source of truth for the exact version (`LIBTORCH_VERSION`); as of this writing, LibTorch 2.15.0 for torch.rb 0.27.x:
18
+
19
+ ```bash
20
+ # macOS (Apple Silicon), either via Homebrew...
21
+ brew install pytorch
22
+ # ...or with the official archive
23
+ curl -L https://download.pytorch.org/libtorch/cpu/libtorch-macos-arm64-2.15.0.zip -o libtorch.zip
24
+ unzip -q libtorch.zip
25
+ bundle config set build.torch-rb --with-torch-dir="$(pwd)/libtorch"
26
+
27
+ # Linux (CPU)
28
+ curl -L https://download.pytorch.org/libtorch/cpu/libtorch-shared-with-deps-2.15.0%2Bcpu.zip -o libtorch.zip
29
+ unzip -q libtorch.zip
30
+ bundle config set build.torch-rb --with-torch-dir="$(pwd)/libtorch"
31
+ ```
32
+
33
+ Then install dependencies:
34
+
35
+ ```bash
36
+ bundle install
37
+ ```
38
+
39
+ ## Running tests
40
+
41
+ ```bash
42
+ bundle exec sus
43
+ ```
44
+
45
+ ## Linting
46
+
47
+ ```bash
48
+ bundle exec standardrb # check
49
+ bundle exec standardrb --fix # auto-fix what's safe to auto-fix
50
+ ```
51
+
52
+ CI runs this as a blocking check with zero tolerated offenses.
53
+
54
+ ## Coverage
55
+
56
+ ```bash
57
+ COVERAGE=BriefSummary bundle exec sus # overall percentage + least-covered files
58
+ COVERAGE=PartialSummary bundle exec sus # only the uncovered code snippets
59
+ bundle exec bake covered:validate --minimum 0.90 # what CI actually checks
60
+ ```
61
+
62
+ ## Code conventions
63
+
64
+ - `lib/<path>.rb` and `test/<path>.rb` mirror each other 1:1 (e.g. `lib/ltn/fuzzy_ops.rb` corresponds to `test/ltn/fuzzy_ops.rb`).
65
+ - This is a port: keep LTNtorch's semantics, including numerical results, unless a deviation is deliberate. Document every deliberate deviation in the code and in `changelog.md`.
66
+ - Ruby idioms replace Python ones where that doesn't change behavior: keyword arguments instead of optional positional ones, `#call` (so `op.(x, y)` works) instead of `__call__`, blocks or lambdas instead of Python `lambda`s, and symbols instead of string flags.
data/changelog.md ADDED
@@ -0,0 +1,68 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ### Added
11
+
12
+ - `LTN::FuzzyOps`, a port of LTNtorch's `ltn.fuzzy_ops`: the projections
13
+ `pi_0`/`pi_1`; the connective operators (`NotStandard`, `NotGodel`,
14
+ `AndMin`, `AndProd`, `AndLuk`, `OrMax`, `OrProbSum`, `OrLuk`,
15
+ `ImpliesKleeneDienes`, `ImpliesGodel`, `ImpliesReichenbach`,
16
+ `ImpliesGoguen`, `ImpliesLuk`, `Equiv`); the aggregators (`AggregMin`,
17
+ `AggregMean`, `AggregPMean`, `AggregPMeanError`), with masks for guarded
18
+ quantification; and `SatAgg`. Optional arguments are keywords
19
+ (`AndProd.new(stable: false)`, `agg.call(xs, dim: [0], p: 3)`), and
20
+ Python's ValueError becomes ArgumentError.
21
+ - `LTN::LTNObject`, a grounding together with the labels of its free
22
+ variables.
23
+ - The core of LTN, ported from LTNtorch's `ltn.core`: `LTN::Constant`
24
+ (optionally trainable), `LTN::Variable`, `LTN.process_ltn_objects` (LTN
25
+ broadcasting), `LTN::Predicate` and `LTN::Function` (grounded by a
26
+ `Torch::NN::Module`, a function given as `func:`, or a block),
27
+ `LTN::LambdaModel`, `LTN.diag`/`LTN.undiag`, `LTN::Connective` and
28
+ `LTN::Quantifier` (with guarded quantification, the guard given as
29
+ `cond_fn:` or a block). Quantifiers take `:forall`/`:exists` (LTNtorch's
30
+ `"f"`/`"e"` work too).
31
+ - Ruby ports of LTNtorch's seven examples (`examples/`, with the Iris,
32
+ crabs and real estate datasets; MNIST is downloaded on first use) and four
33
+ tutorials (`tutorials/`), smoke-tested by `test/examples.rb`, plus a
34
+ seeded learning benchmark of the examples (`benchmark/examples.rb`), run
35
+ by CI as a separate job.
36
+ - Example 4 takes `--default-init` (`init_weights: false`) to keep PyTorch's
37
+ default weight initialization: about 98% test accuracy on MNIST addition,
38
+ as in the LTN paper, instead of the about 48% of LTNtorch's notebook
39
+ initialization, which stays the default.
40
+ - `test/ltn/training_parity.rb`: training a small knowledge base from the
41
+ same data and weights follows LTNtorch's loss at every epoch, from
42
+ `test/fixtures/training.py`.
43
+ - Reference results for the core (broadcasting, predicates, functions,
44
+ connectives, quantifiers, guarded and diagonal quantification, and the
45
+ gradients of a small knowledge base), generated from LTNtorch by
46
+ `test/fixtures/core.py`; float64 and scalar cases for the fuzzy operators.
47
+ - Reference values for every operator and aggregator, gradients included,
48
+ generated from LTNtorch by `test/fixtures/fuzzy_ops.py`.
49
+ - Project scaffolding: `ltntorch` gem with the `LTN` module, `LTN.device`
50
+ configuration, sus/covered test setup, standard linting, and CI on
51
+ Ubuntu (every push) and macOS (scheduled).
52
+
53
+ ### Changed (compared to LTNtorch)
54
+
55
+ - `LTN.process_ltn_objects`, `Quantifier.compute_mask` and
56
+ `Quantifier.transpose_vars` never modify their arguments. LTNtorch rebinds
57
+ the value and free variables of intermediate results it processes, so
58
+ reusing a formula after, e.g., a connective sees the broadcast grounding;
59
+ the computed values are the same.
60
+ - `LTN::Connective#call` passes keyword arguments on to its operator
61
+ (e.g. `stable: false`); LTNtorch accepts and ignores them.
62
+ - `LTN::Variable` converts any float64 individuals to float32; LTNtorch
63
+ only converts CPU ones.
64
+
65
+ ### Fixed (compared to LTNtorch)
66
+
67
+ - `SatAgg` reports the shapes of formulas that are not closed; LTNtorch
68
+ raises an unrelated error while building that message.
@@ -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 mauro.tortonesi@unife.it. 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.
@@ -0,0 +1,108 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Released under the MIT License.
5
+ # Copyright, 2026, by Mauro Tortonesi.
6
+ # Ported from LTNtorch's examples/1-binary_classification.ipynb, copyright 2021-2024 by Tommaso Carraro.
7
+
8
+ # Binary classification: learn a predicate A(x) that holds for the points of
9
+ # [0, 1]^2 within distance 0.3 of (0.5, 0.5), from the knowledge base
10
+ #
11
+ # forall x_A: A(x_A)
12
+ # forall x_not_A: not A(x_not_A)
13
+ #
14
+ # where x_A and x_not_A are the positive and negative training examples.
15
+ #
16
+ # bundle exec ruby examples/1_binary_classification.rb
17
+
18
+ require_relative "support/example"
19
+
20
+ module LTNExamples
21
+ class BinaryClassification
22
+ # The grounding of A: a multi-layer perceptron ending in a sigmoid.
23
+ class ModelA < Torch::NN::Module
24
+ def initialize
25
+ super
26
+ @layer1 = Torch::NN::Linear.new(2, 16)
27
+ @layer2 = Torch::NN::Linear.new(16, 16)
28
+ @layer3 = Torch::NN::Linear.new(16, 1)
29
+ @elu = Torch::NN::ELU.new
30
+ @sigmoid = Torch::NN::Sigmoid.new
31
+ end
32
+
33
+ def forward(x)
34
+ x = @elu.call(@layer1.call(x))
35
+ x = @elu.call(@layer2.call(x))
36
+ @sigmoid.call(@layer3.call(x))
37
+ end
38
+ end
39
+
40
+ attr_reader :a, :dataset, :labels
41
+
42
+ def initialize(seed: 2020, output: $stdout)
43
+ @output = output
44
+ LTNExamples.seed(seed)
45
+
46
+ @dataset = Torch.rand(100, 2)
47
+ @labels = Torch.sum(Torch.square(@dataset - 0.5), dim: 1).lt(0.09)
48
+
49
+ @a = LTN::Predicate.new(ModelA.new)
50
+ @not = LTN::Connective.new(LTN::FuzzyOps::NotStandard.new)
51
+ @forall = LTN::Quantifier.new(LTN::FuzzyOps::AggregPMeanError.new(p: 2), :forall)
52
+ @sat_agg = LTN::FuzzyOps::SatAgg.new
53
+ end
54
+
55
+ # @returns [Hash] the final satisfaction levels and accuracies.
56
+ def run(epochs: 1000, log_every: 20)
57
+ train, test = [@dataset[0...50], @labels[0...50]], [@dataset[50..], @labels[50..]]
58
+ optimizer = Torch::Optim::Adam.new(@a.parameters, lr: 0.001)
59
+
60
+ epochs.times do |epoch|
61
+ train_loss = 0.0
62
+ batches = LTNExamples.batches(train, batch_size: 64, shuffle: true)
63
+ batches.each do |data, labels|
64
+ optimizer.zero_grad
65
+ loss = 1.0 - satisfaction(data, labels)
66
+ loss.backward
67
+ optimizer.step
68
+ train_loss += loss.item
69
+ end
70
+ next unless (epoch % log_every).zero?
71
+
72
+ @output.puts format(" epoch %d | loss %.4f | Train Sat %.3f | Test Sat %.3f | Train Acc %.3f | Test Acc %.3f",
73
+ epoch, train_loss / batches.size, sat_level(*train), sat_level(*test), accuracy(*train), accuracy(*test))
74
+ end
75
+
76
+ {train_sat: sat_level(*train), test_sat: sat_level(*test),
77
+ train_accuracy: accuracy(*train), test_accuracy: accuracy(*test)}
78
+ end
79
+
80
+ # The satisfaction level of the knowledge base on the given examples.
81
+ def satisfaction(data, labels)
82
+ x_a = LTN::Variable.new("x_A", data[labels])
83
+ x_not_a = LTN::Variable.new("x_not_A", data[labels.logical_not])
84
+ @sat_agg.call(
85
+ @forall.call(x_a, @a.call(x_a)),
86
+ @forall.call(x_not_a, @not.call(@a.call(x_not_a)))
87
+ )
88
+ end
89
+
90
+ def sat_level(data, labels)
91
+ Torch.no_grad { satisfaction(data, labels).item }
92
+ end
93
+
94
+ def accuracy(data, labels)
95
+ predictions = Torch.no_grad { @a.model.call(data).squeeze(1).gt(0.5) }
96
+ LTNExamples.accuracy(predictions, labels)
97
+ end
98
+ end
99
+ end
100
+
101
+ LTNExamples.main(LTNExamples::BinaryClassification.new, __FILE__) do |example|
102
+ points, labels = example.dataset[50..], example.labels[50..]
103
+ predicted = Torch.no_grad { example.a.model.call(points).squeeze(1).gt(0.5) }
104
+ [["Ground truth (test data)", labels], ["A(x) > 0.5 (test data)", predicted]].each do |title, mask|
105
+ puts
106
+ puts LTNExamples.scatter({"A" => ["#", points[mask]], "not A" => [".", points[mask.logical_not]]}, title: title)
107
+ end
108
+ end
@@ -0,0 +1,130 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Released under the MIT License.
5
+ # Copyright, 2026, by Mauro Tortonesi.
6
+ # Ported from LTNtorch's examples/2-multi_class_single_label_classification.ipynb, copyright 2021-2024 by
7
+ # Tommaso Carraro.
8
+
9
+ # Multi-class single-label classification of the Iris dataset: learn a
10
+ # predicate P(x, l), "example x has label l", from the knowledge base
11
+ #
12
+ # forall x_A: P(x_A, l_A)
13
+ # forall x_B: P(x_B, l_B)
14
+ # forall x_C: P(x_C, l_C)
15
+ #
16
+ # where l_A, l_B, l_C are one-hot constants for the three species. P is a
17
+ # softmax classifier, so each example has exactly one label.
18
+ #
19
+ # bundle exec ruby examples/2_multi_class_single_label_classification.rb
20
+
21
+ require_relative "support/example"
22
+
23
+ module LTNExamples
24
+ class MultiClassSingleLabelClassification
25
+ # Returns the logits of the classes of x (the softmax is applied by
26
+ # LogitsToPredicate, so that the logits can be used for accuracy).
27
+ class MLP < Torch::NN::Module
28
+ def initialize(layer_sizes = [4, 16, 16, 8, 3])
29
+ super()
30
+ @elu = Torch::NN::ELU.new
31
+ @dropout = Torch::NN::Dropout.new(p: 0.2)
32
+ @linear_layers = Torch::NN::ModuleList.new(
33
+ layer_sizes.each_cons(2).map { |input, output| Torch::NN::Linear.new(input, output) }
34
+ )
35
+ end
36
+
37
+ def forward(x, training: false)
38
+ @linear_layers.to_a[0...-1].each do |layer|
39
+ x = @elu.call(layer.call(x))
40
+ x = @dropout.call(x) if training
41
+ end
42
+ @linear_layers.to_a.last.call(x)
43
+ end
44
+ end
45
+
46
+ # The truth value of P(x, l): the softmax probability of the class l
47
+ # (one-hot) of example x.
48
+ class LogitsToPredicate < Torch::NN::Module
49
+ def initialize(logits_model)
50
+ super()
51
+ @logits_model = logits_model
52
+ @softmax = Torch::NN::Softmax.new(dim: 1)
53
+ end
54
+
55
+ def forward(x, l, training: false)
56
+ probabilities = @softmax.call(@logits_model.call(x, training: training))
57
+ Torch.sum(probabilities * l, dim: 1)
58
+ end
59
+ end
60
+
61
+ def initialize(seed: 2020, output: $stdout)
62
+ @output = output
63
+ LTNExamples.seed(seed)
64
+
65
+ @train = load("iris_training.csv")
66
+ @test = load("iris_test.csv")
67
+
68
+ @l_a = LTN::Constant.new(Torch.tensor([1, 0, 0]))
69
+ @l_b = LTN::Constant.new(Torch.tensor([0, 1, 0]))
70
+ @l_c = LTN::Constant.new(Torch.tensor([0, 0, 1]))
71
+
72
+ @mlp = MLP.new
73
+ @p = LTN::Predicate.new(LogitsToPredicate.new(@mlp))
74
+ @forall = LTN::Quantifier.new(LTN::FuzzyOps::AggregPMeanError.new(p: 2), :forall)
75
+ @sat_agg = LTN::FuzzyOps::SatAgg.new
76
+ end
77
+
78
+ def run(epochs: 500, log_every: 20)
79
+ optimizer = Torch::Optim::Adam.new(@p.parameters, lr: 0.001)
80
+
81
+ epochs.times do |epoch|
82
+ train_loss = 0.0
83
+ batches = LTNExamples.batches(@train, batch_size: 64, shuffle: true)
84
+ batches.each do |data, labels|
85
+ optimizer.zero_grad
86
+ loss = 1.0 - satisfaction(data, labels, training: true)
87
+ loss.backward
88
+ optimizer.step
89
+ train_loss += loss.item
90
+ end
91
+ next unless (epoch % log_every).zero?
92
+
93
+ @output.puts format(" epoch %d | loss %.4f | Train Sat %.3f | Test Sat %.3f | Train Acc %.3f | Test Acc %.3f",
94
+ epoch, train_loss / batches.size, sat_level(*@train), sat_level(*@test), accuracy(*@train), accuracy(*@test))
95
+ end
96
+
97
+ {train_sat: sat_level(*@train), test_sat: sat_level(*@test),
98
+ train_accuracy: accuracy(*@train), test_accuracy: accuracy(*@test)}
99
+ end
100
+
101
+ def satisfaction(data, labels, training: false)
102
+ x_a = LTN::Variable.new("x_A", data[labels.eq(0)])
103
+ x_b = LTN::Variable.new("x_B", data[labels.eq(1)])
104
+ x_c = LTN::Variable.new("x_C", data[labels.eq(2)])
105
+ @sat_agg.call(
106
+ @forall.call(x_a, @p.call(x_a, @l_a, training: training)),
107
+ @forall.call(x_b, @p.call(x_b, @l_b, training: training)),
108
+ @forall.call(x_c, @p.call(x_c, @l_c, training: training))
109
+ )
110
+ end
111
+
112
+ def sat_level(data, labels)
113
+ Torch.no_grad { satisfaction(data, labels).item }
114
+ end
115
+
116
+ def accuracy(data, labels)
117
+ predictions = Torch.no_grad { Torch.argmax(@mlp.call(data), dim: 1) }
118
+ LTNExamples.accuracy(predictions, labels)
119
+ end
120
+
121
+ private
122
+
123
+ def load(name)
124
+ _, rows = LTNExamples.read_table(name)
125
+ [Torch.tensor(rows.map { |row| row[0...4].map(&:to_f) }), Torch.tensor(rows.map { |row| Integer(row[4]) })]
126
+ end
127
+ end
128
+ end
129
+
130
+ LTNExamples.main(LTNExamples::MultiClassSingleLabelClassification.new, __FILE__)
@@ -0,0 +1,158 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # Released under the MIT License.
5
+ # Copyright, 2026, by Mauro Tortonesi.
6
+ # Ported from LTNtorch's examples/3-multi_class_multi_label_classification.ipynb, copyright 2021-2024 by
7
+ # Tommaso Carraro.
8
+
9
+ # Multi-class multi-label classification of the Leptograpsus crabs dataset:
10
+ # each crab has a color (blue or orange) and a sex (male or female). Learn a
11
+ # predicate P(x, l), "crab x has label l", from the knowledge base
12
+ #
13
+ # forall x_blue: P(x_blue, l_blue) (and likewise for orange, male, female)
14
+ # forall x: not (P(x, l_blue) and P(x, l_orange))
15
+ # forall x: not (P(x, l_male) and P(x, l_female))
16
+ #
17
+ # P is a sigmoid classifier, so the labels are learned independently, and the
18
+ # last two axioms state that they are mutually exclusive. After training, the
19
+ # script also queries three formulas the knowledge base does not state:
20
+ #
21
+ # phi1: forall x: P(x, l_blue) -> not P(x, l_orange) (implied by the axioms)
22
+ # phi2: forall x: P(x, l_blue) -> P(x, l_orange) (contradicted by them)
23
+ # phi3: forall x: P(x, l_blue) -> P(x, l_male) (independent of them)
24
+ #
25
+ # bundle exec ruby examples/3_multi_class_multi_label_classification.rb
26
+
27
+ require_relative "support/example"
28
+
29
+ module LTNExamples
30
+ class MultiClassMultiLabelClassification
31
+ # Returns the logits of the four labels of x.
32
+ class MLP < Torch::NN::Module
33
+ def initialize(layer_sizes = [5, 16, 16, 8, 4])
34
+ super()
35
+ @elu = Torch::NN::ELU.new
36
+ @dropout = Torch::NN::Dropout.new(p: 0.2)
37
+ @linear_layers = Torch::NN::ModuleList.new(
38
+ layer_sizes.each_cons(2).map { |input, output| Torch::NN::Linear.new(input, output) }
39
+ )
40
+ end
41
+
42
+ def forward(x, training: false)
43
+ @linear_layers.to_a[0...-1].each do |layer|
44
+ x = @elu.call(layer.call(x))
45
+ x = @dropout.call(x) if training
46
+ end
47
+ @linear_layers.to_a.last.call(x)
48
+ end
49
+ end
50
+
51
+ # The truth value of P(x, l): the sigmoid probability of the label l
52
+ # (one-hot) of example x.
53
+ class LogitsToPredicate < Torch::NN::Module
54
+ def initialize(logits_model)
55
+ super()
56
+ @logits_model = logits_model
57
+ @sigmoid = Torch::NN::Sigmoid.new
58
+ end
59
+
60
+ def forward(x, l, training: false)
61
+ Torch.sum(@sigmoid.call(@logits_model.call(x, training: training)) * l, dim: 1)
62
+ end
63
+ end
64
+
65
+ # Label codes, as in LTNtorch: colors 0 (blue) and 1 (orange), sexes 2 (male) and 3 (female).
66
+ CODES = {"B" => 0, "O" => 1, "M" => 2, "F" => 3}.freeze
67
+
68
+ def initialize(seed: 2020, output: $stdout)
69
+ @output = output
70
+ LTNExamples.seed(seed)
71
+
72
+ header, rows = LTNExamples.read_table("crabs.dat", separator: /\s+/)
73
+ rows = rows.values_at(*Torch.randperm(rows.size).to_a) # shuffle, as LTNtorch does
74
+ features = Torch.tensor(rows.map { |row| %w[FL RW CL CW BD].map { |column| Float(row[header.index(column)]) } })
75
+ sex = Torch.tensor(rows.map { |row| CODES.fetch(row[header.index("sex")]) })
76
+ color = Torch.tensor(rows.map { |row| CODES.fetch(row[header.index("sp")]) })
77
+ @train = [features[0...160], sex[0...160], color[0...160]]
78
+ @test = [features[160..], sex[160..], color[160..]]
79
+
80
+ @l_blue, @l_orange, @l_male, @l_female = Torch.eye(4).to_a.map { |onehot| LTN::Constant.new(Torch.tensor(onehot)) }
81
+
82
+ @mlp = MLP.new
83
+ @p = LTN::Predicate.new(LogitsToPredicate.new(@mlp))
84
+ @not = LTN::Connective.new(LTN::FuzzyOps::NotStandard.new)
85
+ @and = LTN::Connective.new(LTN::FuzzyOps::AndProd.new)
86
+ @implies = LTN::Connective.new(LTN::FuzzyOps::ImpliesReichenbach.new)
87
+ @forall = LTN::Quantifier.new(LTN::FuzzyOps::AggregPMeanError.new(p: 2), :forall)
88
+ @sat_agg = LTN::FuzzyOps::SatAgg.new
89
+ end
90
+
91
+ def run(epochs: 500, log_every: 20)
92
+ optimizer = Torch::Optim::Adam.new(@p.parameters, lr: 0.001)
93
+
94
+ epochs.times do |epoch|
95
+ train_loss = 0.0
96
+ batches = LTNExamples.batches(@train, batch_size: 64, shuffle: true)
97
+ batches.each do |data, sex, color|
98
+ optimizer.zero_grad
99
+ loss = 1.0 - satisfaction(data, sex, color)
100
+ loss.backward
101
+ optimizer.step
102
+ train_loss += loss.item
103
+ end
104
+ next unless (epoch % log_every).zero?
105
+
106
+ @output.puts format(" epoch %d | loss %.4f | Train Sat %.3f | Test Sat %.3f | Train Acc %.3f | " \
107
+ "Test Acc %.3f | Test Sat Phi 1 %.3f | Test Sat Phi 2 %.3f | Test Sat Phi 3 %.3f",
108
+ epoch, train_loss / batches.size, sat_level(*@train), sat_level(*@test), accuracy(*@train),
109
+ accuracy(*@test), *(1..3).map { |i| phi(i, @test[0]) })
110
+ end
111
+
112
+ {train_sat: sat_level(*@train), test_sat: sat_level(*@test),
113
+ train_accuracy: accuracy(*@train), test_accuracy: accuracy(*@test),
114
+ phi1: phi(1, @test[0]), phi2: phi(2, @test[0]), phi3: phi(3, @test[0])}
115
+ end
116
+
117
+ def satisfaction(data, sex, color)
118
+ x = LTN::Variable.new("x", data)
119
+ x_blue = LTN::Variable.new("x_blue", data[color.eq(0)])
120
+ x_orange = LTN::Variable.new("x_orange", data[color.eq(1)])
121
+ x_male = LTN::Variable.new("x_male", data[sex.eq(2)])
122
+ x_female = LTN::Variable.new("x_female", data[sex.eq(3)])
123
+ @sat_agg.call(
124
+ @forall.call(x_blue, @p.call(x_blue, @l_blue)),
125
+ @forall.call(x_orange, @p.call(x_orange, @l_orange)),
126
+ @forall.call(x_male, @p.call(x_male, @l_male)),
127
+ @forall.call(x_female, @p.call(x_female, @l_female)),
128
+ @forall.call(x, @not.call(@and.call(@p.call(x, @l_blue), @p.call(x, @l_orange)))),
129
+ @forall.call(x, @not.call(@and.call(@p.call(x, @l_male), @p.call(x, @l_female))))
130
+ )
131
+ end
132
+
133
+ def sat_level(data, sex, color)
134
+ Torch.no_grad { satisfaction(data, sex, color).item }
135
+ end
136
+
137
+ # The truth value of one of the queries phi1, phi2, phi3 on the given examples.
138
+ def phi(index, data)
139
+ Torch.no_grad do
140
+ x = LTN::Variable.new("x", data)
141
+ blue = @p.call(x, @l_blue)
142
+ consequent = {1 => -> { @not.call(@p.call(x, @l_orange)) }, 2 => -> { @p.call(x, @l_orange) },
143
+ 3 => -> { @p.call(x, @l_male) }}.fetch(index).call
144
+ @forall.call(x, @implies.call(blue, consequent), p: 5).value.item
145
+ end
146
+ end
147
+
148
+ # One minus the Hamming loss of the four labels. Like LTNtorch, it
149
+ # thresholds the logits (not the probabilities) at 0.5.
150
+ def accuracy(data, sex, color)
151
+ predictions = Torch.no_grad { @mlp.call(data).gt(0.5) }
152
+ onehot = Torch.stack([color.eq(0), color.eq(1), sex.eq(2), sex.eq(3)], dim: -1)
153
+ predictions.eq(onehot).float.mean.item
154
+ end
155
+ end
156
+ end
157
+
158
+ LTNExamples.main(LTNExamples::MultiClassMultiLabelClassification.new, __FILE__)