Coverage for biobb_ml/regression/polynomial_regression.py: 87%
145 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 PolynomialRegression class and the command line interface."""
4import argparse
5import numpy as np
6import pandas as pd
7import joblib
8from biobb_common.generic.biobb_object import BiobbObject
9from sklearn.preprocessing import StandardScaler, PolynomialFeatures
10from sklearn.model_selection import train_test_split
11from sklearn.feature_selection import f_regression
12from sklearn.metrics import mean_squared_error, r2_score
13from sklearn import linear_model
14from biobb_common.configuration import settings
15from biobb_common.tools import file_utils as fu
16from biobb_common.tools.file_utils import launchlogger
17from biobb_ml.regression.common import check_input_path, check_output_path, getHeader, getIndependentVars, getIndependentVarsList, getTarget, getTargetValue, getWeight, adjusted_r2, plotResults
20class PolynomialRegression(BiobbObject):
21 """
22 | biobb_ml PolynomialRegression
23 | Wrapper of the scikit-learn LinearRegression method with PolynomialFeatures.
24 | Trains and tests a given dataset and saves the model and scaler. Visit the `LinearRegression documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html>`_ in the sklearn official website for further information.
26 Args:
27 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_polynomial_regression.csv>`_. Accepted formats: csv (edam:format_3752).
28 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_polynomial_regression.pkl>`_. Accepted formats: pkl (edam:format_3653).
29 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_polynomial_regression.csv>`_. Accepted formats: csv (edam:format_3752).
30 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_polynomial_regression.png>`_. Accepted formats: png (edam:format_3603).
31 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
32 * **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.
33 * **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.
34 * **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.
35 * **random_state_train_test** (*int*) - (5) [1~1000|1] Controls the shuffling applied to the data before applying the split.
36 * **degree** (*int*) - (2) [1~100|1] Polynomial degree.
37 * **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.
38 * **scale** (*bool*) - (False) Whether or not to scale the input dataset.
39 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
40 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
41 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
43 Examples:
44 This is a use example of how to use the building block from Python::
46 from biobb_ml.regression.polynomial_regression import polynomial_regression
47 prop = {
48 'independent_vars': {
49 'columns': [ 'column1', 'column2', 'column3' ]
50 },
51 'target': {
52 'column': 'target'
53 },
54 'degree': 2,
55 'test_size': 0.2
56 }
57 polynomial_regression(input_dataset_path='/path/to/myDataset.csv',
58 output_model_path='/path/to/newModel.pkl',
59 output_test_table_path='/path/to/newTable.csv',
60 output_plot_path='/path/to/newPlot.png',
61 properties=prop)
63 Info:
64 * wrapped_software:
65 * name: scikit-learn LinearRegression
66 * version: >=0.24.2
67 * license: BSD 3-Clause
68 * ontology:
69 * name: EDAM
70 * schema: http://edamontology.org/EDAM.owl
72 """
74 def __init__(self, input_dataset_path, output_model_path,
75 output_test_table_path=None, output_plot_path=None, properties=None, **kwargs) -> None:
76 properties = properties or {}
78 # Call parent class constructor
79 super().__init__(properties)
80 self.locals_var_dict = locals().copy()
82 # Input/Output files
83 self.io_dict = {
84 "in": {"input_dataset_path": input_dataset_path},
85 "out": {"output_model_path": output_model_path, "output_test_table_path": output_test_table_path, "output_plot_path": output_plot_path}
86 }
88 # Properties specific for BB
89 self.independent_vars = properties.get('independent_vars', {})
90 self.target = properties.get('target', {})
91 self.weight = properties.get('weight', {})
92 self.random_state_train_test = properties.get('random_state_train_test', 5)
93 self.degree = properties.get('degree', 2)
94 self.test_size = properties.get('test_size', 0.2)
95 self.scale = properties.get('scale', False)
96 self.properties = properties
98 # Check the properties
99 self.check_properties(properties)
100 self.check_arguments()
102 def check_data_params(self, out_log, err_log):
103 """ Checks all the input/output paths and parameters """
104 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__)
105 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__)
106 if self.io_dict["out"]["output_test_table_path"]:
107 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__)
108 if self.io_dict["out"]["output_plot_path"]:
109 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__)
111 @launchlogger
112 def launch(self) -> int:
113 """Execute the :class:`PolynomialRegression <regression.polynomial_regression.PolynomialRegression>` regression.polynomial_regression.PolynomialRegression object."""
115 # check input/output paths and parameters
116 self.check_data_params(self.out_log, self.err_log)
118 # Setup Biobb
119 if self.check_restart():
120 return 0
121 self.stage_files()
123 # load dataset
124 fu.log('Getting dataset from %s' % self.io_dict["in"]["input_dataset_path"], self.out_log, self.global_log)
125 if 'columns' in self.independent_vars:
126 labels = getHeader(self.io_dict["in"]["input_dataset_path"])
127 skiprows = 1
128 else:
129 labels = None
130 skiprows = None
131 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels)
133 # declare inputs, targets and weights
134 # the inputs are all the independent variables
135 X = getIndependentVars(self.independent_vars, data, self.out_log, self.__class__.__name__)
136 fu.log('Independent variables: [%s]' % (getIndependentVarsList(self.independent_vars)), self.out_log, self.global_log)
137 # target
138 y = getTarget(self.target, data, self.out_log, self.__class__.__name__)
139 fu.log('Target: %s' % (getTargetValue(self.target)), self.out_log, self.global_log)
140 # weights
141 if self.weight:
142 w = getWeight(self.weight, data, self.out_log, self.__class__.__name__)
143 fu.log('Weight column provided', self.out_log, self.global_log)
145 # train / test split
146 fu.log('Creating train and test sets', self.out_log, self.global_log)
147 arrays_sets = (X, y)
148 # if user provide weights
149 if self.weight:
150 arrays_sets = arrays_sets + (w,)
151 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)
152 else:
153 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)
155 # scale dataset
156 if self.scale:
157 fu.log('Scaling dataset', self.out_log, self.global_log)
158 scaler = StandardScaler()
159 X_train = scaler.fit_transform(X_train)
161 # regression
162 fu.log('Training dataset applying polynomial regression', self.out_log, self.global_log)
163 poly_features = PolynomialFeatures(degree=self.degree)
164 X_train_poly = poly_features.fit_transform(X_train)
165 model = linear_model.LinearRegression()
166 model.fit(X_train_poly, y_train)
168 # scores and coefficients train
169 y_hat_train = model.predict(X_train_poly)
170 rmse = (np.sqrt(mean_squared_error(y_train, y_hat_train)))
171 rss = ((y_train - y_hat_train) ** 2).sum()
172 score = r2_score(y_hat_train, y_train)
173 # bias = model.intercept_
174 coef = model.coef_
175 coef = ['%.3f' % item for item in coef]
176 adj_r2 = adjusted_r2(X_train_poly, y_train, score)
177 p_values = f_regression(X_train_poly, y_train)[1]
178 p_values = ['%.3f' % item for item in p_values]
180 # r-squared
181 r2_table = pd.DataFrame()
182 r2_table["feature"] = ['R2', 'Adj. R2', 'RMSE', 'RSS']
183 r2_table['coefficient'] = [score, adj_r2, rmse, rss]
185 fu.log('Calculating scores and coefficients for training dataset\n\nR2, ADJUSTED R2 & RMSE\n\n%s\n' % r2_table, self.out_log, self.global_log)
187 if self.scale:
188 X_test = scaler.transform(X_test)
189 X_test_poly = poly_features.fit_transform(X_test)
190 y_hat_test = model.predict(X_test_poly)
191 test_table = pd.DataFrame(y_hat_test, columns=['prediction'])
192 # reset y_test (problem with old indexes column)
193 y_test = y_test.reset_index(drop=True)
194 # add real values to predicted ones in test_table table
195 test_table['target'] = y_test
196 # calculate difference between target and prediction (absolute and %)
197 test_table['residual'] = test_table['target'] - test_table['prediction']
198 test_table['difference %'] = np.absolute(test_table['residual']/test_table['target']*100)
199 pd.set_option('display.float_format', lambda x: '%.2f' % x)
200 # sort by difference in %
201 test_table = test_table.sort_values(by=['difference %'])
202 test_table = test_table.reset_index(drop=True)
203 fu.log('Testing\n\nTEST DATA\n\n%s\n' % test_table, self.out_log, self.global_log)
205 # scores and coefficients test
206 r2_test = r2_score(y_hat_test, y_test)
207 adj_r2_test = adjusted_r2(X_test_poly, y_test, r2_test)
208 rmse_test = np.sqrt(mean_squared_error(y_test, y_hat_test))
209 rss_test = ((y_test - y_hat_test) ** 2).sum()
211 # r-squared
212 pd.set_option('display.float_format', lambda x: '%.6f' % x)
213 r2_table_test = pd.DataFrame()
214 r2_table_test["feature"] = ['R2', 'Adj. R2', 'RMSE', 'RSS']
215 r2_table_test['coefficient'] = [r2_test, adj_r2_test, rmse_test, rss_test]
217 fu.log('Calculating scores and coefficients for testing dataset\n\nR2, ADJUSTED R2 & RMSE\n\n%s\n' % r2_table_test, self.out_log, self.global_log)
219 if (self.io_dict["out"]["output_test_table_path"]):
220 fu.log('Saving testing data to %s' % self.io_dict["out"]["output_test_table_path"], self.out_log, self.global_log)
221 test_table.to_csv(self.io_dict["out"]["output_test_table_path"], index=False, header=True)
223 # create test plot
224 if (self.io_dict["out"]["output_plot_path"]):
225 fu.log('Saving residual plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log)
226 y_hat_test = y_hat_test.flatten()
227 y_hat_train = y_hat_train.flatten()
228 plot = plotResults(y_train, y_hat_train, y_test, y_hat_test)
229 plot.savefig(self.io_dict["out"]["output_plot_path"], dpi=150)
231 # save model, scaler and parameters
232 variables = {
233 'target': self.target,
234 'independent_vars': self.independent_vars,
235 'scale': self.scale
236 }
237 fu.log('Saving model to %s' % self.io_dict["out"]["output_model_path"], self.out_log, self.global_log)
238 with open(self.io_dict["out"]["output_model_path"], "wb") as f:
239 joblib.dump(model, f)
240 if self.scale:
241 joblib.dump(scaler, f)
242 joblib.dump(poly_features, f)
243 joblib.dump(variables, f)
245 # Copy files to host
246 self.copy_to_host()
248 self.tmp_files.extend([
249 self.stage_io_dict.get("unique_dir")
250 ])
251 self.remove_tmp_files()
253 self.check_arguments(output_files_created=True, raise_exception=False)
255 return 0
258def polynomial_regression(input_dataset_path: str, output_model_path: str, output_test_table_path: str = None, output_plot_path: str = None, properties: dict = None, **kwargs) -> int:
259 """Execute the :class:`PolynomialRegression <regression.polynomial_regression.PolynomialRegression>` class and
260 execute the :meth:`launch() <regression.polynomial_regression.PolynomialRegression.launch>` method."""
262 return PolynomialRegression(input_dataset_path=input_dataset_path,
263 output_model_path=output_model_path,
264 output_test_table_path=output_test_table_path,
265 output_plot_path=output_plot_path,
266 properties=properties, **kwargs).launch()
269def main():
270 """Command line execution of this building block. Please check the command line documentation."""
271 parser = argparse.ArgumentParser(description="Wrapper of the scikit-learn LinearRegression method with PolynomialFeatures.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
272 parser.add_argument('--config', required=False, help='Configuration file')
274 # Specific args of each building block
275 required_args = parser.add_argument_group('required arguments')
276 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.')
277 required_args.add_argument('--output_model_path', required=True, help='Path to the output model file. Accepted formats: pkl.')
278 parser.add_argument('--output_test_table_path', required=False, help='Path to the test table file. Accepted formats: csv.')
279 parser.add_argument('--output_plot_path', required=False, help='Residual plot checks the error between actual values and predicted values. Accepted formats: png.')
281 args = parser.parse_args()
282 args.config = args.config or "{}"
283 properties = settings.ConfReader(config=args.config).get_prop_dic()
285 # Specific call of each building block
286 polynomial_regression(input_dataset_path=args.input_dataset_path,
287 output_model_path=args.output_model_path,
288 output_test_table_path=args.output_test_table_path,
289 output_plot_path=args.output_plot_path,
290 properties=properties)
293if __name__ == '__main__':
294 main()