rumale-torch 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 0ec07a29a0bfa24f06e95a9cd8ca4e80eb61ffcb80d66caa2fc29b9f288bbb70
4
+ data.tar.gz: 4831243f51051c809c73d090424341fffec4b194f9f6e8fb83e648ab5ba4619e
5
+ SHA512:
6
+ metadata.gz: 053ed2b73a9edb5bb44631ed815555ca9bea25dab6de0edaa88bbd3358de07ea488d9c830ed083a99cb62007691512beb8cf68b0380fa440ecdfd22d5c1457c6
7
+ data.tar.gz: 1c483667b49e6bab0d2bd9cf8665b1f5d1f2e7a58f3e70b01800f50dc89d98b3cedd03ad30cb59c441c4c8bb355d63556863bb238081e304e20dfc15cd2d478c
@@ -0,0 +1,33 @@
1
+ name: build
2
+ on: [push, pull_request]
3
+ jobs:
4
+ build:
5
+ runs-on: ubuntu-20.04
6
+ strategy:
7
+ matrix:
8
+ ruby: [ '2.5', '2.6', '2.7' ]
9
+ env:
10
+ LIBTORCH_VERSION: 1.7.1
11
+ steps:
12
+ - uses: actions/checkout@v2
13
+ - name: Set up Ruby ${{ matrix.ruby }}
14
+ uses: actions/setup-ruby@v1
15
+ with:
16
+ ruby-version: ${{ matrix.ruby }}
17
+ - uses: actions/cache@v2
18
+ with:
19
+ path: ~/libtorch
20
+ key: libtorch-${{ env.LIBTORCH_VERSION }}
21
+ id: cache-libtorch
22
+ - name: Download LibTorch
23
+ if: steps.cache-libtorch.outputs.cache-hit != 'true'
24
+ run: |
25
+ cd ~
26
+ wget -q -O libtorch.zip https://download.pytorch.org/libtorch/cpu/libtorch-cxx11-abi-shared-with-deps-$LIBTORCH_VERSION%2Bcpu.zip
27
+ unzip -q libtorch.zip
28
+ - name: Build and test with Rake
29
+ run: |
30
+ gem install bundler
31
+ bundle config build.torch-rb --with-torch-dir=$HOME/libtorch
32
+ bundle install
33
+ bundle exec rake
@@ -0,0 +1,18 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ .DS_Store
14
+ .ruby-version
15
+ tags
16
+ Gemfile.lock
17
+ *.swp
18
+ *.bundle
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,2 @@
1
+ # 0.1.0
2
+ - First 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 yoshoku@outlook.com. 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/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in rumale-torch.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 13.0'
9
+ gem 'rspec', '~> 3.0'
10
+ gem 'simplecov', '~> 0.19'
@@ -0,0 +1,27 @@
1
+ Copyright (c) 2020 Atsushi Tatsuma
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ * Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ * Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ * Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,222 @@
1
+ # Rumale::Torch
2
+
3
+ [![Build Status](https://github.com/yoshoku/rumale-torch/workflows/build/badge.svg)](https://github.com/yoshoku/rumale-torch/actions?query=workflow%3Abuild)
4
+ [![Gem Version](https://badge.fury.io/rb/rumale-torch.svg)](https://badge.fury.io/rb/rumale-torch)
5
+ [![BSD 3-Clause License](https://img.shields.io/badge/License-BSD%203--Clause-orange.svg)](https://github.com/yoshoku/rumale-torch/blob/main/LICENSE.txt)
6
+ [![Documentation](http://img.shields.io/badge/api-reference-blue.svg)](https://yoshoku.github.io/rumale-torch/doc/)
7
+
8
+ Rumale::Torch provides the learning and inference by the neural network defined in [torch.rb](https://github.com/ankane/torch.rb)
9
+ with the same interface as [Rumale](https://github.com/yoshoku/rumale).
10
+
11
+ ## Installation
12
+ torch.rb is a runtime dependent gem of Rumale::Torch. It requires to install [LibTorch](https://github.com/ankane/torch.rb#libtorch-installation):
13
+
14
+ $ brew install automake libtorch
15
+
16
+ Here, automake is needed to install [rice](https://github.com/jasonroelofs/rice) gem, which torch.rb depends on.
17
+
18
+ Add this line to your application's Gemfile:
19
+
20
+ ```ruby
21
+ gem 'rumale-torch'
22
+ ```
23
+
24
+ And then execute:
25
+
26
+ $ bundle install
27
+
28
+ Or install it yourself as:
29
+
30
+ $ gem install rumale-torch
31
+
32
+ ## Usage
33
+
34
+ ### Example 1. Pendigits dataset classification
35
+
36
+ We start by downloading the pendigits dataset from [LIBSVM Data](https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/) web site.
37
+
38
+ ```bash
39
+ $ wget https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/pendigits
40
+ $ wget https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/multiclass/pendigits.t
41
+ ```
42
+
43
+ Training phase:
44
+
45
+ ```ruby
46
+ require 'rumale'
47
+ require 'rumale/torch'
48
+
49
+ Torch.manual_seed(1)
50
+ device = Torch.device('cpu')
51
+
52
+ # Loading pendigits dataset consisting of
53
+ # 16-dimensional data divided into 10 classes.
54
+ x, y = Rumale::Dataset.load_libsvm_file('pendigits')
55
+
56
+ # Define a neural network in torch.rb framework.
57
+ class MyNet < Torch::NN::Module
58
+ def initialize
59
+ super
60
+ @dropout = Torch::NN::Dropout.new(p: 0.5)
61
+ @fc1 = Torch::NN::Linear.new(16, 128)
62
+ @fc2 = Torch::NN::Linear.new(128, 10)
63
+ end
64
+
65
+ def forward(x)
66
+ x = @fc1.call(x)
67
+ x = Torch::NN::F.relu(x)
68
+ x = @dropout.call(x)
69
+ x = @fc2.call(x)
70
+ Torch::NN::F.softmax(x)
71
+ end
72
+ end
73
+
74
+ net = MyNet.new.to(device)
75
+
76
+ # Create a classifier with neural network model.
77
+ classifier = Rumale::Torch::NeuralNetClassifier.new(
78
+ model: net, device: device,
79
+ batch_size: 10, max_epoch: 50, validation_split: 0.1,
80
+ verbose: true
81
+ )
82
+
83
+ # Learning classifier.
84
+ classifier.fit(x, y)
85
+
86
+ # Saving model.
87
+ Torch.save(net.state_dict, 'pendigits.pth')
88
+ File.binwrite('pendigits.dat', Marshal.dump(classifier))
89
+ ```
90
+
91
+ Testing phase:
92
+
93
+ ```ruby
94
+ require 'rumale'
95
+ require 'rumale/torch'
96
+
97
+ # Loading neural network model.
98
+ class MyNet < Torch::NN::Module
99
+ def initialize
100
+ super
101
+ @dropout = Torch::NN::Dropout.new(p: 0.5)
102
+ @fc1 = Torch::NN::Linear.new(16, 128)
103
+ @fc2 = Torch::NN::Linear.new(128, 10)
104
+ end
105
+
106
+ def forward(x)
107
+ x = @fc1.call(x)
108
+ x = Torch::NN::F.relu(x)
109
+ # x = @dropout.call(x)
110
+ x = @fc2.call(x)
111
+ Torch::NN::F.softmax(x)
112
+ end
113
+ end
114
+
115
+ net = MyNet.new
116
+ net.load_state_dict(Torch.load('pendigits.pth'))
117
+
118
+ # Loading classifier.
119
+ classifier = Marshal.load(File.binread('pendigits.dat'))
120
+ classifier.model = net
121
+
122
+ # Loading test dataset.
123
+ x_test, y_test = Rumale::Dataset.load_libsvm_file('pendigits.t')
124
+
125
+ # Predict labels of test data.
126
+ p_test = classifier.predict(x_test)
127
+
128
+ # Evaluate predicted result.
129
+ accuracy = Rumale::EvaluationMeasure::Accuracy.new.score(y_test, p_test)
130
+ puts(format("Accuracy: %2.1f%%", accuracy * 100))
131
+ ```
132
+
133
+ The result of executing the above scripts is as follows:
134
+
135
+ ```sh
136
+ $ ruby train.rb
137
+ epoch: 1/50 - loss: 0.2073 - accuracy: 0.3885 - val_loss: 0.2074 - val_accuracy: 0.3853
138
+ epoch: 2/50 - loss: 0.1973 - accuracy: 0.4883 - val_loss: 0.1970 - val_accuracy: 0.4893
139
+ epoch: 3/50 - loss: 0.1962 - accuracy: 0.4997 - val_loss: 0.1959 - val_accuracy: 0.5013
140
+
141
+ ...
142
+
143
+ epoch: 50/50 - loss: 0.1542 - accuracy: 0.9199 - val_loss: 0.1531 - val_accuracy: 0.9293
144
+
145
+ $ ruby test.rb
146
+ Accuracy: 91.2%
147
+ ```
148
+
149
+ ### Example 2. Cross-validation with Rumale
150
+
151
+ Perform 5-fold cross-validation for regression problem using the housing dataset.
152
+
153
+ ```sh
154
+ $ wget https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/regression/housing
155
+ ```
156
+
157
+ The example script:
158
+
159
+ ```ruby
160
+ require 'rumale'
161
+ require 'rumale/torch'
162
+
163
+ Torch.manual_seed(1)
164
+ device = Torch.device('cpu')
165
+
166
+ # Loading pendigits dataset consisting of
167
+ # 13-dimensional data with single target variable.
168
+ x, y = Rumale::Dataset.load_libsvm_file('housing')
169
+
170
+ # Define a neural network in torch.rb framework.
171
+ class MyNet < Torch::NN::Module
172
+ def initialize
173
+ super
174
+ @fc1 = Torch::NN::Linear.new(13, 128)
175
+ @fc2 = Torch::NN::Linear.new(128, 1)
176
+ end
177
+
178
+ def forward(x)
179
+ x = @fc1.call(x)
180
+ x = Torch::NN::F.relu(x)
181
+ x = @fc2.call(x)
182
+ end
183
+ end
184
+
185
+ net = MyNet.new.to(device)
186
+
187
+ # Create a regressor with neural network model.
188
+ regressor = Rumale::Torch::NeuralNetRegressor.new(
189
+ model: net, device: device, batch_size: 10, max_epoch: 100
190
+ )
191
+
192
+ # Create evaluation measure, splitting strategy, and cross validation.
193
+ ev = Rumale::EvaluationMeasure::R2Score.new
194
+ kf = Rumale::ModelSelection::ShuffleSplit.new(n_splits: 5, test_size: 0.1, random_seed: 1)
195
+ cv = Rumale::ModelSelection::CrossValidation.new(estimator: regressor, splitter: kf, evaluator: ev)
196
+
197
+ # Perform 5-cross validation.
198
+ report = cv.perform(x, y)
199
+
200
+ # Output result.
201
+ mean_score = report[:test_score].sum / kf.n_splits
202
+ puts(format("5-CV R2-score: %.3f", mean_score))
203
+ ```
204
+
205
+ The execution result is as follows:
206
+
207
+ ```ruby
208
+ $ ruby cv.rb
209
+ 5-CV R2-score: 0.755
210
+ ```
211
+
212
+ ## Contributing
213
+
214
+ Bug reports and pull requests are welcome on GitHub at https://github.com/yoshoku/rumale-torch. 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/yoshoku/rumale-torch/blob/master/CODE_OF_CONDUCT.md).
215
+
216
+ ## License
217
+
218
+ The gem is available as open source under the terms of the [BSD-3-Clause License](https://opensource.org/licenses/BSD-3-Clause).
219
+
220
+ ## Code of Conduct
221
+
222
+ Everyone interacting in the Rumale::Torch project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/yoshoku/rumale-torch/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'torch'
4
+ require 'numo/narray'
5
+
6
+ require 'rumale/torch/version'
7
+ require 'rumale/torch/neural_net_classifier'
8
+ require 'rumale/torch/neural_net_regressor'
@@ -0,0 +1,223 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rumale/base/base_estimator'
4
+ require 'rumale/base/classifier'
5
+ require 'rumale/preprocessing/label_encoder'
6
+ require 'rumale/model_selection/function'
7
+
8
+ module Rumale
9
+ module Torch
10
+ # NeuralNetClassifier is a class that provides learning and inference by the neural network defined in torch.rb
11
+ # with an interface similar to classifier of Rumale.
12
+ #
13
+ # @example
14
+ # require 'rumale/torch'
15
+ #
16
+ # class MyNet < Torch::NN::Module
17
+ # def initialize
18
+ # super
19
+ # @dropout = Torch::NN::Dropout.new(p: 0.5)
20
+ # @fc1 = Torch::NN::Linear.new(2, 8)
21
+ # @fc2 = Torch::NN::Linear.new(8, 2)
22
+ # end
23
+ #
24
+ # def forward(x)
25
+ # x = @fc1.call(x)
26
+ # x = Torch::NN::F.relu(x)
27
+ # x = @dropout.call(x)
28
+ # x = @fc2.call(x)
29
+ # Torch::NN::F.softmax(x)
30
+ # end
31
+ # end
32
+ #
33
+ # device = Torch.device('gpu')
34
+ # net = MyNet.new.to(device)
35
+ #
36
+ # classifier = Rumale::Torch::NeuralNetClassifier.new(model: net, device: device, batch_size: 50, max_epoch: 10)
37
+ # classifier.fit(x, y)
38
+ #
39
+ # classifier.predict(x)
40
+ #
41
+ class NeuralNetClassifier
42
+ include Base::BaseEstimator
43
+ include Base::Classifier
44
+
45
+ # Return the class labels.
46
+ # @return [Numo::Int32] (size: n_classes)
47
+ attr_reader :classes
48
+
49
+ # Return the neural nets defined with torch.rb.
50
+ # @return [Torch::NN::Module]
51
+ attr_accessor :model
52
+
53
+ # Return the compute device.
54
+ # @return [Torch::Device]
55
+ attr_accessor :device
56
+
57
+ # Return the optimizer.
58
+ # @return [Torch::Optim]
59
+ attr_accessor :optimizer
60
+
61
+ # Return the loss function.
62
+ # @return [Torch::NN]
63
+ attr_accessor :loss
64
+
65
+ # Create a new classifier with neural nets defined by torch.rb.
66
+ #
67
+ # @param model [Torch::NN::Module] The neural nets defined with torch.rb.
68
+ # @param device [Torch::Device/Nil] The compute device to be used.
69
+ # If nil is given, it to be set to Torch.device('cpu').
70
+ # @param optimizer [Torch::Optim/Nil] The optimizer to be used to optimize the model.
71
+ # If nil is given, it to be set to Torch::Optim::Adam.
72
+ # @param loss [Torch:NN] The loss function to be used to optimize the model.
73
+ # If nil is given, it to be set to Torch::NN::CrossEntropyLoss.
74
+ # @param batch_size [Integer] The number of samples per batch to load.
75
+ # @param max_epoch [Integer] The number of epochs to train the model.
76
+ # @param shuffle [Boolean] The flag indicating whether to shuffle the data at every epoch.
77
+ # @param validation_split [Float] The fraction of the training data to be used as validation data.
78
+ # @param verbose [Boolean] The flag indicating whether to output loss during epoch.
79
+ # @param random_seed [Integer/Nil] The seed value using to initialize the random generator for data splitting.
80
+ def initialize(model:, device: nil, optimizer: nil, loss: nil,
81
+ batch_size: 128, max_epoch: 10, shuffle: true, validation_split: 0,
82
+ verbose: false, random_seed: nil)
83
+ @model = model
84
+ @device = device || ::Torch.device('cpu')
85
+ @optimizer = optimizer || ::Torch::Optim::Adam.new(model.parameters)
86
+ @loss = loss || ::Torch::NN::CrossEntropyLoss.new
87
+ @params = {}
88
+ @params[:batch_size] = batch_size
89
+ @params[:max_epoch] = max_epoch
90
+ @params[:shuffle] = shuffle
91
+ @params[:validation_split] = validation_split
92
+ @params[:verbose] = verbose
93
+ @params[:random_seed] = random_seed || srand
94
+ define_parameter_accessors
95
+ end
96
+
97
+ # Fit the model with given training data.
98
+ #
99
+ # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
100
+ # @param y [Numo::Int32] (shape: [n_samples]) The labels to be used for fitting the model.
101
+ # @return [NeuralNetClassifier] The learned classifier itself.
102
+ def fit(x, y)
103
+ encoder = Rumale::Preprocessing::LabelEncoder.new
104
+ y_encoded = encoder.fit_transform(y)
105
+ @classes = Numo::NArray[*encoder.classes]
106
+
107
+ train_loader, test_loader = prepare_dataset(x, y_encoded)
108
+
109
+ model.children.each do |layer|
110
+ layer.reset_parameters if layer.class.method_defined?(:reset_parameters)
111
+ end
112
+
113
+ 1.upto(max_epoch) do |epoch|
114
+ train(train_loader)
115
+ display_epoch(train_loader, test_loader, epoch) if verbose
116
+ end
117
+
118
+ self
119
+ end
120
+
121
+ # Predict class labels for samples.
122
+ #
123
+ # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to predict the labels.
124
+ # @return [Numo::Int32] (shape: [n_samples]) Predicted class label per sample.
125
+ def predict(x)
126
+ output = ::Torch.no_grad { model.call(::Torch.from_numo(x).to(:float32)) }
127
+ _, indices = ::Torch.max(output, 1)
128
+ @classes[indices.numo].dup
129
+ end
130
+
131
+ # Calculate confidence scores for samples.
132
+ #
133
+ # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to compute the scores.
134
+ # @return [Numo::DFloat] (shape: [n_samples, n_classes]) The confidence score per sample.
135
+ def decision_function(x)
136
+ Numo::DFloat.cast(::Torch.no_grad { model.call(::Torch.from_numo(x).to(:float32)) }.numo)
137
+ end
138
+
139
+ # @!visibility private
140
+ def marshal_dump
141
+ { classes: @classes, params: @params }
142
+ end
143
+
144
+ # @!visibility private
145
+ def marshal_load(obj)
146
+ @model = nil
147
+ @device = nil
148
+ @optimizer = nil
149
+ @loss = nil
150
+ @classes = obj[:classes]
151
+ @params = obj[:params]
152
+ define_parameter_accessors
153
+ end
154
+
155
+ private
156
+
157
+ def define_parameter_accessors
158
+ @params.each_key do |name|
159
+ self.class.send(:define_method, name) { @params[name] }
160
+ self.class.send(:private, name)
161
+ end
162
+ end
163
+
164
+ def prepare_dataset(x, y)
165
+ n_validations = (validation_split * x.shape[0]).ceil.to_i
166
+ return [torch_data_loader(x, y), nil] unless n_validations.positive?
167
+
168
+ x_train, x_test, y_train, y_test = Rumale::ModelSelection.train_test_split(
169
+ x, y, test_size: validation_split, stratify: true, random_seed: random_seed
170
+ )
171
+ [torch_data_loader(x_train, y_train), torch_data_loader(x_test, y_test)]
172
+ end
173
+
174
+ def torch_data_loader(x, y)
175
+ x_tensor = ::Torch.from_numo(x).to(:float32)
176
+ y_tensor = ::Torch.from_numo(y).to(:int64)
177
+ dataset = ::Torch::Utils::Data::TensorDataset.new(x_tensor, y_tensor)
178
+ ::Torch::Utils::Data::DataLoader.new(dataset, batch_size: batch_size, shuffle: shuffle)
179
+ end
180
+
181
+ def train(data_loader)
182
+ model.train
183
+ data_loader.each_with_index do |(data, target), _batch_idx|
184
+ data = data.to(device)
185
+ target = target.to(device)
186
+ optimizer.zero_grad
187
+ output = model.call(data)
188
+ ls = loss.call(output, target)
189
+ ls.backward
190
+ optimizer.step
191
+ end
192
+ end
193
+
194
+ def display_epoch(train_loader, test_loader, epoch)
195
+ if test_loader.nil?
196
+ puts(format("epoch: %#{max_epoch.to_s.length}d/#{max_epoch} - loss: %.4f - accuracy: %.4f", epoch, *evaluate(train_loader)))
197
+ else
198
+ puts(format("epoch: %#{max_epoch.to_s.length}d/#{max_epoch} - loss: %.4f - accuracy: %.4f - val_loss: %.4f - val_accuracy: %.4f", epoch, *evaluate(train_loader), *evaluate(test_loader)))
199
+ end
200
+ end
201
+
202
+ def evaluate(data_loader)
203
+ model.eval
204
+ mean_loss = 0
205
+ correct = 0
206
+ ::Torch.no_grad do
207
+ data_loader.each do |data, target|
208
+ data = data.to(device)
209
+ target = target.to(device)
210
+ output = model.call(data)
211
+ mean_loss += loss.call(output, target).item
212
+ pred = output.argmax(1, keepdim: true).view(-1)
213
+ correct += pred.eq(target.view_as(pred)).sum.item
214
+ end
215
+ end
216
+
217
+ mean_loss /= data_loader.dataset.size
218
+ accuracy = correct.fdiv(data_loader.dataset.size)
219
+ [mean_loss, accuracy]
220
+ end
221
+ end
222
+ end
223
+ end
@@ -0,0 +1,205 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rumale/base/base_estimator'
4
+ require 'rumale/base/regressor'
5
+ require 'rumale/model_selection/shuffle_split'
6
+
7
+ module Rumale
8
+ module Torch
9
+ # NeuralNetRegressor is a class that provides learning and inference by the neural network defined in torch.rb
10
+ # with an interface similar to regressor of Rumale.
11
+ #
12
+ # @example
13
+ # require 'rumale/torch'
14
+ #
15
+ # class MyNet < Torch::NN::Module
16
+ # def initialize
17
+ # super
18
+ # @dropout = Torch::NN::Dropout.new(p: 0.5)
19
+ # @fc1 = Torch::NN::Linear.new(2, 64)
20
+ # @fc2 = Torch::NN::Linear.new(64, 1)
21
+ # end
22
+ #
23
+ # def forward(x)
24
+ # x = @fc1.call(x)
25
+ # x = Torch::NN::F.relu(x)
26
+ # x = @dropout.call(x)
27
+ # @fc2.call(x)
28
+ # end
29
+ # end
30
+ #
31
+ # device = Torch.device('gpu')
32
+ # net = MyNet.new.to(device)
33
+ #
34
+ # regressor = Rumale::Torch::NeuralNetRegressor.new(model: net, device: device, batch_size: 50, max_epoch: 10)
35
+ # regressor.fit(x, y)
36
+ #
37
+ # regressor.predict(x)
38
+ #
39
+ class NeuralNetRegressor
40
+ include Base::BaseEstimator
41
+ include Base::Regressor
42
+
43
+ # Return the neural nets defined with torch.rb.
44
+ # @return [Torch::NN::Module]
45
+ attr_accessor :model
46
+
47
+ # Return the compute device.
48
+ # @return [Torch::Device]
49
+ attr_accessor :device
50
+
51
+ # Return the optimizer.
52
+ # @return [Torch::Optim]
53
+ attr_accessor :optimizer
54
+
55
+ # Return the loss function.
56
+ # @return [Torch::NN]
57
+ attr_accessor :loss
58
+
59
+ # Create a new regressor with neural nets defined by torch.rb.
60
+ #
61
+ # @param model [Torch::NN::Module] The neural nets defined with torch.rb.
62
+ # @param device [Torch::Device/Nil] The compute device to be used.
63
+ # If nil is given, it to be set to Torch.device('cpu').
64
+ # @param optimizer [Torch::Optim/Nil] The optimizer to be used to optimize the model.
65
+ # If nil is given, it to be set to Torch::Optim::Adam.
66
+ # @param loss [Torch:NN] The loss function to be used to optimize the model.
67
+ # If nil is given, it to be set to Torch::NN::MSELoss.
68
+ # @param batch_size [Integer] The number of samples per batch to load.
69
+ # @param max_epoch [Integer] The number of epochs to train the model.
70
+ # @param shuffle [Boolean] The flag indicating whether to shuffle the data at every epoch.
71
+ # @param validation_split [Float] The fraction of the training data to be used as validation data.
72
+ # @param verbose [Boolean] The flag indicating whether to output loss during epoch.
73
+ # @param random_seed [Integer/Nil] The seed value using to initialize the random generator for data splitting.
74
+ def initialize(model:, device: nil, optimizer: nil, loss: nil,
75
+ batch_size: 128, max_epoch: 10, shuffle: true, validation_split: 0,
76
+ verbose: false, random_seed: nil)
77
+ @model = model
78
+ @device = device || ::Torch.device('cpu')
79
+ @optimizer = optimizer || ::Torch::Optim::Adam.new(model.parameters)
80
+ @loss = loss || ::Torch::NN::MSELoss.new
81
+ @params = {}
82
+ @params[:batch_size] = batch_size
83
+ @params[:max_epoch] = max_epoch
84
+ @params[:shuffle] = shuffle
85
+ @params[:validation_split] = validation_split
86
+ @params[:verbose] = verbose
87
+ @params[:random_seed] = random_seed || srand
88
+ define_parameter_accessors
89
+ end
90
+
91
+ # Fit the model with given training data.
92
+ #
93
+ # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The training data to be used for fitting the model.
94
+ # @param y [Numo::DFloat] (shape: [n_samples, n_outputs]) The target values to be used for fitting the model.
95
+ # @return [NeuralNetRegressor] The learned regressor itself.
96
+ def fit(x, y)
97
+ y = y.expand_dims(1) if y.ndim == 1
98
+
99
+ train_loader, test_loader = prepare_dataset(x, y)
100
+
101
+ model.children.each do |layer|
102
+ layer.reset_parameters if layer.class.method_defined?(:reset_parameters)
103
+ end
104
+
105
+ 1.upto(max_epoch) do |epoch|
106
+ train(train_loader)
107
+ display_epoch(train_loader, test_loader, epoch) if verbose
108
+ end
109
+
110
+ self
111
+ end
112
+
113
+ # Predict values for samples.
114
+ #
115
+ # @param x [Numo::DFloat] (shape: [n_samples, n_features]) The samples to predict the values.
116
+ # @return [Numo::DFloat] (shape: [n_samples, n_outputs]) The predicted values per sample.
117
+ def predict(x)
118
+ output = Numo::DFloat.cast(::Torch.no_grad { model.call(::Torch.from_numo(x).to(:float32)) }.numo)
119
+ output.shape[1] == 1 ? output[true, 0].dup : output
120
+ end
121
+
122
+ # @!visibility private
123
+ def marshal_dump
124
+ { params: @params }
125
+ end
126
+
127
+ # @!visibility private
128
+ def marshal_load(obj)
129
+ @model = nil
130
+ @device = nil
131
+ @optimizer = nil
132
+ @loss = nil
133
+ @params = obj[:params]
134
+ define_parameter_accessors
135
+ end
136
+
137
+ private
138
+
139
+ def define_parameter_accessors
140
+ @params.each_key do |name|
141
+ self.class.send(:define_method, name) { @params[name] }
142
+ self.class.send(:private, name)
143
+ end
144
+ end
145
+
146
+ def prepare_dataset(x, y)
147
+ n_validations = (validation_split * x.shape[0]).ceil.to_i
148
+ return [torch_data_loader(x, y), nil] unless n_validations.positive?
149
+
150
+ splitter = Rumale::ModelSelection::ShuffleSplit.new(
151
+ n_splits: 1, test_size: validation_split, random_seed: random_seed
152
+ )
153
+ train_ids, test_ids = splitter.split(x).first
154
+ x_train = x[train_ids, true]
155
+ x_test = x[test_ids, true]
156
+ y_train = y[train_ids, true]
157
+ y_test = y[test_ids, true]
158
+ [torch_data_loader(x_train, y_train), torch_data_loader(x_test, y_test)]
159
+ end
160
+
161
+ def torch_data_loader(x, y)
162
+ x_tensor = ::Torch.from_numo(x).to(:float32)
163
+ y_tensor = ::Torch.from_numo(y).to(:float32)
164
+ dataset = ::Torch::Utils::Data::TensorDataset.new(x_tensor, y_tensor)
165
+ ::Torch::Utils::Data::DataLoader.new(dataset, batch_size: batch_size, shuffle: shuffle)
166
+ end
167
+
168
+ def train(data_loader)
169
+ model.train
170
+ data_loader.each_with_index do |(data, target), _batch_idx|
171
+ data = data.to(device)
172
+ target = target.to(device)
173
+ optimizer.zero_grad
174
+ output = model.call(data)
175
+ ls = loss.call(output, target)
176
+ ls.backward
177
+ optimizer.step
178
+ end
179
+ end
180
+
181
+ def display_epoch(train_loader, test_loader, epoch)
182
+ if test_loader.nil?
183
+ puts(format("epoch: %#{max_epoch.to_s.length}d/#{max_epoch} - loss: %.4f", epoch, evaluate(train_loader)))
184
+ else
185
+ puts(format("epoch: %#{max_epoch.to_s.length}d/#{max_epoch} - loss: %.4f - val_loss: %.4f", epoch, evaluate(train_loader), evaluate(test_loader)))
186
+ end
187
+ end
188
+
189
+ def evaluate(data_loader)
190
+ model.eval
191
+ mean_loss = 0
192
+ ::Torch.no_grad do
193
+ data_loader.each do |data, target|
194
+ data = data.to(device)
195
+ target = target.to(device)
196
+ output = model.call(data)
197
+ mean_loss += loss.call(output, target).item
198
+ end
199
+ end
200
+
201
+ mean_loss / data_loader.dataset.size
202
+ end
203
+ end
204
+ end
205
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Rumale is a machine learning library in Ruby.
4
+ module Rumale
5
+ # Rumale::Torch provides the learning and inference function by
6
+ # the neural nets defined in torch.rb with the same interface as Rumale.
7
+ module Torch
8
+ # The version of Rumale::Torch you are using.
9
+ VERSION = '0.1.0'
10
+ end
11
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/rumale/torch/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'rumale-torch'
7
+ spec.version = Rumale::Torch::VERSION
8
+ spec.authors = ['yoshoku']
9
+ spec.email = ['yoshoku@outlook.com']
10
+
11
+ spec.summary = 'Rumale::Torch provides the learning and inference by the neural network defined in torch.rb with the same interface as Rumale'
12
+ spec.description = 'Rumale::Torch provides the learning and inference by the neural network defined in torch.rb with the same interface as Rumale'
13
+ spec.homepage = 'https://github.com/yoshoku/rumale-torch'
14
+ spec.license = 'BSD-3-Clause'
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = spec.homepage
18
+ spec.metadata['changelog_uri'] = 'https://github.com/yoshoku/rumale-torch/blob/main/CHANGELOG.md'
19
+ spec.metadata['documentation_uri'] = 'https://yoshoku.github.io/rumale-torch/doc/'
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
25
+ end
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ spec.add_runtime_dependency 'rumale'
31
+ spec.add_runtime_dependency 'torch-rb'
32
+ end
metadata ADDED
@@ -0,0 +1,91 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rumale-torch
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - yoshoku
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-12-29 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rumale
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: torch-rb
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: Rumale::Torch provides the learning and inference by the neural network
42
+ defined in torch.rb with the same interface as Rumale
43
+ email:
44
+ - yoshoku@outlook.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".github/workflows/build.yml"
50
+ - ".gitignore"
51
+ - ".rspec"
52
+ - CHANGELOG.md
53
+ - CODE_OF_CONDUCT.md
54
+ - Gemfile
55
+ - LICENSE.txt
56
+ - README.md
57
+ - Rakefile
58
+ - lib/rumale/torch.rb
59
+ - lib/rumale/torch/neural_net_classifier.rb
60
+ - lib/rumale/torch/neural_net_regressor.rb
61
+ - lib/rumale/torch/version.rb
62
+ - rumale-torch.gemspec
63
+ homepage: https://github.com/yoshoku/rumale-torch
64
+ licenses:
65
+ - BSD-3-Clause
66
+ metadata:
67
+ homepage_uri: https://github.com/yoshoku/rumale-torch
68
+ source_code_uri: https://github.com/yoshoku/rumale-torch
69
+ changelog_uri: https://github.com/yoshoku/rumale-torch/blob/main/CHANGELOG.md
70
+ documentation_uri: https://yoshoku.github.io/rumale-torch/doc/
71
+ post_install_message:
72
+ rdoc_options: []
73
+ require_paths:
74
+ - lib
75
+ required_ruby_version: !ruby/object:Gem::Requirement
76
+ requirements:
77
+ - - ">="
78
+ - !ruby/object:Gem::Version
79
+ version: '0'
80
+ required_rubygems_version: !ruby/object:Gem::Requirement
81
+ requirements:
82
+ - - ">="
83
+ - !ruby/object:Gem::Version
84
+ version: '0'
85
+ requirements: []
86
+ rubygems_version: 3.1.4
87
+ signing_key:
88
+ specification_version: 4
89
+ summary: Rumale::Torch provides the learning and inference by the neural network defined
90
+ in torch.rb with the same interface as Rumale
91
+ test_files: []