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

193 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 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 

52 Examples: 

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

54 

55 from biobb_ml.neural_networks.classification_neural_network import classification_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 classification_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) 

85 

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 

94 

95 """ 

96 

97 def __init__(self, input_dataset_path, output_model_path, 

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

99 properties = properties or {} 

100 

101 # Call parent class constructor 

102 super().__init__(properties) 

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

104 

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 } 

110 

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.normalize_cm = properties.get('normalize_cm', False) 

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

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

126 self.properties = properties 

127 

128 # Check the properties 

129 self.check_properties(properties) 

130 self.check_arguments() 

131 

132 def check_data_params(self, out_log, err_log): 

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

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

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

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

137 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 

139 def build_model(self, input_shape, output_size): 

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

141 

142 # create model 

143 model = Sequential([]) 

144 

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

146 if not self.hidden_layers: 

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

148 

149 # generate hidden_layers 

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

151 if i == 0: 

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

153 else: 

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

155 

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

157 

158 return model 

159 

160 @launchlogger 

161 def launch(self) -> int: 

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

163 

164 # check input/output paths and parameters 

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

166 

167 # Setup Biobb 

168 if self.check_restart(): 

169 return 0 

170 self.stage_files() 

171 

172 # load dataset 

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

174 if 'columns' in self.features: 

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

176 skiprows = 1 

177 else: 

178 labels = None 

179 skiprows = None 

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

181 

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

183 

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

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

186 # target 

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

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

189 # weights 

190 if self.weight: 

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

192 

193 # shuffle dataset 

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

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

196 np.random.shuffle(shuffled_indices) 

197 np_X = X.to_numpy() 

198 shuffled_X = np_X[shuffled_indices] 

199 shuffled_y = targets_list[shuffled_indices] 

200 if self.weight: 

201 shuffled_w = w[shuffled_indices] 

202 

203 # train / test split 

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

205 arrays_sets = (shuffled_X, shuffled_y) 

206 # if user provide weights 

207 if self.weight: 

208 arrays_sets = arrays_sets + (shuffled_w,) 

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

210 else: 

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

212 

213 # scale dataset 

214 if self.scale: 

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

216 X_train = scale(X_train) 

217 

218 # build model 

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

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

221 

222 # model summary 

223 stringlist = [] 

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

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

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

227 

228 # get optimizer 

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

230 opt_class = getattr(mod, self.optimizer) 

231 opt = opt_class(lr=self.learning_rate) 

232 # compile model 

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

234 

235 # fitting 

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

237 # set an early stopping mechanism 

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

239 early_stopping = EarlyStopping(patience=2) 

240 

241 if self.weight: 

242 sample_weight = w_train 

243 class_weight = [] 

244 else: 

245 # TODO: class_weight not working since TF 2.4.1 update 

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

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

248 sample_weight = None 

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

250 

251 print(class_weight) 

252 # fit the model 

253 mf = model.fit(X_train, 

254 y_train, 

255 class_weight=class_weight, 

256 sample_weight=sample_weight, 

257 batch_size=self.batch_size, 

258 epochs=self.max_epochs, 

259 callbacks=[early_stopping], 

260 validation_split=self.validation_size, 

261 verbose=1) 

262 

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

264 

265 train_metrics = pd.DataFrame() 

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

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

268 

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

270 

271 # confusion matrix 

272 train_predictions = model.predict(X_train) 

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

274 norm_pred = [] 

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

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

277 np.set_printoptions(precision=2) 

278 if self.normalize_cm: 

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

280 cm_type = 'NORMALIZED CONFUSION MATRIX' 

281 else: 

282 cm_type = 'CONFUSION MATRIX, WITHOUT NORMALIZATION' 

283 

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

285 

286 # testing 

287 if self.scale: 

288 X_test = scale(X_test) 

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

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

291 

292 test_metrics = pd.DataFrame() 

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

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

295 

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

297 

298 # predict data from X_test 

299 test_predictions = model.predict(X_test) 

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

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

302 

303 test_table = pd.DataFrame() 

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

305 test_table['target'] = y_test 

306 

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

308 

309 # confusion matrix 

310 norm_pred = [] 

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

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

313 np.set_printoptions(precision=2) 

314 if self.normalize_cm: 

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

316 cm_type = 'NORMALIZED CONFUSION MATRIX' 

317 else: 

318 cm_type = 'CONFUSION MATRIX, WITHOUT NORMALIZATION' 

319 

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

321 

322 # save test data 

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

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

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

326 

327 # create test plot 

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

329 vs = np.unique(targets_list) 

330 vs.sort() 

331 if len(vs) > 2: 

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

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

334 else: 

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

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

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

338 

339 # save model and parameters 

340 vs = np.unique(targets_list) 

341 vs.sort() 

342 vars_obj = { 

343 'features': self.features, 

344 'target': self.target, 

345 'scale': self.scale, 

346 'vs': vs.tolist(), 

347 'type': 'classification' 

348 } 

349 variables = json.dumps(vars_obj) 

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

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

352 hdf5_format.save_model_to_hdf5(model, f) 

353 f.attrs['variables'] = variables 

354 

355 # Copy files to host 

356 self.copy_to_host() 

357 

358 self.tmp_files.extend([ 

359 self.stage_io_dict.get("unique_dir") 

360 ]) 

361 self.remove_tmp_files() 

362 

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

364 

365 return 0 

366 

367 

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

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

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

371 

372 return ClassificationNeuralNetwork(input_dataset_path=input_dataset_path, 

373 output_model_path=output_model_path, 

374 output_test_table_path=output_test_table_path, 

375 output_plot_path=output_plot_path, 

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

377 

378 

379def main(): 

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

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

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

383 

384 # Specific args of each building block 

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

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

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

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

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

390 

391 args = parser.parse_args() 

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

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

394 

395 # Specific call of each building block 

396 classification_neural_network(input_dataset_path=args.input_dataset_path, 

397 output_model_path=args.output_model_path, 

398 output_test_table_path=args.output_test_table_path, 

399 output_plot_path=args.output_plot_path, 

400 properties=properties) 

401 

402 

403if __name__ == '__main__': 

404 main()