Coverage for biobb_ml/regression/random_forest_regressor.py: 85%
143 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 14:57 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-10-03 14:57 +0000
1#!/usr/bin/env python3
3"""Module containing the RandomForestRegressor class and the command line interface."""
4import argparse
5import joblib
6import numpy as np
7import pandas as pd
8from biobb_common.generic.biobb_object import BiobbObject
9from sklearn.preprocessing import StandardScaler
10from sklearn.model_selection import train_test_split
11from sklearn.metrics import mean_squared_error, r2_score
12from sklearn import ensemble
13from biobb_common.configuration import settings
14from biobb_common.tools import file_utils as fu
15from biobb_common.tools.file_utils import launchlogger
16from biobb_ml.regression.common import check_input_path, check_output_path, getHeader, getIndependentVars, getIndependentVarsList, getTarget, getTargetValue, getWeight, plotResults
19class RandomForestRegressor(BiobbObject):
20 """
21 | biobb_ml RandomForestRegressor
22 | Wrapper of the scikit-learn RandomForestRegressor method.
23 | Trains and tests a given dataset and saves the model and scaler. Visit the `RandomForestRegressor documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html>`_.
25 Args:
26 input_dataset_path (str): Path to the input dataset. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/regression/dataset_random_forest_regressor.csv>`_. Accepted formats: csv (edam:format_3752).
27 output_model_path (str): Path to the output model file. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/regression/ref_output_model_random_forest_regressor.pkl>`_. Accepted formats: pkl (edam:format_3653).
28 output_test_table_path (str) (Optional): Path to the test table file. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/regression/ref_output_test_random_forest_regressor.csv>`_. Accepted formats: csv (edam:format_3752).
29 output_plot_path (str) (Optional): Residual plot checks the error between actual values and predicted values. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/regression/ref_output_plot_random_forest_regressor.png>`_. Accepted formats: png (edam:format_3603).
30 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
31 * **independent_vars** (*dict*) - ({}) Independent variables you want to train from your dataset. You can specify either a list of columns names from your input dataset, a list of columns indexes or a range of columns indexes. Formats: { "columns": ["column1", "column2"] } or { "indexes": [0, 2, 3, 10, 11, 17] } or { "range": [[0, 20], [50, 102]] }. In case of mulitple formats, the first one will be picked.
32 * **target** (*dict*) - ({}) Dependent variable you want to predict from your dataset. You can specify either a column name or a column index. Formats: { "column": "column3" } or { "index": 21 }. In case of mulitple formats, the first one will be picked.
33 * **weight** (*dict*) - ({}) Weight variable from your dataset. You can specify either a column name or a column index. Formats: { "column": "column3" } or { "index": 21 }. In case of mulitple formats, the first one will be picked.
34 * **n_estimators** (*int*) - (10) The number of trees in the forest.
35 * **max_depth** (*int*) - (None) The maximum depth of the tree.
36 * **random_state_method** (*int*) - (5) [1~1000|1] Controls the randomness of the estimator.
37 * **random_state_train_test** (*int*) - (5) [1~1000|1] Controls the shuffling applied to the data before applying the split.
38 * **test_size** (*float*) - (0.2) Represents the proportion of the dataset to include in the test split. It should be between 0.0 and 1.0.
39 * **scale** (*bool*) - (False) Whether or not to scale the input dataset.
40 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
41 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
42 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
44 Examples:
45 This is a use example of how to use the building block from Python::
47 from biobb_ml.regression.random_forest_regressor import random_forest_regressor
48 prop = {
49 'independent_vars': {
50 'columns': [ 'column1', 'column2', 'column3' ]
51 },
52 'target': {
53 'column': 'target'
54 },
55 'n_estimators': 10,
56 'max_depth': 5,
57 'test_size': 0.2
58 }
59 random_forest_regressor(input_dataset_path='/path/to/myDataset.csv',
60 output_model_path='/path/to/newModel.pkl',
61 output_test_table_path='/path/to/newTable.csv',
62 output_plot_path='/path/to/newPlot.png',
63 properties=prop)
65 Info:
66 * wrapped_software:
67 * name: scikit-learn RandomForestRegressor
68 * version: >0.24.2
69 * license: BSD 3-Clause
70 * ontology:
71 * name: EDAM
72 * schema: http://edamontology.org/EDAM.owl
74 """
76 def __init__(self, input_dataset_path, output_model_path,
77 output_test_table_path=None, output_plot_path=None, properties=None, **kwargs) -> None:
78 properties = properties or {}
80 # Call parent class constructor
81 super().__init__(properties)
82 self.locals_var_dict = locals().copy()
84 # Input/Output files
85 self.io_dict = {
86 "in": {"input_dataset_path": input_dataset_path},
87 "out": {"output_model_path": output_model_path, "output_test_table_path": output_test_table_path, "output_plot_path": output_plot_path}
88 }
90 # Properties specific for BB
91 self.independent_vars = properties.get('independent_vars', {})
92 self.target = properties.get('target', {})
93 self.weight = properties.get('weight', {})
94 self.n_estimators = properties.get('n_estimators', 10)
95 self.max_depth = properties.get('max_depth', None)
96 self.random_state_method = properties.get('random_state_method', 5)
97 self.random_state_train_test = properties.get('random_state_train_test', 5)
98 self.test_size = properties.get('test_size', 0.2)
99 self.scale = properties.get('scale', False)
100 self.properties = properties
102 # Check the properties
103 self.check_properties(properties)
104 self.check_arguments()
106 def check_data_params(self, out_log, err_log):
107 """ Checks all the input/output paths and parameters """
108 self.io_dict["in"]["input_dataset_path"] = check_input_path(self.io_dict["in"]["input_dataset_path"], "input_dataset_path", out_log, self.__class__.__name__)
109 self.io_dict["out"]["output_model_path"] = check_output_path(self.io_dict["out"]["output_model_path"], "output_model_path", False, out_log, self.__class__.__name__)
110 if self.io_dict["out"]["output_test_table_path"]:
111 self.io_dict["out"]["output_test_table_path"] = check_output_path(self.io_dict["out"]["output_test_table_path"], "output_test_table_path", True, out_log, self.__class__.__name__)
112 if self.io_dict["out"]["output_plot_path"]:
113 self.io_dict["out"]["output_plot_path"] = check_output_path(self.io_dict["out"]["output_plot_path"], "output_plot_path", True, out_log, self.__class__.__name__)
115 @launchlogger
116 def launch(self) -> int:
117 """Execute the :class:`RandomForestRegressor <regression.random_forest_regressor.RandomForestRegressor>` regression.random_forest_regressor.RandomForestRegressor object."""
119 # check input/output paths and parameters
120 self.check_data_params(self.out_log, self.err_log)
122 # Setup Biobb
123 if self.check_restart():
124 return 0
125 self.stage_files()
127 # load dataset
128 fu.log('Getting dataset from %s' % self.io_dict["in"]["input_dataset_path"], self.out_log, self.global_log)
129 if 'columns' in self.independent_vars:
130 labels = getHeader(self.io_dict["in"]["input_dataset_path"])
131 skiprows = 1
132 else:
133 labels = None
134 skiprows = None
135 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels)
137 # declare inputs, targets and weights
138 # the inputs are all the independent variables
139 X = getIndependentVars(self.independent_vars, data, self.out_log, self.__class__.__name__)
140 fu.log('Independent variables: [%s]' % (getIndependentVarsList(self.independent_vars)), self.out_log, self.global_log)
141 # target
142 y = getTarget(self.target, data, self.out_log, self.__class__.__name__)
143 fu.log('Target: %s' % (getTargetValue(self.target)), self.out_log, self.global_log)
144 # weights
145 if self.weight:
146 w = getWeight(self.weight, data, self.out_log, self.__class__.__name__)
147 fu.log('Weight column provided', self.out_log, self.global_log)
149 # train / test split
150 fu.log('Creating train and test sets', self.out_log, self.global_log)
151 arrays_sets = (X, y)
152 # if user provide weights
153 if self.weight:
154 arrays_sets = arrays_sets + (w,)
155 X_train, X_test, y_train, y_test, w_train, w_test = train_test_split(*arrays_sets, test_size=self.test_size, random_state=self.random_state_train_test)
156 else:
157 X_train, X_test, y_train, y_test = train_test_split(*arrays_sets, test_size=self.test_size, random_state=self.random_state_train_test)
159 # scale dataset
160 if self.scale:
161 fu.log('Scaling dataset', self.out_log, self.global_log)
162 scaler = StandardScaler()
163 X_train = scaler.fit_transform(X_train)
165 # regression
166 fu.log('Training dataset applying random forest regressor', self.out_log, self.global_log)
167 model = ensemble.RandomForestRegressor(max_depth=self.max_depth, n_estimators=self.n_estimators, random_state=self.random_state_method)
168 arrays_fit = (X_train, y_train)
169 # if user provide weights
170 if self.weight:
171 arrays_fit = arrays_fit + (w_train,)
173 model.fit(*arrays_fit)
175 # scores and coefficients train
176 y_hat_train = model.predict(X_train)
177 rmse = (np.sqrt(mean_squared_error(y_train, y_hat_train)))
178 rss = ((y_train - y_hat_train) ** 2).sum()
179 score_train_inputs = (y_train, y_hat_train)
180 if self.weight:
181 score_train_inputs = score_train_inputs + (w_train,)
182 score = r2_score(*score_train_inputs)
184 # r-squared
185 r2_table = pd.DataFrame()
186 r2_table["feature"] = ['R2', 'RMSE', 'RSS']
187 r2_table['coefficient'] = [score, rmse, rss]
189 fu.log('Calculating scores and coefficients for TRAINING dataset\n\nSCORES\n\n%s\n' % r2_table, self.out_log, self.global_log)
191 # testing
192 # predict data from x_test
193 if self.scale:
194 X_test = scaler.transform(X_test)
195 y_hat_test = model.predict(X_test)
196 test_table = pd.DataFrame(y_hat_test, columns=['prediction'])
197 # reset y_test (problem with old indexes column)
198 y_test = y_test.reset_index(drop=True)
199 # add real values to predicted ones in test_table table
200 test_table['target'] = y_test
201 # calculate difference between target and prediction (absolute and %)
202 test_table['residual'] = test_table['target'] - test_table['prediction']
203 test_table['difference %'] = np.absolute(test_table['residual']/test_table['target']*100)
204 # sort by difference in %
205 test_table = test_table.sort_values(by=['difference %'])
206 test_table = test_table.reset_index(drop=True)
207 fu.log('Testing\n\nTEST DATA\n\n%s\n' % test_table, self.out_log, self.global_log)
209 # scores and coefficients test
210 score_test_inputs = (y_test, y_hat_test)
211 if self.weight:
212 score_test_inputs = score_test_inputs + (w_test,)
213 r2_test = r2_score(*score_test_inputs)
214 rmse_test = np.sqrt(mean_squared_error(y_test, y_hat_test))
215 rss_test = ((y_test - y_hat_test) ** 2).sum()
217 # r-squared
218 r2_table_test = pd.DataFrame()
219 r2_table_test["feature"] = ['R2', 'RMSE', 'RSS']
220 r2_table_test['coefficient'] = [r2_test, rmse_test, rss_test]
222 fu.log('Calculating scores and coefficients for TESTING dataset\n\nSCORES\n\n%s\n' % r2_table_test, self.out_log, self.global_log)
224 if (self.io_dict["out"]["output_test_table_path"]):
225 fu.log('Saving testing data to %s' % self.io_dict["out"]["output_test_table_path"], self.out_log, self.global_log)
226 test_table.to_csv(self.io_dict["out"]["output_test_table_path"], index=False, header=True)
228 # create test plot
229 if (self.io_dict["out"]["output_plot_path"]):
230 fu.log('Saving residual plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log)
231 y_hat_test = y_hat_test.flatten()
232 y_hat_train = y_hat_train.flatten()
233 plot = plotResults(y_train, y_hat_train, y_test, y_hat_test)
234 plot.savefig(self.io_dict["out"]["output_plot_path"], dpi=150)
236 # save model, scaler and parameters
237 variables = {
238 'target': self.target,
239 'independent_vars': self.independent_vars,
240 'scale': self.scale
241 }
242 fu.log('Saving model to %s' % self.io_dict["out"]["output_model_path"], self.out_log, self.global_log)
243 with open(self.io_dict["out"]["output_model_path"], "wb") as f:
244 joblib.dump(model, f)
245 if self.scale:
246 joblib.dump(scaler, f)
247 joblib.dump(variables, f)
249 # Copy files to host
250 self.copy_to_host()
252 self.tmp_files.extend([
253 self.stage_io_dict.get("unique_dir")
254 ])
255 self.remove_tmp_files()
257 self.check_arguments(output_files_created=True, raise_exception=False)
259 return 0
262def random_forest_regressor(input_dataset_path: str, output_model_path: str, output_test_table_path: str = None, output_plot_path: str = None, properties: dict = None, **kwargs) -> int:
263 """Execute the :class:`RandomForestRegressor <regression.random_forest_regressor.RandomForestRegressor>` class and
264 execute the :meth:`launch() <regression.random_forest_regressor.RandomForestRegressor.launch>` method."""
266 return RandomForestRegressor(input_dataset_path=input_dataset_path,
267 output_model_path=output_model_path,
268 output_test_table_path=output_test_table_path,
269 output_plot_path=output_plot_path,
270 properties=properties, **kwargs).launch()
273def main():
274 """Command line execution of this building block. Please check the command line documentation."""
275 parser = argparse.ArgumentParser(description="Wrapper of the scikit-learn RandomForestRegressor method.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
276 parser.add_argument('--config', required=False, help='Configuration file')
278 # Specific args of each building block
279 required_args = parser.add_argument_group('required arguments')
280 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.')
281 required_args.add_argument('--output_model_path', required=True, help='Path to the output model file. Accepted formats: pkl.')
282 parser.add_argument('--output_test_table_path', required=False, help='Path to the test table file. Accepted formats: csv.')
283 parser.add_argument('--output_plot_path', required=False, help='Residual plot checks the error between actual values and predicted values. Accepted formats: png.')
285 args = parser.parse_args()
286 args.config = args.config or "{}"
287 properties = settings.ConfReader(config=args.config).get_prop_dic()
289 # Specific call of each building block
290 random_forest_regressor(input_dataset_path=args.input_dataset_path,
291 output_model_path=args.output_model_path,
292 output_test_table_path=args.output_test_table_path,
293 output_plot_path=args.output_plot_path,
294 properties=properties)
297if __name__ == '__main__':
298 main()