Coverage for biobb_ml/neural_networks/regression_neural_network.py: 85%

180 statements  

« prev     ^ index     » next       coverage.py v7.5.1, created at 2024-05-07 09:39 +0000

1#!/usr/bin/env python3 

2 

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 

21 

22 

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. 

28 

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 

51 Examples: 

52 This is a use example of how to use the building block from Python:: 

53 

54 from biobb_ml.neural_networks.regression_neural_network import regression_neural_network 

55 prop = { 

56 'features': { 

57 'columns': [ 'column1', 'column2', 'column3' ] 

58 }, 

59 'target': { 

60 'column': 'target' 

61 }, 

62 'validation_size': 0.2, 

63 'test_size': .33, 

64 'hidden_layers': [ 

65 { 

66 'size': 10, 

67 'activation': 'relu' 

68 }, 

69 { 

70 'size': 8, 

71 'activation': 'relu' 

72 } 

73 ], 

74 'optimizer': 'Adam', 

75 'learning_rate': 0.01, 

76 'batch_size': 32, 

77 'max_epochs': 150 

78 } 

79 regression_neural_network(input_dataset_path='/path/to/myDataset.csv', 

80 output_model_path='/path/to/newModel.h5', 

81 output_test_table_path='/path/to/newTable.csv', 

82 output_plot_path='/path/to/newPlot.png', 

83 properties=prop) 

84 

85 Info: 

86 * wrapped_software: 

87 * name: TensorFlow Keras Sequential 

88 * version: >2.1.0 

89 * license: MIT 

90 * ontology: 

91 * name: EDAM 

92 * schema: http://edamontology.org/EDAM.owl 

93 

94 """ 

95 

96 def __init__(self, input_dataset_path, 

97 output_model_path, output_test_table_path=None, output_plot_path=None, properties=None, **kwargs) -> None: 

98 properties = properties or {} 

99 

100 # Call parent class constructor 

101 super().__init__(properties) 

102 self.locals_var_dict = locals().copy() 

103 

104 # Input/Output files 

105 self.io_dict = { 

106 "in": {"input_dataset_path": input_dataset_path}, 

107 "out": {"output_model_path": output_model_path, "output_test_table_path": output_test_table_path, "output_plot_path": output_plot_path} 

108 } 

109 

110 # Properties specific for BB 

111 self.features = properties.get('features', {}) 

112 self.target = properties.get('target', {}) 

113 self.weight = properties.get('weight', {}) 

114 self.validation_size = properties.get('validation_size', 0.1) 

115 self.test_size = properties.get('test_size', 0.1) 

116 self.hidden_layers = properties.get('hidden_layers', []) 

117 self.output_layer_activation = properties.get('output_layer_activation', 'softmax') 

118 self.optimizer = properties.get('optimizer', 'Adam') 

119 self.learning_rate = properties.get('learning_rate', 0.02) 

120 self.batch_size = properties.get('batch_size', 100) 

121 self.max_epochs = properties.get('max_epochs', 100) 

122 self.random_state = properties.get('random_state', 5) 

123 self.scale = properties.get('scale', False) 

124 self.properties = properties 

125 

126 # Check the properties 

127 self.check_properties(properties) 

128 self.check_arguments() 

129 

130 def check_data_params(self, out_log, err_log): 

131 """ Checks all the input/output paths and parameters """ 

132 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__) 

133 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__) 

134 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__) 

135 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__) 

136 

137 def build_model(self, input_shape): 

138 """ Builds Neural network according to hidden_layers property """ 

139 

140 # create model 

141 model = Sequential([]) 

142 

143 # if no hidden_layers provided, create manually a hidden layer with default values 

144 if not self.hidden_layers: 

145 self.hidden_layers = [{'size': 50, 'activation': 'relu'}] 

146 

147 # generate hidden_layers 

148 for i, layer in enumerate(self.hidden_layers): 

149 if i == 0: 

150 model.add(Dense(layer['size'], activation=layer['activation'], kernel_initializer='he_normal', input_shape=input_shape)) # 1st hidden layer 

151 else: 

152 model.add(Dense(layer['size'], activation=layer['activation'], kernel_initializer='he_normal')) 

153 

154 model.add(Dense(1)) # output layer 

155 

156 return model 

157 

158 @launchlogger 

159 def launch(self) -> int: 

160 """Execute the :class:`RegressionNeuralNetwork <neural_networks.regression_neural_network.RegressionNeuralNetwork>` neural_networks.regression_neural_network.RegressionNeuralNetwork object.""" 

161 

162 # check input/output paths and parameters 

163 self.check_data_params(self.out_log, self.err_log) 

164 

165 # Setup Biobb 

166 if self.check_restart(): 

167 return 0 

168 self.stage_files() 

169 

170 # load dataset 

171 fu.log('Getting dataset from %s' % self.io_dict["in"]["input_dataset_path"], self.out_log, self.global_log) 

172 if 'columns' in self.features: 

173 labels = getHeader(self.io_dict["in"]["input_dataset_path"]) 

174 skiprows = 1 

175 else: 

176 labels = None 

177 skiprows = None 

178 data = pd.read_csv(self.io_dict["in"]["input_dataset_path"], header=None, sep="\\s+|;|:|,|\t", engine="python", skiprows=skiprows, names=labels) 

179 

180 X = getFeatures(self.features, data, self.out_log, self.__class__.__name__) 

181 fu.log('Features: [%s]' % (getIndependentVarsList(self.features)), self.out_log, self.global_log) 

182 # target 

183 y = getTarget(self.target, data, self.out_log, self.__class__.__name__) 

184 fu.log('Target: %s' % (str(getTargetValue(self.target))), self.out_log, self.global_log) 

185 # weights 

186 if self.weight: 

187 w = getWeight(self.weight, data, self.out_log, self.__class__.__name__) 

188 

189 # shuffle dataset 

190 fu.log('Shuffling dataset', self.out_log, self.global_log) 

191 shuffled_indices = np.arange(X.shape[0]) 

192 np.random.shuffle(shuffled_indices) 

193 np_X = X.to_numpy() 

194 shuffled_X = np_X[shuffled_indices] 

195 shuffled_y = y[shuffled_indices] 

196 if self.weight: 

197 shuffled_w = w[shuffled_indices] 

198 

199 # train / test split 

200 fu.log('Creating train and test sets', self.out_log, self.global_log) 

201 arrays_sets = (shuffled_X, shuffled_y) 

202 # if user provide weights 

203 if self.weight: 

204 arrays_sets = arrays_sets + (shuffled_w,) 

205 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) 

206 else: 

207 X_train, X_test, y_train, y_test = train_test_split(*arrays_sets, test_size=self.test_size, random_state=self.random_state) 

208 

209 # scale dataset 

210 if self.scale: 

211 fu.log('Scaling dataset', self.out_log, self.global_log) 

212 X_train = scale(X_train) 

213 

214 # build model 

215 fu.log('Building model', self.out_log, self.global_log) 

216 model = self.build_model((X_train.shape[1],)) 

217 

218 # model summary 

219 stringlist = [] 

220 model.summary(print_fn=lambda x: stringlist.append(x)) 

221 model_summary = "\n".join(stringlist) 

222 fu.log('Model summary:\n\n%s\n' % model_summary, self.out_log, self.global_log) 

223 

224 # get optimizer 

225 mod = __import__('tensorflow.keras.optimizers', fromlist=[self.optimizer]) 

226 opt_class = getattr(mod, self.optimizer) 

227 opt = opt_class(lr=self.learning_rate) 

228 # compile model 

229 model.compile(optimizer=opt, loss='mse', metrics=['mae', 'mse'], sample_weight_mode='samplewise') 

230 

231 # fitting 

232 fu.log('Training model', self.out_log, self.global_log) 

233 # set an early stopping mechanism 

234 # set patience=2, to be a bit tolerant against random validation loss increases 

235 early_stopping = EarlyStopping(patience=2) 

236 

237 if self.weight: 

238 sample_weight = w_train 

239 class_weight = [] 

240 else: 

241 # TODO: class_weight not working since TF 2.4.1 update 

242 # fu.log('No weight provided, class_weight will be estimated from the target data', self.out_log, self.global_log) 

243 sample_weight = None 

244 class_weight = [] # compute_class_weight('balanced', np.unique(y_train), y_train) 

245 

246 # fit the model 

247 mf = model.fit(X_train, 

248 y_train, 

249 class_weight=class_weight, 

250 sample_weight=sample_weight, 

251 batch_size=self.batch_size, 

252 epochs=self.max_epochs, 

253 callbacks=[early_stopping], 

254 validation_split=self.validation_size, 

255 verbose=1) 

256 

257 fu.log('Total epochs performed: %s' % len(mf.history['loss']), self.out_log, self.global_log) 

258 

259 # predict data from X_train 

260 train_predictions = model.predict(X_train) 

261 train_predictions = np.around(train_predictions, decimals=2) 

262 

263 score_train_inputs = (y_train, train_predictions) 

264 if self.weight: 

265 score_train_inputs = score_train_inputs + (w_train,) 

266 train_score = r2_score(*score_train_inputs) 

267 

268 train_metrics = pd.DataFrame() 

269 train_metrics['metric'] = ['Train loss', 'Train MAE', 'Train MSE', 'Train R2', 'Validation loss', 'Validation MAE', 'Validation MSE'] 

270 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]] 

271 

272 fu.log('Training metrics\n\nTRAINING METRICS TABLE\n\n%s\n' % train_metrics, self.out_log, self.global_log) 

273 

274 # testing 

275 if self.scale: 

276 X_test = scale(X_test) 

277 fu.log('Testing model', self.out_log, self.global_log) 

278 test_loss, test_mae, test_mse = model.evaluate(X_test, y_test) 

279 

280 # predict data from X_test 

281 test_predictions = model.predict(X_test) 

282 test_predictions = np.around(test_predictions, decimals=2) 

283 tpr = np.squeeze(np.asarray(test_predictions)) 

284 

285 score_test_inputs = (y_test, test_predictions) 

286 if self.weight: 

287 score_test_inputs = score_test_inputs + (w_test,) 

288 score = r2_score(*score_test_inputs) 

289 

290 test_metrics = pd.DataFrame() 

291 test_metrics['metric'] = ['Test loss', 'Test MAE', 'Test MSE', 'Test R2'] 

292 test_metrics['coefficient'] = [test_loss, test_mae, test_mse, score] 

293 

294 fu.log('Testing metrics\n\nTESTING METRICS TABLE\n\n%s\n' % test_metrics, self.out_log, self.global_log) 

295 

296 test_table = pd.DataFrame() 

297 test_table['prediction'] = tpr 

298 test_table['target'] = y_test 

299 test_table['residual'] = test_table['target'] - test_table['prediction'] 

300 test_table['difference %'] = np.absolute(test_table['residual']/test_table['target']*100) 

301 pd.set_option('display.float_format', lambda x: '%.2f' % x) 

302 # sort by difference in % 

303 test_table = test_table.sort_values(by=['difference %']) 

304 test_table = test_table.reset_index(drop=True) 

305 fu.log('TEST DATA\n\n%s\n' % test_table, self.out_log, self.global_log) 

306 

307 # save test data 

308 if (self.io_dict["out"]["output_test_table_path"]): 

309 fu.log('Saving testing data to %s' % self.io_dict["out"]["output_test_table_path"], self.out_log, self.global_log) 

310 test_table.to_csv(self.io_dict["out"]["output_test_table_path"], index=False, header=True) 

311 

312 # create test plot 

313 if (self.io_dict["out"]["output_plot_path"]): 

314 fu.log('Saving plot to %s' % self.io_dict["out"]["output_plot_path"], self.out_log, self.global_log) 

315 test_predictions = test_predictions.flatten() 

316 train_predictions = model.predict(X_train).flatten() 

317 plot = plotResultsReg(mf.history, y_test, test_predictions, y_train, train_predictions) 

318 plot.savefig(self.io_dict["out"]["output_plot_path"], dpi=150) 

319 

320 # save model and parameters 

321 vars_obj = { 

322 'features': self.features, 

323 'target': self.target, 

324 'scale': self.scale, 

325 'type': 'regression' 

326 } 

327 variables = json.dumps(vars_obj) 

328 fu.log('Saving model to %s' % self.io_dict["out"]["output_model_path"], self.out_log, self.global_log) 

329 with h5py.File(self.io_dict["out"]["output_model_path"], mode='w') as f: 

330 hdf5_format.save_model_to_hdf5(model, f) 

331 f.attrs['variables'] = variables 

332 

333 # Copy files to host 

334 self.copy_to_host() 

335 

336 self.tmp_files.extend([ 

337 self.stage_io_dict.get("unique_dir") 

338 ]) 

339 self.remove_tmp_files() 

340 

341 self.check_arguments(output_files_created=True, raise_exception=False) 

342 

343 return 0 

344 

345 

346def 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: 

347 """Execute the :class:`RegressionNeuralNetwork <neural_networks.regression_neural_network.RegressionNeuralNetwork>` class and 

348 execute the :meth:`launch() <neural_networks.regression_neural_network.RegressionNeuralNetwork.launch>` method.""" 

349 

350 return RegressionNeuralNetwork(input_dataset_path=input_dataset_path, 

351 output_model_path=output_model_path, 

352 output_test_table_path=output_test_table_path, 

353 output_plot_path=output_plot_path, 

354 properties=properties, **kwargs).launch() 

355 

356 

357def main(): 

358 """Command line execution of this building block. Please check the command line documentation.""" 

359 parser = argparse.ArgumentParser(description="Wrapper of the TensorFlow Keras Sequential method.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

360 parser.add_argument('--config', required=False, help='Configuration file') 

361 

362 # Specific args of each building block 

363 required_args = parser.add_argument_group('required arguments') 

364 required_args.add_argument('--input_dataset_path', required=True, help='Path to the input dataset. Accepted formats: csv.') 

365 required_args.add_argument('--output_model_path', required=True, help='Path to the output model file. Accepted formats: h5.') 

366 parser.add_argument('--output_test_table_path', required=False, help='Path to the test table file. Accepted formats: csv.') 

367 parser.add_argument('--output_plot_path', required=False, help='Loss, MAE and MSE plots. Accepted formats: png.') 

368 

369 args = parser.parse_args() 

370 args.config = args.config or "{}" 

371 properties = settings.ConfReader(config=args.config).get_prop_dic() 

372 

373 # Specific call of each building block 

374 regression_neural_network(input_dataset_path=args.input_dataset_path, 

375 output_model_path=args.output_model_path, 

376 output_test_table_path=args.output_test_table_path, 

377 output_plot_path=args.output_plot_path, 

378 properties=properties) 

379 

380 

381if __name__ == '__main__': 

382 main()