learningmachine 0.2.2__tar.gz → 1.1.0__tar.gz

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 (34) hide show
  1. {learningmachine-0.2.2 → learningmachine-1.1.0}/PKG-INFO +7 -4
  2. learningmachine-1.1.0/learningmachine/__init__.py +10 -0
  3. learningmachine-1.1.0/learningmachine/base.py +213 -0
  4. learningmachine-1.1.0/learningmachine/classifier.py +134 -0
  5. learningmachine-1.1.0/learningmachine/regression.py +92 -0
  6. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine/utils.py +12 -0
  7. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine.egg-info/PKG-INFO +7 -4
  8. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine.egg-info/SOURCES.txt +2 -1
  9. learningmachine-1.1.0/setup.py +220 -0
  10. learningmachine-0.2.2/learningmachine/__init__.py +0 -11
  11. learningmachine-0.2.2/learningmachine/base.py +0 -18
  12. learningmachine-0.2.2/learningmachine/basemodels.py +0 -112
  13. learningmachine-0.2.2/setup.py +0 -175
  14. {learningmachine-0.2.2 → learningmachine-1.1.0}/CONTRIBUTING.rst +0 -0
  15. {learningmachine-0.2.2 → learningmachine-1.1.0}/HISTORY.rst +0 -0
  16. {learningmachine-0.2.2 → learningmachine-1.1.0}/LICENSE +0 -0
  17. {learningmachine-0.2.2 → learningmachine-1.1.0}/MANIFEST.in +0 -0
  18. {learningmachine-0.2.2 → learningmachine-1.1.0}/README.rst +0 -0
  19. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/Makefile +0 -0
  20. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/conf.py +0 -0
  21. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/contributing.rst +0 -0
  22. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/history.rst +0 -0
  23. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/index.rst +0 -0
  24. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/installation.rst +0 -0
  25. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/make.bat +0 -0
  26. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/readme.rst +0 -0
  27. {learningmachine-0.2.2 → learningmachine-1.1.0}/docs/usage.rst +0 -0
  28. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine.egg-info/dependency_links.txt +0 -0
  29. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine.egg-info/not-zip-safe +0 -0
  30. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine.egg-info/requires.txt +0 -0
  31. {learningmachine-0.2.2 → learningmachine-1.1.0}/learningmachine.egg-info/top_level.txt +0 -0
  32. {learningmachine-0.2.2 → learningmachine-1.1.0}/setup.cfg +0 -0
  33. {learningmachine-0.2.2 → learningmachine-1.1.0}/tests/__init__.py +0 -0
  34. {learningmachine-0.2.2 → learningmachine-1.1.0}/tests/test_learningmachine.py +0 -0
@@ -1,13 +1,12 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: learningmachine
3
- Version: 0.2.2
3
+ Version: 1.1.0
4
4
  Summary: Machine Learning with uncertainty quantification and interpretability
5
- Home-page: https://github.com/Techtonique/learningmachine
5
+ Home-page: https://github.com/Techtonique/learningmachine_python
6
6
  Author: T. Moudiki
7
7
  Author-email: thierry.moudiki@gmail.com
8
8
  License: BSD Clause Clear license
9
9
  Keywords: learningmachine
10
- Platform: UNKNOWN
11
10
  Classifier: Development Status :: 2 - Pre-Alpha
12
11
  Classifier: Intended Audience :: Developers
13
12
  Classifier: License :: OSI Approved :: BSD License
@@ -18,6 +17,10 @@ Classifier: Programming Language :: Python :: 3.7
18
17
  Classifier: Programming Language :: Python :: 3.8
19
18
  Requires-Python: >=3.6
20
19
  License-File: LICENSE
20
+ Requires-Dist: numpy
21
+ Requires-Dist: pandas
22
+ Requires-Dist: rpy2>=3.4.5
23
+ Requires-Dist: scikit-learn
24
+ Requires-Dist: scipy
21
25
 
22
26
  Machine Learning with uncertainty quantification and interpretability.
23
-
@@ -0,0 +1,10 @@
1
+ """Top-level package for learningmachine."""
2
+
3
+ __author__ = """T. Moudiki"""
4
+ __email__ = "thierry.moudiki@gmail.com"
5
+
6
+ from .base import Base
7
+ from .classifier import Classifier
8
+ from .regression import Regressor
9
+
10
+ __all__ = ["Base", "Classifier", "Regressor"]
@@ -0,0 +1,213 @@
1
+ import sklearn.metrics as skm
2
+ import subprocess
3
+ from functools import lru_cache
4
+ from sklearn.base import BaseEstimator
5
+ from rpy2.robjects.vectors import StrVector
6
+ from rpy2.robjects.packages import importr
7
+ from rpy2.robjects import r
8
+
9
+ base = importr("base")
10
+ stats = importr("stats")
11
+ utils = importr("utils")
12
+
13
+
14
+ class Base(BaseEstimator):
15
+ """
16
+ Base class.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ type=None,
22
+ name="Base",
23
+ method="ranger",
24
+ pi_method="kdesplitconformal",
25
+ level=95,
26
+ type_prediction_set="score",
27
+ B=100,
28
+ nb_hidden = 0,
29
+ nodes_sim = "sobol",
30
+ activ = "relu",
31
+ params=None,
32
+ seed=123,
33
+ ):
34
+ """
35
+ Initialize the model.
36
+ """
37
+ super().__init__()
38
+ self.name = name
39
+ self.type = type
40
+ self.method = method
41
+ self.pi_method = pi_method
42
+ self.level = level
43
+ self.type_prediction_set = type_prediction_set
44
+ self.B = B
45
+ self.nb_hidden = nb_hidden
46
+ assert nodes_sim in ("sobol", "halton", "unif"), \
47
+ "must have nodes_sim in ('sobol', 'halton', 'unif')"
48
+ self.nodes_sim = "sobol"
49
+ assert activ in ("relu", "sigmoid", "tanh",
50
+ "leakyrelu", "elu", "linear"), \
51
+ "must have activ in ('relu', 'sigmoid', 'tanh', 'leakyrelu', 'elu', 'linear')"
52
+ self.activ = activ
53
+ self.params = params
54
+ self.seed = seed
55
+ self.obj = None
56
+
57
+ @lru_cache
58
+ def load_learningmachine(self):
59
+ # Install R packages
60
+ commands1_lm = 'base::system.file(package = "learningmachine")' # check "learningmachine" is installed
61
+ commands2_lm = 'base::system.file("learningmachine_r", package = "learningmachine")' # check "learningmachine" is installed locally
62
+ exec_commands1_lm = subprocess.run(
63
+ ["Rscript", "-e", commands1_lm], capture_output=True, text=True
64
+ )
65
+ exec_commands2_lm = subprocess.run(
66
+ ["Rscript", "-e", commands2_lm], capture_output=True, text=True
67
+ )
68
+ if (
69
+ len(exec_commands1_lm.stdout) == 7
70
+ and len(exec_commands2_lm.stdout) == 7
71
+ ): # kind of convoluted, but works
72
+ print("Installing R packages along with 'learningmachine'...")
73
+ commands1 = [
74
+ 'try(utils::install.packages(c("R6", "Rcpp", "skimr"), repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
75
+ 'try(utils::install.packages("learningmachine", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=FALSE)',
76
+ ]
77
+ commands2 = [
78
+ 'try(utils::install.packages(c("R6", "Rcpp", "skimr"), lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
79
+ 'try(utils::install.packages("learningmachine", lib="./learningmachine_r", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=FALSE)',
80
+ ]
81
+ try:
82
+ for cmd in commands1:
83
+ subprocess.run(["Rscript", "-e", cmd])
84
+ except NotImplementedError as e: # can't install packages globally
85
+ subprocess.run(["mkdir", "learningmachine_r"])
86
+ for cmd in commands2:
87
+ subprocess.run(["Rscript", "-e", cmd])
88
+
89
+ try:
90
+ base.library(StrVector(["learningmachine"]))
91
+ except (
92
+ NotImplementedError
93
+ ) as e1: # can't load the package from the global environment
94
+ try:
95
+ base.library(
96
+ StrVector(["learningmachine"]),
97
+ lib_loc="learningmachine_r",
98
+ )
99
+ except NotImplementedError as e2: # well, we tried
100
+ try:
101
+ r("try(library('learningmachine'), silence=FALSE)")
102
+ except (
103
+ NotImplementedError
104
+ ) as e3: # well, we tried everything at this point
105
+ r(
106
+ "try(library('learningmachine', lib.loc='learningmachine_r'), silence=FALSE)"
107
+ )
108
+
109
+ def score(self, X, y, scoring=None, **kwargs):
110
+ """Score the model on test set features X and response y.
111
+
112
+ Parameters:
113
+
114
+ X: {array-like}, shape = [n_samples, n_features]
115
+ Training vectors, where n_samples is the number
116
+ of samples and n_features is the number of features
117
+
118
+ y: array-like, shape = [n_samples]
119
+ Target values
120
+
121
+ scoring: str
122
+ must be in ('explained_variance', 'neg_mean_absolute_error',
123
+ 'neg_mean_squared_error', 'neg_mean_squared_log_error',
124
+ 'neg_median_absolute_error', 'r2')
125
+
126
+ **kwargs: additional parameters to be passed to scoring functions
127
+
128
+ Returns:
129
+
130
+ model scores: {array-like}
131
+
132
+ """
133
+
134
+ preds = self.predict(X)
135
+
136
+ if self.type == "classification":
137
+
138
+ if scoring is None:
139
+ scoring = "accuracy"
140
+
141
+ # check inputs
142
+ assert scoring in (
143
+ "accuracy",
144
+ "average_precision",
145
+ "brier_score_loss",
146
+ "f1",
147
+ "f1_micro",
148
+ "f1_macro",
149
+ "f1_weighted",
150
+ "f1_samples",
151
+ "neg_log_loss",
152
+ "precision",
153
+ "recall",
154
+ "roc_auc",
155
+ ), "'scoring' should be in ('accuracy', 'average_precision', \
156
+ 'brier_score_loss', 'f1', 'f1_micro', \
157
+ 'f1_macro', 'f1_weighted', 'f1_samples', \
158
+ 'neg_log_loss', 'precision', 'recall', \
159
+ 'roc_auc')"
160
+
161
+ scoring_options = {
162
+ "accuracy": skm.accuracy_score,
163
+ "average_precision": skm.average_precision_score,
164
+ "brier_score_loss": skm.brier_score_loss,
165
+ "f1": skm.f1_score,
166
+ "f1_micro": skm.f1_score,
167
+ "f1_macro": skm.f1_score,
168
+ "f1_weighted": skm.f1_score,
169
+ "f1_samples": skm.f1_score,
170
+ "neg_log_loss": skm.log_loss,
171
+ "precision": skm.precision_score,
172
+ "recall": skm.recall_score,
173
+ "roc_auc": skm.roc_auc_score,
174
+ }
175
+
176
+ try:
177
+ preds = preds.ravel().astype(int)
178
+ return scoring_options[scoring](y, preds, **kwargs)
179
+ except:
180
+ return scoring_options[scoring](y, preds, **kwargs)
181
+
182
+ if self.type == "regression":
183
+
184
+ if (
185
+ type(preds) == tuple
186
+ ): # if there are std. devs in the predictions
187
+ preds = preds[0]
188
+
189
+ if scoring is None:
190
+ scoring = "neg_mean_squared_error"
191
+
192
+ # check inputs
193
+ assert scoring in (
194
+ "explained_variance",
195
+ "neg_mean_absolute_error",
196
+ "neg_mean_squared_error",
197
+ "neg_mean_squared_log_error",
198
+ "neg_median_absolute_error",
199
+ "r2",
200
+ ), "'scoring' should be in ('explained_variance', 'neg_mean_absolute_error', \
201
+ 'neg_mean_squared_error', 'neg_mean_squared_log_error', \
202
+ 'neg_median_absolute_error', 'r2')"
203
+
204
+ scoring_options = {
205
+ "explained_variance": skm.explained_variance_score,
206
+ "neg_mean_absolute_error": skm.median_absolute_error,
207
+ "neg_mean_squared_error": skm.mean_squared_error,
208
+ "neg_mean_squared_log_error": skm.mean_squared_log_error,
209
+ "neg_median_absolute_error": skm.median_absolute_error,
210
+ "r2": skm.r2_score,
211
+ }
212
+
213
+ return scoring_options[scoring](y, preds, **kwargs)
@@ -0,0 +1,134 @@
1
+ import numpy as np
2
+ import sklearn.metrics as skm
3
+ from rpy2.robjects import r
4
+ from rpy2.robjects.packages import importr
5
+ from rpy2.robjects.vectors import (
6
+ FloatMatrix,
7
+ FloatVector,
8
+ IntVector,
9
+ FactorVector,
10
+ )
11
+ from sklearn.base import ClassifierMixin
12
+ from .base import Base
13
+ from .utils import format_value
14
+
15
+ base = importr("base")
16
+ stats = importr("stats")
17
+ utils = importr("utils")
18
+
19
+
20
+ class Classifier(Base, ClassifierMixin):
21
+ """
22
+ Classifier.
23
+ """
24
+
25
+ def __init__(
26
+ self,
27
+ method="ranger",
28
+ pi_method="kdesplitconformal",
29
+ level=95,
30
+ type_prediction_set="score",
31
+ B=100,
32
+ nb_hidden = 0,
33
+ nodes_sim = "sobol",
34
+ activ = "relu",
35
+ seed=123,
36
+ ):
37
+ """
38
+ Initialize the model.
39
+ """
40
+ super().__init__(
41
+ name = "Classifier",
42
+ type = "classification",
43
+ method=method,
44
+ pi_method=pi_method,
45
+ level=level,
46
+ type_prediction_set=type_prediction_set,
47
+ B=B,
48
+ nb_hidden=nb_hidden,
49
+ nodes_sim=nodes_sim,
50
+ activ=activ,
51
+ seed=seed,
52
+ )
53
+
54
+ try:
55
+ self.load_learningmachine()
56
+ self.obj = r(
57
+ f"learningmachine::Classifier$new(method = {format_value(self.method)}, pi_method = {format_value(self.pi_method)}, level = {format_value(self.level)}, type_prediction_set = {format_value(self.type_prediction_set)}, B = {format_value(self.B)}, nb_hidden = {format_value(self.nb_hidden)}, nodes_sim = {format_value(self.nodes_sim)}, activ = {format_value(self.activ)}, seed = {format_value(self.seed)})"
58
+ )
59
+ except NotImplementedError as e:
60
+ try:
61
+ r.library("learningmachine")
62
+ self.obj = r(
63
+ f"Classifier$new(method = {format_value(self.method)}, pi_method = {format_value(self.pi_method)}, level = {format_value(self.level)}, type_prediction_set = {format_value(self.type_prediction_set)}, B = {format_value(self.B)}, nb_hidden = {format_value(self.nb_hidden)}, nodes_sim = {format_value(self.nodes_sim)}, activ = {format_value(self.activ)}, seed = {format_value(self.seed)})"
64
+ )
65
+ except NotImplementedError as e:
66
+ try:
67
+ self.obj = r(
68
+ f"""
69
+ library(learningmachine);
70
+ Classifier$new(method = {format_value(self.method)}, pi_method = {format_value(self.pi_method)}, level = {format_value(self.level)}, type_prediction_set = {format_value(self.type_prediction_set)}, B = {format_value(self.B)}, nb_hidden = {format_value(self.nb_hidden)}, nodes_sim = {format_value(self.nodes_sim)}, activ = {format_value(self.activ)}, seed = {format_value(self.seed)})
71
+ """
72
+ )
73
+ except NotImplementedError as e:
74
+ print("R package can't be loaded: ", e)
75
+
76
+ def fit(self, X, y):
77
+ """
78
+ Fit the model according to the given training data.
79
+ """
80
+ self.obj["fit"](
81
+ r.matrix(FloatVector(X.ravel()),
82
+ byrow=True,
83
+ ncol=X.shape[1],
84
+ nrow=X.shape[0]),
85
+ FactorVector(IntVector(y)),
86
+ )
87
+ self.classes_ = np.unique(y) # /!\ do not remove
88
+ return self
89
+
90
+ def predict_proba(self, X):
91
+ """
92
+ Predict using the model.
93
+ """
94
+ if self.level is None:
95
+ res = self.obj["predict_proba"](
96
+ r.matrix(FloatVector(X.ravel()),
97
+ byrow=True,
98
+ ncol=X.shape[1],
99
+ nrow=X.shape[0])
100
+ )
101
+ return np.asarray(res)
102
+ res = self.obj["predict_proba"](
103
+ r.matrix(FloatVector(X.ravel()),
104
+ byrow=True,
105
+ ncol=X.shape[1],
106
+ nrow=X.shape[0])
107
+ )
108
+ return np.asarray(res[0])
109
+
110
+ def predict(self, X):
111
+ """
112
+ Predict using the model.
113
+ """
114
+ if self.level is None:
115
+ return (
116
+ np.asarray(
117
+ self.obj["predict"](
118
+ r.matrix(FloatVector(X.ravel()),
119
+ byrow=True,
120
+ ncol=X.shape[1],
121
+ nrow=X.shape[0])
122
+ )
123
+ ) - 1
124
+ )
125
+ return (
126
+ np.asarray(
127
+ self.obj["predict"](
128
+ r.matrix(FloatVector(X.ravel()),
129
+ byrow=True,
130
+ ncol=X.shape[1],
131
+ nrow=X.shape[0])
132
+ )
133
+ )
134
+ )
@@ -0,0 +1,92 @@
1
+ import numpy as np
2
+ from rpy2.robjects import r
3
+ from rpy2.robjects.packages import importr
4
+ from rpy2.robjects.vectors import FloatMatrix, FloatVector
5
+ from sklearn.base import RegressorMixin
6
+ from .base import Base
7
+ from .utils import format_value
8
+
9
+ base = importr("base")
10
+ stats = importr("stats")
11
+ utils = importr("utils")
12
+
13
+
14
+ class Regressor(Base, RegressorMixin):
15
+ """
16
+ Regressor.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ method="ranger",
22
+ pi_method="kdesplitconformal",
23
+ level=95,
24
+ B=100,
25
+ nb_hidden = 0,
26
+ nodes_sim = "sobol",
27
+ activ = "relu",
28
+ seed=123,
29
+ ):
30
+ """
31
+ Initialize the model.
32
+ """
33
+ super().__init__(
34
+ name = "Regressor",
35
+ type = "regression",
36
+ method=method,
37
+ pi_method=pi_method,
38
+ level=level,
39
+ B=B,
40
+ nb_hidden=nb_hidden,
41
+ nodes_sim=nodes_sim,
42
+ activ=activ,
43
+ seed=seed,
44
+ )
45
+
46
+ try:
47
+ self.load_learningmachine()
48
+ self.obj = r(
49
+ f"learningmachine::Regressor$new(method = {format_value(self.method)}, pi_method = {format_value(self.pi_method)}, level = {format_value(self.level)}, type_prediction_set = {format_value(self.type_prediction_set)}, B = {format_value(self.B)}, nb_hidden = {format_value(self.nb_hidden)}, nodes_sim = {format_value(self.nodes_sim)}, activ = {format_value(self.activ)}, seed = {format_value(self.seed)})"
50
+ )
51
+ except NotImplementedError as e:
52
+ try:
53
+ r.library("learningmachine")
54
+ self.obj = r(
55
+ f"Regressor$new(method = {format_value(self.method)}, pi_method = {format_value(self.pi_method)}, level = {format_value(self.level)}, type_prediction_set = {format_value(self.type_prediction_set)}, B = {format_value(self.B)}, nb_hidden = {format_value(self.nb_hidden)}, nodes_sim = {format_value(self.nodes_sim)}, activ = {format_value(self.activ)}, seed = {format_value(self.seed)})"
56
+ )
57
+ except NotImplementedError as e:
58
+ try:
59
+ self.obj = r(
60
+ f"""
61
+ library(learningmachine);
62
+ Regressor$new(method = {format_value(self.method)}, pi_method = {format_value(self.pi_method)}, level = {format_value(self.level)}, type_prediction_set = {format_value(self.type_prediction_set)}, B = {format_value(self.B)}, nb_hidden = {format_value(self.nb_hidden)}, nodes_sim = {format_value(self.nodes_sim)}, activ = {format_value(self.activ)}, seed = {format_value(self.seed)})
63
+ """
64
+ )
65
+ except NotImplementedError as e:
66
+ print("R package can't be loaded: ", e)
67
+
68
+ def fit(self, X, y):
69
+ """
70
+ Fit the model according to the given training data.
71
+ """
72
+ self.obj["fit"](
73
+ r.matrix(FloatVector(X.ravel()),
74
+ byrow=True,
75
+ ncol=X.shape[1],
76
+ nrow=X.shape[0]),
77
+ FloatVector(y),
78
+ )
79
+ return self
80
+
81
+ def predict(self, X):
82
+ """
83
+ Predict using the model.
84
+ """
85
+ return np.asarray(
86
+ self.obj["predict"](
87
+ r.matrix(FloatVector(X.ravel()),
88
+ byrow=True,
89
+ ncol=X.shape[1],
90
+ nrow=X.shape[0])
91
+ )
92
+ )
@@ -60,3 +60,15 @@ def check_install_r_pkg():
60
60
  if check_pkg_installed() == True:
61
61
  return 1
62
62
  return 0
63
+
64
+
65
+ # Formatting object as a string
66
+ def format_value(value):
67
+ if value is None:
68
+ return f"NULL"
69
+ if isinstance(value, str):
70
+ return f'"{value}"'
71
+ if isinstance(value, bool):
72
+ return f"{str(value).upper()}"
73
+ if isinstance(value, int) or isinstance(value, float):
74
+ return f"{value}"
@@ -1,13 +1,12 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: learningmachine
3
- Version: 0.2.2
3
+ Version: 1.1.0
4
4
  Summary: Machine Learning with uncertainty quantification and interpretability
5
- Home-page: https://github.com/Techtonique/learningmachine
5
+ Home-page: https://github.com/Techtonique/learningmachine_python
6
6
  Author: T. Moudiki
7
7
  Author-email: thierry.moudiki@gmail.com
8
8
  License: BSD Clause Clear license
9
9
  Keywords: learningmachine
10
- Platform: UNKNOWN
11
10
  Classifier: Development Status :: 2 - Pre-Alpha
12
11
  Classifier: Intended Audience :: Developers
13
12
  Classifier: License :: OSI Approved :: BSD License
@@ -18,6 +17,10 @@ Classifier: Programming Language :: Python :: 3.7
18
17
  Classifier: Programming Language :: Python :: 3.8
19
18
  Requires-Python: >=3.6
20
19
  License-File: LICENSE
20
+ Requires-Dist: numpy
21
+ Requires-Dist: pandas
22
+ Requires-Dist: rpy2>=3.4.5
23
+ Requires-Dist: scikit-learn
24
+ Requires-Dist: scipy
21
25
 
22
26
  Machine Learning with uncertainty quantification and interpretability.
23
-
@@ -16,7 +16,8 @@ docs/readme.rst
16
16
  docs/usage.rst
17
17
  learningmachine/__init__.py
18
18
  learningmachine/base.py
19
- learningmachine/basemodels.py
19
+ learningmachine/classifier.py
20
+ learningmachine/regression.py
20
21
  learningmachine/utils.py
21
22
  learningmachine.egg-info/PKG-INFO
22
23
  learningmachine.egg-info/SOURCES.txt
@@ -0,0 +1,220 @@
1
+ #!/usr/bin/env python
2
+
3
+ import platform
4
+ import subprocess
5
+ from os import path
6
+ from setuptools import setup, find_packages
7
+
8
+ # 0 - utility functions -----------------------------------------------
9
+
10
+ def check_r_installed():
11
+ current_platform = platform.system()
12
+
13
+ if current_platform == "Windows":
14
+ # Check if R is installed on Windows by checking the registry
15
+ try:
16
+ subprocess.run(
17
+ ["reg", "query", "HKLM\\Software\\R-core\\R"], check=True
18
+ )
19
+ print("R is already installed on Windows.")
20
+ return True
21
+ except subprocess.CalledProcessError as e:
22
+ install_r(prompt=True)
23
+ return True
24
+
25
+ elif current_platform in ("Darwin", "Linux"):
26
+ # Check if R is installed on Linux by checking if the 'R' executable is available
27
+
28
+ try:
29
+ # Try to find the 'R' executable using 'which' (if available)
30
+ subprocess.check_call(['which', 'R'])
31
+ print(f"R is already installed on {current_platform}.")
32
+ return True
33
+ except subprocess.CalledProcessError:
34
+ # 'which' might not be available, or R is not installed
35
+ print('R may not be installed.')
36
+ install_r(prompt=True)
37
+ return True
38
+
39
+ else:
40
+
41
+ print("Unsupported platform (check manually: https://cloud.r-project.org/)")
42
+ return False
43
+
44
+ def install_r(prompt=False):
45
+
46
+ current_platform = platform.system()
47
+
48
+ if prompt == True:
49
+ print("Installing R...")
50
+ # choice = input("Would you like to install R? (yes/no): ").strip().lower()
51
+ # if choice == 'yes':
52
+ # print("Installing R...")
53
+ # elif choice == 'no':
54
+ # print("No problem. R will not be installed.")
55
+ # return
56
+ # else:
57
+ # print("Invalid input. Please enter 'yes' or 'no'.")
58
+ # return
59
+
60
+ if current_platform == "Windows":
61
+ # Install R on Windows using PowerShell
62
+ install_command = "Start-Process powershell -Verb runAs -ArgumentList '-Command \"& {Invoke-WebRequest https://cran.r-project.org/bin/windows/base/R-4.1.2-win.exe -OutFile R.exe}; Start-Process R.exe -ArgumentList '/SILENT' -Wait}'"
63
+ subprocess.run(install_command, shell=True)
64
+
65
+ elif current_platform == "Linux":
66
+ # Install R on Linux using the appropriate package manager (e.g., apt-get)
67
+ install_command = (
68
+ "sudo apt update -qq && sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9"
69
+ + "&& sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/'"
70
+ + "&& sudo apt update"
71
+ + "&& sudo apt install r-base"
72
+ )
73
+ try:
74
+ subprocess.run(install_command, shell=True)
75
+ except NotImplementedError as e:
76
+ print("Error installing R on this Linux distribution. Please check manually: https://cloud.r-project.org/")
77
+
78
+ elif current_platform == "Darwin": # macOS
79
+ # Install R on macOS using Homebrew
80
+ install_command = "brew install r"
81
+ try:
82
+ subprocess.run(install_command, shell=True)
83
+ except NotImplementedError as e:
84
+ print("Error installing R on macOS. Please check manually: https://cloud.r-project.org/")
85
+
86
+ else:
87
+ print("Unsupported platform. Unable to install R.")
88
+
89
+ def load_learningmachine():
90
+ # Install R packages
91
+ commands1_lm = 'base::system.file(package = "learningmachine")' # check "learningmachine" is installed
92
+ commands2_lm = 'base::system.file("learningmachine_r", package = "learningmachine")' # check "learningmachine" is installed locally
93
+ exec_commands1_lm = subprocess.run(
94
+ ["Rscript", "-e", commands1_lm], capture_output=True, text=True
95
+ )
96
+ exec_commands2_lm = subprocess.run(
97
+ ["Rscript", "-e", commands2_lm], capture_output=True, text=True
98
+ )
99
+ if (
100
+ len(exec_commands1_lm.stdout) == 7
101
+ and len(exec_commands2_lm.stdout) == 7
102
+ ): # kind of convoluted, but works
103
+ print("Installing R packages along with 'learningmachine'...")
104
+ commands1 = [
105
+ 'try(utils::install.packages(c("R6", "Rcpp", "skimr"), repos="https://cloud.r-project.org", dependencies = TRUE), silent=TRUE)',
106
+ 'try(utils::install.packages("learningmachine", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=TRUE)',
107
+ ]
108
+ commands2 = [
109
+ 'try(utils::install.packages(c("R6", "Rcpp", "skimr"), lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=TRUE)',
110
+ 'try(utils::install.packages("learningmachine", lib="./learningmachine_r", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=TRUE)',
111
+ ]
112
+ commands3 = [
113
+ 'try(utils::install.packages(c("R6", "Rcpp", "remotes", "skimr"), repos="https://cloud.r-project.org", dependencies = TRUE), silent=TRUE)',
114
+ 'try(remotes::install_github("Techtonique/learningmachine"), silent=TRUE)',
115
+ ]
116
+ commands4 = [
117
+ 'try(utils::install.packages(c("R6", "Rcpp", "remotes", "skimr"), lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=TRUE)',
118
+ 'try(remotes::install_github("Techtonique/learningmachine", lib="./learningmachine_r", dependencies = TRUE), silent=TRUE)',
119
+ ]
120
+
121
+ try:
122
+ for cmd in commands3:
123
+ try:
124
+ subprocess.run(["Rscript", "-e", cmd])
125
+ except:
126
+ pass
127
+ except NotImplementedError as e: # can't install packages globally
128
+ try:
129
+ subprocess.run(["mkdir", "learningmachine_r"])
130
+ for cmd in commands4:
131
+ try:
132
+ subprocess.run(["Rscript", "-e", cmd])
133
+ except:
134
+ pass
135
+ except NotImplementedError as e:
136
+ try:
137
+ for cmd in commands1:
138
+ try:
139
+ subprocess.run(["Rscript", "-e", cmd])
140
+ except:
141
+ pass
142
+ except NotImplementedError as e:
143
+ subprocess.run(["mkdir", "learningmachine_r"])
144
+ for cmd in commands2:
145
+ try:
146
+ subprocess.run(["Rscript", "-e", cmd])
147
+ except:
148
+ pass
149
+
150
+ # try:
151
+ # base.library(StrVector(["learningmachine"]))
152
+ # except (
153
+ # NotImplementedError
154
+ # ) as e1: # can't load the package from the global environment
155
+ # try:
156
+ # base.library(
157
+ # StrVector(["learningmachine"]), lib_loc="learningmachine_r"
158
+ # )
159
+ # except NotImplementedError as e2: # well, we tried
160
+ # try:
161
+ # r("try(library('learningmachine'), silence=TRUE)")
162
+ # except (
163
+ # NotImplementedError
164
+ # ) as e3: # well, we tried everything at this point
165
+ # r(
166
+ # "try(library('learningmachine', lib.loc='learningmachine_r'), silence=TRUE)"
167
+ # )
168
+
169
+ # 1 - import Python packages -----------------------------------------------
170
+
171
+ subprocess.run(["pip", "install", "rpy2"])
172
+ try:
173
+ subprocess.run(["pip", "install", "setuptools"])
174
+ except ModuleNotFoundError as e:
175
+ print("Error installing setuptools. Please install setuptools manually.")
176
+
177
+ from rpy2.robjects.packages import importr
178
+ from rpy2.robjects.vectors import StrVector
179
+ from rpy2.robjects import r
180
+
181
+ base = importr("base")
182
+
183
+ if not check_r_installed():
184
+ install_r()
185
+ else:
186
+ print("R is already installed.")
187
+
188
+ load_learningmachine()
189
+
190
+ # 4 - Package setup -----------------------------------------------
191
+
192
+ """The setup script."""
193
+
194
+ setup(
195
+ author="T. Moudiki",
196
+ author_email="thierry.moudiki@gmail.com",
197
+ python_requires=">=3.6",
198
+ classifiers=[
199
+ "Development Status :: 2 - Pre-Alpha",
200
+ "Intended Audience :: Developers",
201
+ "License :: OSI Approved :: BSD License",
202
+ "Natural Language :: English",
203
+ "Programming Language :: Python :: 3",
204
+ "Programming Language :: Python :: 3.6",
205
+ "Programming Language :: Python :: 3.7",
206
+ "Programming Language :: Python :: 3.8",
207
+ ],
208
+ description="Machine Learning with uncertainty quantification and interpretability",
209
+ install_requires=['numpy', 'pandas', 'rpy2>=3.4.5', 'scikit-learn', 'scipy'],
210
+ license="BSD Clause Clear license",
211
+ long_description="Machine Learning with uncertainty quantification and interpretability.",
212
+ include_package_data=True,
213
+ keywords="learningmachine",
214
+ name="learningmachine",
215
+ packages=find_packages(include=["learningmachine", "learningmachine.*"]),
216
+ test_suite="tests",
217
+ url="https://github.com/Techtonique/learningmachine_python",
218
+ version="1.1.0",
219
+ zip_safe=False,
220
+ )
@@ -1,11 +0,0 @@
1
- """Top-level package for learningmachine."""
2
-
3
- __author__ = """T. Moudiki"""
4
- __email__ = "thierry.moudiki@gmail.com"
5
- __version__ = "0.2.0"
6
-
7
- from .base import Base
8
- from .basemodels import BaseClassifier, BaseRegressor
9
- from .utils import check_install_r_pkg
10
-
11
- __all__ = ["check_install_r_pkg", "Base", "BaseClassifier", "BaseRegressor"]
@@ -1,18 +0,0 @@
1
- from rpy2.robjects import r
2
- from rpy2.robjects.packages import importr
3
- from .utils import check_install_r_pkg
4
-
5
- base = importr("base")
6
- stats = importr("stats")
7
-
8
-
9
- class Base(object):
10
- """
11
- Base class.
12
- """
13
-
14
- def __init__(self):
15
- """
16
- Initialize the model.
17
- """
18
- self.obj = None
@@ -1,112 +0,0 @@
1
- from subprocess import run
2
- from rpy2.robjects import r
3
- from rpy2.robjects.packages import importr
4
- from rpy2.robjects.vectors import (
5
- FloatMatrix,
6
- FloatVector,
7
- IntVector,
8
- StrVector,
9
- )
10
-
11
- from sklearn.base import BaseEstimator, RegressorMixin, ClassifierMixin
12
- from .base import Base
13
-
14
- base = importr("base")
15
- stats = importr("stats")
16
- utils = importr("utils")
17
-
18
-
19
- class BaseRegressor(Base, BaseEstimator, RegressorMixin):
20
- """
21
- Base Regressor.
22
- """
23
-
24
- def __init__(self):
25
- """
26
- Initialize the model.
27
- """
28
-
29
- super(Base, self).__init__()
30
-
31
- try:
32
- self.obj = r("learningmachine::BaseRegressor$new()")
33
- except NotImplementedError as e: # doesn't work yet
34
- self.obj = run(
35
- ["Rscript", "-e", "learningmachine::BaseRegressor$new()"],
36
- capture_output=True,
37
- )
38
-
39
- def fit(self, X, y):
40
- """
41
- Fit the model according to the given training data.
42
- """
43
- self.obj["fit"](
44
- r.matrix(
45
- FloatVector(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
46
- ),
47
- FloatVector(y),
48
- )
49
- return self
50
-
51
- def predict(self, X):
52
- """
53
- Predict using the model.
54
- """
55
- return self.obj["predict"](
56
- r.matrix(
57
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
58
- )
59
- )
60
-
61
-
62
- class BaseClassifier(Base, BaseEstimator, ClassifierMixin):
63
- """
64
- Base Classifier.
65
- """
66
-
67
- def __init__(self):
68
- """
69
- Initialize the model.
70
- """
71
-
72
- super(Base, self).__init__()
73
-
74
- try:
75
- self.obj = r("learningmachine::BaseClassifier$new()")
76
- except NotImplementedError as e: # doesn't work yet
77
- self.obj = run(
78
- ["Rscript", "-e", "learningmachine::BaseClassifier$new()"],
79
- capture_output=True,
80
- )
81
-
82
- def fit(self, X, y):
83
- """
84
- Fit the model according to the given training data.
85
- """
86
- self.obj["fit"](
87
- r.matrix(
88
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
89
- ),
90
- base.as_factor(IntVector(y)),
91
- )
92
- return self
93
-
94
- def predict(self, X):
95
- """
96
- Predict classes using the model.
97
- """
98
- return self.obj["predict"](
99
- r.matrix(
100
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
101
- )
102
- )
103
-
104
- def predict_proba(self, X):
105
- """
106
- Predict probabilities using the model.
107
- """
108
- return self.obj["predict_proba"](
109
- r.matrix(
110
- FloatMatrix(X), byrow=True, nrow=X.shape[0], ncol=X.shape[1]
111
- )
112
- )
@@ -1,175 +0,0 @@
1
- #!/usr/bin/env python
2
-
3
- # 1 - import Python packages -----------------------------------------------
4
-
5
- import platform
6
- import subprocess
7
- from os import path
8
- from rpy2.robjects.packages import importr
9
- from setuptools import setup, find_packages
10
- from rpy2.robjects.vectors import StrVector
11
- from rpy2.robjects import r
12
-
13
- # 2 - utility functions -----------------------------------------------
14
-
15
- def check_r_installed():
16
- current_platform = platform.system()
17
-
18
- if current_platform == "Windows":
19
- # Check if R is installed on Windows by checking the registry
20
- try:
21
- subprocess.run(
22
- ["reg", "query", "HKLM\\Software\\R-core\\R"], check=True
23
- )
24
- print("R is already installed on Windows.")
25
- return True
26
- except subprocess.CalledProcessError:
27
- print("R is not installed on Windows.")
28
- return False
29
-
30
- elif current_platform == "Linux":
31
- # Check if R is installed on Linux by checking if the 'R' executable is available
32
- try:
33
- subprocess.run(["which", "R"], check=True)
34
- print("R is already installed on Linux.")
35
- return True
36
- except subprocess.CalledProcessError:
37
- print("R is not installed on Linux.")
38
- return False
39
-
40
- elif current_platform == "Darwin": # macOS
41
- # Check if R is installed on macOS by checking if the 'R' executable is available
42
- try:
43
- subprocess.run(["which", "R"], check=True)
44
- print("R is already installed on macOS.")
45
- return True
46
- except subprocess.CalledProcessError:
47
- print("R is not installed on macOS.")
48
- return False
49
-
50
- else:
51
- print("Unsupported platform. Unable to check for R installation.")
52
- return False
53
-
54
-
55
- def install_r():
56
- current_platform = platform.system()
57
-
58
- if current_platform == "Windows":
59
- # Install R on Windows using PowerShell
60
- install_command = "Start-Process powershell -Verb runAs -ArgumentList '-Command \"& {Invoke-WebRequest https://cran.r-project.org/bin/windows/base/R-4.1.2-win.exe -OutFile R.exe}; Start-Process R.exe -ArgumentList '/SILENT' -Wait}'"
61
- subprocess.run(install_command, shell=True)
62
-
63
- elif current_platform == "Linux":
64
- # Install R on Linux using the appropriate package manager (e.g., apt-get)
65
- install_command = (
66
- "sudo apt update -qq && sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9"
67
- + "&& sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/'"
68
- + "&& sudo apt update"
69
- + "&& sudo apt install r-base"
70
- )
71
- subprocess.run(install_command, shell=True)
72
-
73
- elif current_platform == "Darwin": # macOS
74
- # Install R on macOS using Homebrew
75
- install_command = "brew install r"
76
- subprocess.run(install_command, shell=True)
77
-
78
- else:
79
- print("Unsupported platform. Unable to install R.")
80
-
81
- # 3 - Install packages -----------------------------------------------
82
-
83
- # Check if R is installed; if not, install it
84
- if not check_r_installed():
85
- print("Installing R...")
86
- install_r()
87
- else:
88
- print("No installation needed.")
89
-
90
- # Install R packages
91
- commands1_lm = 'base::system.file(package = "learningmachine")' # check is installed
92
- commands2_lm = 'base::system.file("learningmachine_r", package = "learningmachine")' # check is installed locally
93
- exec_commands1_lm = subprocess.run(['Rscript', '-e', commands1_lm], capture_output=True, text=True)
94
- exec_commands2_lm = subprocess.run(['Rscript', '-e', commands2_lm], capture_output=True, text=True)
95
- if (len(exec_commands1_lm.stdout) == 7 and len(exec_commands2_lm.stdout) == 7): # kind of convoluted, but works
96
- print("Installing R packages...")
97
- commands1 = ['try(utils::install.packages("R6", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
98
- 'try(utils::install.packages("Rcpp", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
99
- 'try(utils::install.packages("skimr", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
100
- 'try(utils::install.packages("learningmachine", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=FALSE)']
101
- commands2 = ['try(utils::install.packages("R6", lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
102
- 'try(utils::install.packages("Rcpp", lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
103
- 'try(utils::install.packages("skimr", lib="./learningmachine_r", repos="https://cloud.r-project.org", dependencies = TRUE), silent=FALSE)',
104
- 'try(utils::install.packages("learningmachine", lib="./learningmachine_r", repos="https://techtonique.r-universe.dev", dependencies = TRUE), silent=FALSE)']
105
- try:
106
- for cmd in commands1:
107
- subprocess.run(['Rscript', '-e', cmd])
108
- except Exception as e:
109
- subprocess.run(['mkdir', 'learningmachine_r'])
110
- for cmd in commands2:
111
- subprocess.run(['Rscript', '-e', cmd])
112
-
113
- base = importr("base")
114
-
115
- try:
116
- base.library(StrVector(["learningmachine"]))
117
- except Exception as e1:
118
- try:
119
- base.library(
120
- StrVector(["learningmachine"]), lib_loc="learningmachine_r"
121
- )
122
- except Exception as e2:
123
- try:
124
- r("try(library('learningmachine'), silence=TRUE)")
125
- except NotImplementedError as e3:
126
- r(
127
- "try(library('learningmachine', lib.loc='learningmachine_r'), silence=TRUE)"
128
- )
129
-
130
-
131
- """The setup script."""
132
- here = path.abspath(path.dirname(__file__))
133
-
134
- # get the dependencies and installs
135
- with open(
136
- path.join(here, "requirements.txt"), encoding="utf-8"
137
- ) as f:
138
- all_reqs = f.read().split("\n")
139
-
140
- install_requires = [
141
- x.strip() for x in all_reqs if "git+" not in x
142
- ]
143
- dependency_links = [
144
- x.strip().replace("git+", "")
145
- for x in all_reqs
146
- if x.startswith("git+")
147
- ]
148
-
149
- setup(
150
- author="T. Moudiki",
151
- author_email='thierry.moudiki@gmail.com',
152
- python_requires='>=3.6',
153
- classifiers=[
154
- 'Development Status :: 2 - Pre-Alpha',
155
- 'Intended Audience :: Developers',
156
- 'License :: OSI Approved :: BSD License',
157
- 'Natural Language :: English',
158
- 'Programming Language :: Python :: 3',
159
- 'Programming Language :: Python :: 3.6',
160
- 'Programming Language :: Python :: 3.7',
161
- 'Programming Language :: Python :: 3.8',
162
- ],
163
- description="Machine Learning with uncertainty quantification and interpretability",
164
- install_requires=install_requires,
165
- license="BSD Clause Clear license",
166
- long_description="Machine Learning with uncertainty quantification and interpretability.",
167
- include_package_data=True,
168
- keywords='learningmachine',
169
- name='learningmachine',
170
- packages=find_packages(include=['learningmachine', 'learningmachine.*']),
171
- test_suite='tests',
172
- url='https://github.com/Techtonique/learningmachine',
173
- version='0.2.2',
174
- zip_safe=False,
175
- )
File without changes