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

192 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-10-03 14:57 +0000

1#!/usr/bin/env python3 

2 

3"""Module containing the ClassificationNeuralNetwork 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 tensorflow.keras import Sequential 

14from tensorflow.keras.layers import Dense 

15from tensorflow.keras.callbacks import EarlyStopping 

16from tensorflow import math 

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, getFeatures, getIndependentVarsList, getWeight, plotResultsClassMultCM, plotResultsClassBinCM 

21 

22 

23class ClassificationNeuralNetwork(BiobbObject): 

24 """ 

25 | biobb_ml ClassificationNeuralNetwork 

26 | Wrapper of the TensorFlow Keras Sequential method for classification. 

27 | Trains and tests a given dataset and save the complete model for a Neural Network Classification. 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_classification.csv>`_. Accepted formats: csv (edam:format_3752). 

31 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/neural_networks/ref_output_model_classification.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_classification.csv>`_. Accepted formats: csv (edam:format_3752). 

33 output_plot_path (str) (Optional): Loss, accuracy 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_classification.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 multiple 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 * **normalize_cm** (*bool*) - (False) Whether or not to normalize the confusion matrix. 

47 * **random_state** (*int*) - (5) [1~1000|1] Controls the shuffling applied to the data before applying the split. . 

48 * **scale** (*bool*) - (False) Whether or not to scale the input dataset. 

49 * **remove_tmp** (*bool*) - (True) [WF property] Remove temporal files. 

50 * **restart** (*bool*) - (False) [WF property] Do not execute if output files exist. 

51 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

52 

53 Examples: 

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

55 

56 from biobb_ml.neural_networks.classification_neural_network import classification_neural_network 

57 prop = { 

58 'features': { 

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

60 }, 

61 'target': { 

62 'column': 'target' 

63 }, 

64 'validation_size': 0.2, 

65 'test_size': .33, 

66 'hidden_layers': [ 

67 { 

68 'size': 10, 

69 'activation': 'relu' 

70 }, 

71 { 

72 'size': 8, 

73 'activation': 'relu' 

74 } 

75 ], 

76 'optimizer': 'Adam', 

77 'learning_rate': 0.01, 

78 'batch_size': 32, 

79 'max_epochs': 150 

80 } 

81 classification_neural_network(input_dataset_path='/path/to/myDataset.csv', 

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

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

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

85 properties=prop) 

86 

87 Info: 

88 * wrapped_software: 

89 * name: TensorFlow Keras Sequential 

90 * version: >2.1.0 

91 * license: MIT 

92 * ontology: 

93 * name: EDAM 

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

95 

96 """ 

97 

98 def __init__(self, input_dataset_path, output_model_path, 

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

100 properties = properties or {} 

101 

102 # Call parent class constructor 

103 super().__init__(properties) 

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

105 

106 # Input/Output files 

107 self.io_dict = { 

108 "in": {"input_dataset_path": input_dataset_path}, 

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

110 } 

111 

112 # Properties specific for BB 

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

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

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

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

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

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

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

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

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

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

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

124 self.normalize_cm = properties.get('normalize_cm', False) 

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

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

127 self.properties = properties 

128 

129 # Check the properties 

130 self.check_properties(properties) 

131 self.check_arguments() 

132 

133 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

139 

140 def build_model(self, input_shape, output_size): 

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

142 

143 # create model 

144 model = Sequential([]) 

145 

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

147 if not self.hidden_layers: 

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

149 

150 # generate hidden_layers 

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

152 if i == 0: 

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

154 else: 

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

156 

157 model.add(Dense(output_size, activation=self.output_layer_activation)) # output layer 

158 

159 return model 

160 

161 @launchlogger 

162 def launch(self) -> int: 

163 """Execute the :class:`ClassificationNeuralNetwork <neural_networks.classification_neural_network.ClassificationNeuralNetwork>` neural_networks.classification_neural_network.ClassificationNeuralNetwork object.""" 

164 

165 # check input/output paths and parameters 

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

167 

168 # Setup Biobb 

169 if self.check_restart(): 

170 return 0 

171 self.stage_files() 

172 

173 # load dataset 

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

175 if 'columns' in self.features: 

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

177 skiprows = 1 

178 else: 

179 labels = None 

180 skiprows = None 

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

182 

183 targets_list = data[getTargetValue(self.target)].to_numpy() 

184 

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

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

187 # target 

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

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

190 # weights 

191 if self.weight: 

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

193 

194 # shuffle dataset 

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

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

197 np.random.shuffle(shuffled_indices) 

198 np_X = X.to_numpy() 

199 shuffled_X = np_X[shuffled_indices] 

200 shuffled_y = targets_list[shuffled_indices] 

201 if self.weight: 

202 shuffled_w = w[shuffled_indices] 

203 

204 # train / test split 

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

206 arrays_sets = (shuffled_X, shuffled_y) 

207 # if user provide weights 

208 if self.weight: 

209 arrays_sets = arrays_sets + (shuffled_w,) 

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

211 else: 

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

213 

214 # scale dataset 

215 if self.scale: 

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

217 X_train = scale(X_train) 

218 

219 # build model 

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

221 model = self.build_model((X_train.shape[1],), np.unique(y_train).size) 

222 

223 # model summary 

224 stringlist = [] 

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

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

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

228 

229 # get optimizer 

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

231 opt_class = getattr(mod, self.optimizer) 

232 opt = opt_class(lr=self.learning_rate) 

233 # compile model 

234 model.compile(optimizer=opt, loss='sparse_categorical_crossentropy', metrics=['accuracy', 'mse']) 

235 

236 # fitting 

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

238 # set an early stopping mechanism 

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

240 early_stopping = EarlyStopping(patience=2) 

241 

242 if self.weight: 

243 sample_weight = w_train 

244 class_weight = [] 

245 else: 

246 # TODO: class_weight not working since TF 2.4.1 update 

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

248 fu.log('No weight provided', self.out_log, self.global_log) 

249 sample_weight = None 

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

251 

252 print(class_weight) 

253 # fit the model 

254 mf = model.fit(X_train, 

255 y_train, 

256 class_weight=class_weight, 

257 sample_weight=sample_weight, 

258 batch_size=self.batch_size, 

259 epochs=self.max_epochs, 

260 callbacks=[early_stopping], 

261 validation_split=self.validation_size, 

262 verbose=1) 

263 

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

265 

266 train_metrics = pd.DataFrame() 

267 train_metrics['metric'] = ['Train loss', ' Train accuracy', 'Train MSE', 'Validation loss', 'Validation accuracy', 'Validation MSE'] 

268 train_metrics['coefficient'] = [mf.history['loss'][-1], mf.history['accuracy'][-1], mf.history['mse'][-1], mf.history['val_loss'][-1], mf.history['val_accuracy'][-1], mf.history['val_mse'][-1]] 

269 

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

271 

272 # confusion matrix 

273 train_predictions = model.predict(X_train) 

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

275 norm_pred = [] 

276 [norm_pred.append(np.argmax(pred, axis=0)) for pred in train_predictions] 

277 cnf_matrix_train = math.confusion_matrix(y_train, norm_pred).numpy() 

278 np.set_printoptions(precision=2) 

279 if self.normalize_cm: 

280 cnf_matrix_train = cnf_matrix_train.astype('float') / cnf_matrix_train.sum(axis=1)[:, np.newaxis] 

281 cm_type = 'NORMALIZED CONFUSION MATRIX' 

282 else: 

283 cm_type = 'CONFUSION MATRIX, WITHOUT NORMALIZATION' 

284 

285 fu.log('Calculating confusion matrix for training dataset\n\n%s\n\n%s\n' % (cm_type, cnf_matrix_train), self.out_log, self.global_log) 

286 

287 # testing 

288 if self.scale: 

289 X_test = scale(X_test) 

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

291 test_loss, test_accuracy, test_mse = model.evaluate(X_test, y_test) 

292 

293 test_metrics = pd.DataFrame() 

294 test_metrics['metric'] = ['Test loss', ' Test accuracy', 'Test MSE'] 

295 test_metrics['coefficient'] = [test_loss, test_accuracy, test_mse] 

296 

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

298 

299 # predict data from X_test 

300 test_predictions = model.predict(X_test) 

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

302 tpr = tuple(map(tuple, test_predictions)) 

303 

304 test_table = pd.DataFrame() 

305 test_table['P' + np.array2string(np.unique(y_train))] = tpr 

306 test_table['target'] = y_test 

307 

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

309 

310 # confusion matrix 

311 norm_pred = [] 

312 [norm_pred.append(np.argmax(pred, axis=0)) for pred in test_predictions] 

313 cnf_matrix_test = math.confusion_matrix(y_test, norm_pred).numpy() 

314 np.set_printoptions(precision=2) 

315 if self.normalize_cm: 

316 cnf_matrix_test = cnf_matrix_test.astype('float') / cnf_matrix_test.sum(axis=1)[:, np.newaxis] 

317 cm_type = 'NORMALIZED CONFUSION MATRIX' 

318 else: 

319 cm_type = 'CONFUSION MATRIX, WITHOUT NORMALIZATION' 

320 

321 fu.log('Calculating confusion matrix for testing dataset\n\n%s\n\n%s\n' % (cm_type, cnf_matrix_test), self.out_log, self.global_log) 

322 

323 # save test data 

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

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

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

327 

328 # create test plot 

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

330 vs = np.unique(targets_list) 

331 vs.sort() 

332 if len(vs) > 2: 

333 plot = plotResultsClassMultCM(mf.history, cnf_matrix_train, cnf_matrix_test, self.normalize_cm, vs) 

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

335 else: 

336 plot = plotResultsClassBinCM(mf.history, train_predictions, test_predictions, y_train, y_test, cnf_matrix_train, cnf_matrix_test, self.normalize_cm, vs) 

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

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

339 

340 # save model and parameters 

341 vs = np.unique(targets_list) 

342 vs.sort() 

343 vars_obj = { 

344 'features': self.features, 

345 'target': self.target, 

346 'scale': self.scale, 

347 'vs': vs.tolist(), 

348 'type': 'classification' 

349 } 

350 variables = json.dumps(vars_obj) 

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

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

353 hdf5_format.save_model_to_hdf5(model, f) 

354 f.attrs['variables'] = variables 

355 

356 # Copy files to host 

357 self.copy_to_host() 

358 

359 self.tmp_files.extend([ 

360 self.stage_io_dict.get("unique_dir") 

361 ]) 

362 self.remove_tmp_files() 

363 

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

365 

366 return 0 

367 

368 

369def classification_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: 

370 """Execute the :class:`AutoencoderNeuralNetwork <neural_networks.classification_neural_network.AutoencoderNeuralNetwork>` class and 

371 execute the :meth:`launch() <neural_networks.classification_neural_network.AutoencoderNeuralNetwork.launch>` method.""" 

372 

373 return ClassificationNeuralNetwork(input_dataset_path=input_dataset_path, 

374 output_model_path=output_model_path, 

375 output_test_table_path=output_test_table_path, 

376 output_plot_path=output_plot_path, 

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

378 

379 

380def main(): 

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

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

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

384 

385 # Specific args of each building block 

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

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

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

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

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

391 

392 args = parser.parse_args() 

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

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

395 

396 # Specific call of each building block 

397 classification_neural_network(input_dataset_path=args.input_dataset_path, 

398 output_model_path=args.output_model_path, 

399 output_test_table_path=args.output_test_table_path, 

400 output_plot_path=args.output_plot_path, 

401 properties=properties) 

402 

403 

404if __name__ == '__main__': 

405 main()