Coverage for biobb_ml/neural_networks/regression_neural_network.py: 85%
179 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 RegressionNeuralNetwork class and the command line interface."""
4import argparse
5import h5py
6import json
7import numpy as np
8import pandas as pd
9from biobb_common.generic.biobb_object import BiobbObject
10from tensorflow.python.keras.saving import hdf5_format
11from sklearn.preprocessing import scale
12from sklearn.model_selection import train_test_split
13from sklearn.metrics import r2_score
14from tensorflow.keras import Sequential
15from tensorflow.keras.layers import Dense
16from tensorflow.keras.callbacks import EarlyStopping
17from biobb_common.configuration import settings
18from biobb_common.tools import file_utils as fu
19from biobb_common.tools.file_utils import launchlogger
20from biobb_ml.neural_networks.common import check_input_path, check_output_path, getHeader, getTargetValue, plotResultsReg, getFeatures, getIndependentVarsList, getTarget, getWeight
23class RegressionNeuralNetwork(BiobbObject):
24 """
25 | biobb_ml RegressionNeuralNetwork
26 | Wrapper of the TensorFlow Keras Sequential method for regression.
27 | Trains and tests a given dataset and save the complete model for a Neural Network Regression. Visit the `Sequential documentation page <https://www.tensorflow.org/api_docs/python/tf/keras/Sequential>`_ in the TensorFlow Keras official website for further information.
29 Args:
30 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/neural_networks/dataset_regression.csv>`_. Accepted formats: csv (edam:format_3752).
31 output_model_path (str): Path to the output model file. File type: output. `Sample file <http://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/neural_networks/ref_output_model_regression.h5>`_. Accepted formats: h5 (edam:format_3590).
32 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/neural_networks/ref_output_test_regression.csv>`_. Accepted formats: csv (edam:format_3752).
33 output_plot_path (str) (Optional): Loss, MAE and MSE plots. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/neural_networks/ref_output_plot_regression.png>`_. Accepted formats: png (edam:format_3603).
34 properties (dic - Python dictionary object containing the tool parameters, not input/output files):
35 * **features** (*dict*) - ({}) Independent variables or columns from your dataset you want to train. 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.
36 * **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.
37 * **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.
38 * **validation_size** (*float*) - (0.2) [0~1|0.05] Represents the proportion of the dataset to include in the validation split. It should be between 0.0 and 1.0.
39 * **test_size** (*float*) - (0.1) [0~1|0.05] Represents the proportion of the dataset to include in the test split. It should be between 0.0 and 1.0.
40 * **hidden_layers** (*list*) - (None) List of dictionaries with hidden layers values. Format: [ { 'size': 50, 'activation': 'relu' } ].
41 * **output_layer_activation** (*string*) - ("softmax") Activation function to use in the output layer. Values: sigmoid (Sigmoid activation function: sigmoid[x] = 1 / [1 + exp[-x]]), tanh (Hyperbolic tangent activation function), relu (Applies the rectified linear unit activation function), softmax(Softmax converts a real vector to a vector of categorical probabilities).
42 * **optimizer** (*string*) - ("Adam") Name of optimizer instance. Values: Adadelta (Adadelta optimization is a stochastic gradient descent method that is based on adaptive learning rate per dimension to address two drawbacks: the continual decay of learning rates throughout training and the need for a manually selected global learning rate), Adagrad (Adagrad is an optimizer with parameter-specific learning rates; which are adapted relative to how frequently a parameter gets updated during training. The more updates a parameter receives; the smaller the updates), Adam (Adam optimization is a stochastic gradient descent method that is based on adaptive estimation of first-order and second-order moments), Adamax (It is a variant of Adam based on the infinity norm. Default parameters follow those provided in the paper. Adamax is sometimes superior to adam; specially in models with embeddings), Ftrl (Optimizer that implements the FTRL algorithm), Nadam (Much like Adam is essentially RMSprop with momentum; Nadam is Adam with Nesterov momentum), RMSprop (Optimizer that implements the RMSprop algorithm), SGD (Gradient descent -with momentum- optimizer).
43 * **learning_rate** (*float*) - (0.02) [0~100|0.01] Determines the step size at each iteration while moving toward a minimum of a loss function
44 * **batch_size** (*int*) - (100) [0~1000|1] Number of samples per gradient update.
45 * **max_epochs** (*int*) - (100) [0~1000|1] Number of epochs to train the model. As the early stopping is enabled, this is a maximum.
46 * **random_state** (*int*) - (5) [1~1000|1] Controls the shuffling applied to the data before applying the split. .
47 * **scale** (*bool*) - (False) Whether or not to scale the input dataset.
48 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files.
49 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist.
50 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory.
52 Examples:
53 This is a use example of how to use the building block from Python::
55 from biobb_ml.neural_networks.regression_neural_network import regression_neural_network
56 prop = {
57 'features': {
58 'columns': [ 'column1', 'column2', 'column3' ]
59 },
60 'target': {
61 'column': 'target'
62 },
63 'validation_size': 0.2,
64 'test_size': .33,
65 'hidden_layers': [
66 {
67 'size': 10,
68 'activation': 'relu'
69 },
70 {
71 'size': 8,
72 'activation': 'relu'
73 }
74 ],
75 'optimizer': 'Adam',
76 'learning_rate': 0.01,
77 'batch_size': 32,
78 'max_epochs': 150
79 }
80 regression_neural_network(input_dataset_path='/path/to/myDataset.csv',
81 output_model_path='/path/to/newModel.h5',
82 output_test_table_path='/path/to/newTable.csv',
83 output_plot_path='/path/to/newPlot.png',
84 properties=prop)
86 Info:
87 * wrapped_software:
88 * name: TensorFlow Keras Sequential
89 * version: >2.1.0
90 * license: MIT
91 * ontology:
92 * name: EDAM
93 * schema: http://edamontology.org/EDAM.owl
95 """
97 def __init__(self, input_dataset_path,
98 output_model_path, output_test_table_path=None, output_plot_path=None, properties=None, **kwargs) -> None:
99 properties = properties or {}
101 # Call parent class constructor
102 super().__init__(properties)
103 self.locals_var_dict = locals().copy()
105 # Input/Output files
106 self.io_dict = {
107 "in": {"input_dataset_path": input_dataset_path},
108 "out": {"output_model_path": output_model_path, "output_test_table_path": output_test_table_path, "output_plot_path": output_plot_path}
109 }
111 # Properties specific for BB
112 self.features = properties.get('features', {})
113 self.target = properties.get('target', {})
114 self.weight = properties.get('weight', {})
115 self.validation_size = properties.get('validation_size', 0.1)
116 self.test_size = properties.get('test_size', 0.1)
117 self.hidden_layers = properties.get('hidden_layers', [])
118 self.output_layer_activation = properties.get('output_layer_activation', 'softmax')
119 self.optimizer = properties.get('optimizer', 'Adam')
120 self.learning_rate = properties.get('learning_rate', 0.02)
121 self.batch_size = properties.get('batch_size', 100)
122 self.max_epochs = properties.get('max_epochs', 100)
123 self.random_state = properties.get('random_state', 5)
124 self.scale = properties.get('scale', False)
125 self.properties = properties
127 # Check the properties
128 self.check_properties(properties)
129 self.check_arguments()
131 def check_data_params(self, out_log, err_log):
132 """ Checks all the input/output paths and parameters """
133 self.io_dict["in"]["input_dataset_path"] = check_input_path(self.io_dict["in"]["input_dataset_path"], "input_dataset_path", False, out_log, self.__class__.__name__)
134 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__)
135 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__)
136 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__)
138 def build_model(self, input_shape):
139 """ Builds Neural network according to hidden_layers property """
141 # create model
142 model = Sequential([])
144 # if no hidden_layers provided, create manually a hidden layer with default values
145 if not self.hidden_layers:
146 self.hidden_layers = [{'size': 50, 'activation': 'relu'}]
148 # generate hidden_layers
149 for i, layer in enumerate(self.hidden_layers):
150 if i == 0:
151 model.add(Dense(layer['size'], activation=layer['activation'], kernel_initializer='he_normal', input_shape=input_shape)) # 1st hidden layer
152 else:
153 model.add(Dense(layer['size'], activation=layer['activation'], kernel_initializer='he_normal'))
155 model.add(Dense(1)) # output layer
157 return model
159 @launchlogger
160 def launch(self) -> int:
161 """Execute the :class:`RegressionNeuralNetwork <neural_networks.regression_neural_network.RegressionNeuralNetwork>` neural_networks.regression_neural_network.RegressionNeuralNetwork object."""
163 # check input/output paths and parameters
164 self.check_data_params(self.out_log, self.err_log)
166 # Setup Biobb
167 if self.check_restart():
168 return 0
169 self.stage_files()
171 # load dataset
172 fu.log('Getting dataset from %s' % self.io_dict["in"]["input_dataset_path"], self.out_log, self.global_log)
173 if 'columns' in self.features:
174 labels = getHeader(self.io_dict["in"]["input_dataset_path"])
175 skiprows = 1
176 else:
177 labels = None
178 skiprows = None
179 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels)
181 X = getFeatures(self.features, data, self.out_log, self.__class__.__name__)
182 fu.log('Features: [%s]' % (getIndependentVarsList(self.features)), self.out_log, self.global_log)
183 # target
184 y = getTarget(self.target, data, self.out_log, self.__class__.__name__)
185 fu.log('Target: %s' % (str(getTargetValue(self.target))), self.out_log, self.global_log)
186 # weights
187 if self.weight:
188 w = getWeight(self.weight, data, self.out_log, self.__class__.__name__)
190 # shuffle dataset
191 fu.log('Shuffling dataset', self.out_log, self.global_log)
192 shuffled_indices = np.arange(X.shape[0])
193 np.random.shuffle(shuffled_indices)
194 np_X = X.to_numpy()
195 shuffled_X = np_X[shuffled_indices]
196 shuffled_y = y[shuffled_indices]
197 if self.weight:
198 shuffled_w = w[shuffled_indices]
200 # train / test split
201 fu.log('Creating train and test sets', self.out_log, self.global_log)
202 arrays_sets = (shuffled_X, shuffled_y)
203 # if user provide weights
204 if self.weight:
205 arrays_sets = arrays_sets + (shuffled_w,)
206 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)
207 else:
208 X_train, X_test, y_train, y_test = train_test_split(*arrays_sets, test_size=self.test_size, random_state=self.random_state)
210 # scale dataset
211 if self.scale:
212 fu.log('Scaling dataset', self.out_log, self.global_log)
213 X_train = scale(X_train)
215 # build model
216 fu.log('Building model', self.out_log, self.global_log)
217 model = self.build_model((X_train.shape[1],))
219 # model summary
220 stringlist = []
221 model.summary(print_fn=lambda x: stringlist.append(x))
222 model_summary = "\n".join(stringlist)
223 fu.log('Model summary:\n\n%s\n' % model_summary, self.out_log, self.global_log)
225 # get optimizer
226 mod = __import__('tensorflow.keras.optimizers', fromlist=[self.optimizer])
227 opt_class = getattr(mod, self.optimizer)
228 opt = opt_class(lr=self.learning_rate)
229 # compile model
230 model.compile(optimizer=opt, loss='mse', metrics=['mae', 'mse'], sample_weight_mode='samplewise')
232 # fitting
233 fu.log('Training model', self.out_log, self.global_log)
234 # set an early stopping mechanism
235 # set patience=2, to be a bit tolerant against random validation loss increases
236 early_stopping = EarlyStopping(patience=2)
238 if self.weight:
239 sample_weight = w_train
240 class_weight = []
241 else:
242 # TODO: class_weight not working since TF 2.4.1 update
243 # fu.log('No weight provided, class_weight will be estimated from the target data', self.out_log, self.global_log)
244 sample_weight = None
245 class_weight = [] # compute_class_weight('balanced', np.unique(y_train), y_train)
247 # fit the model
248 mf = model.fit(X_train,
249 y_train,
250 class_weight=class_weight,
251 sample_weight=sample_weight,
252 batch_size=self.batch_size,
253 epochs=self.max_epochs,
254 callbacks=[early_stopping],
255 validation_split=self.validation_size,
256 verbose=1)
258 fu.log('Total epochs performed: %s' % len(mf.history['loss']), self.out_log, self.global_log)
260 # predict data from X_train
261 train_predictions = model.predict(X_train)
262 train_predictions = np.around(train_predictions, decimals=2)
264 score_train_inputs = (y_train, train_predictions)
265 if self.weight:
266 score_train_inputs = score_train_inputs + (w_train,)
267 train_score = r2_score(*score_train_inputs)
269 train_metrics = pd.DataFrame()
270 train_metrics['metric'] = ['Train loss', 'Train MAE', 'Train MSE', 'Train R2', 'Validation loss', 'Validation MAE', 'Validation MSE']
271 train_metrics['coefficient'] = [mf.history['loss'][-1], mf.history['mae'][-1], mf.history['mse'][-1], train_score, mf.history['val_loss'][-1], mf.history['val_mae'][-1], mf.history['val_mse'][-1]]
273 fu.log('Training metrics\n\nTRAINING METRICS TABLE\n\n%s\n' % train_metrics, self.out_log, self.global_log)
275 # testing
276 if self.scale:
277 X_test = scale(X_test)
278 fu.log('Testing model', self.out_log, self.global_log)
279 test_loss, test_mae, test_mse = model.evaluate(X_test, y_test)
281 # predict data from X_test
282 test_predictions = model.predict(X_test)
283 test_predictions = np.around(test_predictions, decimals=2)
284 tpr = np.squeeze(np.asarray(test_predictions))
286 score_test_inputs = (y_test, test_predictions)
287 if self.weight:
288 score_test_inputs = score_test_inputs + (w_test,)
289 score = r2_score(*score_test_inputs)
291 test_metrics = pd.DataFrame()
292 test_metrics['metric'] = ['Test loss', 'Test MAE', 'Test MSE', 'Test R2']
293 test_metrics['coefficient'] = [test_loss, test_mae, test_mse, score]
295 fu.log('Testing metrics\n\nTESTING METRICS TABLE\n\n%s\n' % test_metrics, self.out_log, self.global_log)
297 test_table = pd.DataFrame()
298 test_table['prediction'] = tpr
299 test_table['target'] = y_test
300 test_table['residual'] = test_table['target'] - test_table['prediction']
301 test_table['difference %'] = np.absolute(test_table['residual']/test_table['target']*100)
302 pd.set_option('display.float_format', lambda x: '%.2f' % x)
303 # sort by difference in %
304 test_table = test_table.sort_values(by=['difference %'])
305 test_table = test_table.reset_index(drop=True)
306 fu.log('TEST DATA\n\n%s\n' % test_table, self.out_log, self.global_log)
308 # save test data
309 if (self.io_dict["out"]["output_test_table_path"]):
310 fu.log('Saving testing data to %s' % self.io_dict["out"]["output_test_table_path"], self.out_log, self.global_log)
311 test_table.to_csv(self.io_dict["out"]["output_test_table_path"], index=False, header=True)
313 # create test plot
314 if (self.io_dict["out"]["output_plot_path"]):
315 fu.log('Saving plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log)
316 test_predictions = test_predictions.flatten()
317 train_predictions = model.predict(X_train).flatten()
318 plot = plotResultsReg(mf.history, y_test, test_predictions, y_train, train_predictions)
319 plot.savefig(self.io_dict["out"]["output_plot_path"], dpi=150)
321 # save model and parameters
322 vars_obj = {
323 'features': self.features,
324 'target': self.target,
325 'scale': self.scale,
326 'type': 'regression'
327 }
328 variables = json.dumps(vars_obj)
329 fu.log('Saving model to %s' % self.io_dict["out"]["output_model_path"], self.out_log, self.global_log)
330 with h5py.File(self.io_dict["out"]["output_model_path"], mode='w') as f:
331 hdf5_format.save_model_to_hdf5(model, f)
332 f.attrs['variables'] = variables
334 # Copy files to host
335 self.copy_to_host()
337 self.tmp_files.extend([
338 self.stage_io_dict.get("unique_dir")
339 ])
340 self.remove_tmp_files()
342 self.check_arguments(output_files_created=True, raise_exception=False)
344 return 0
347def regression_neural_network(input_dataset_path: str, output_model_path: str, output_test_table_path: str = None, output_plot_path: str = None, properties: dict = None, **kwargs) -> int:
348 """Execute the :class:`RegressionNeuralNetwork <neural_networks.regression_neural_network.RegressionNeuralNetwork>` class and
349 execute the :meth:`launch() <neural_networks.regression_neural_network.RegressionNeuralNetwork.launch>` method."""
351 return RegressionNeuralNetwork(input_dataset_path=input_dataset_path,
352 output_model_path=output_model_path,
353 output_test_table_path=output_test_table_path,
354 output_plot_path=output_plot_path,
355 properties=properties, **kwargs).launch()
358def main():
359 """Command line execution of this building block. Please check the command line documentation."""
360 parser = argparse.ArgumentParser(description="Wrapper of the TensorFlow Keras Sequential method.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999))
361 parser.add_argument('--config', required=False, help='Configuration file')
363 # Specific args of each building block
364 required_args = parser.add_argument_group('required arguments')
365 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.')
366 required_args.add_argument('--output_model_path', required=True, help='Path to the output model file. Accepted formats: h5.')
367 parser.add_argument('--output_test_table_path', required=False, help='Path to the test table file. Accepted formats: csv.')
368 parser.add_argument('--output_plot_path', required=False, help='Loss, MAE and MSE plots. Accepted formats: png.')
370 args = parser.parse_args()
371 args.config = args.config or "{}"
372 properties = settings.ConfReader(config=args.config).get_prop_dic()
374 # Specific call of each building block
375 regression_neural_network(input_dataset_path=args.input_dataset_path,
376 output_model_path=args.output_model_path,
377 output_test_table_path=args.output_test_table_path,
378 output_plot_path=args.output_plot_path,
379 properties=properties)
382if __name__ == '__main__':
383 main()