Coverage for biobb_ml/classification/logistic_regression.py: 83%

151 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 LogisticRegression class and the command line interface.""" 

4import argparse 

5import joblib 

6import pandas as pd 

7import numpy as np 

8from biobb_common.generic.biobb_object import BiobbObject 

9from sklearn.preprocessing import StandardScaler 

10from sklearn.model_selection import train_test_split 

11from sklearn.metrics import confusion_matrix, classification_report, log_loss 

12from sklearn import linear_model 

13from biobb_common.configuration import settings 

14from biobb_common.tools import file_utils as fu 

15from biobb_common.tools.file_utils import launchlogger 

16from biobb_ml.classification.common import check_input_path, check_output_path, getHeader, getIndependentVars, getIndependentVarsList, getTarget, getTargetValue, getWeight, plotMultipleCM, plotBinaryClassifier 

17 

18 

19class LogisticRegression(BiobbObject): 

20 """ 

21 | biobb_ml LogisticRegression 

22 | Wrapper of the scikit-learn LogisticRegression method. 

23 | Trains and tests a given dataset and saves the model and scaler. Visit the `LogisticRegression documentation page <https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html>`_ in the sklearn official website for further information. 

24 

25 Args: 

26 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/classification/dataset_logistic_regression.csv>`_. Accepted formats: csv (edam:format_3752). 

27 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/classification/ref_output_model_logistic_regression.pkl>`_. Accepted formats: pkl (edam:format_3653). 

28 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/classification/ref_output_test_logistic_regression.csv>`_. Accepted formats: csv (edam:format_3752). 

29 output_plot_path (str) (Optional): Path to the statistics plot. If target is binary it shows confusion matrix, distributions of the predicted probabilities of both classes and ROC curve. If target is non-binary it shows confusion matrix. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/classification/ref_output_plot_logistic_regression.png>`_. Accepted formats: png (edam:format_3603). 

30 properties (dic - Python dictionary object containing the tool parameters, not input/output files): 

31 * **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. 

32 * **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. 

33 * **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. 

34 * **solver** (*string*) - ("liblinear") Numerical optimizer to find parameters. Values: newton-cg (Recall the motivation for gradient descent step at x: we minimize the quadratic function), lbfgs (It's analogue of the Newton's Method but here the Hessian matrix is approximated using updates specified by gradient evaluations), liblinear (It's a linear classification that supports logistic regression and linear support vector machines), sag (SAG method optimizes the sum of a finite number of smooth convex functions), saga (It's a variant of SAG that also supports the non-smooth penalty=l1 option). 

35 * **c_parameter** (*float*) - (0.01) [0~100|0.01] Inverse of regularization strength; must be a positive float. Smaller values specify stronger regularization. 

36 * **normalize_cm** (*bool*) - (False) Whether or not to normalize the confusion matrix. 

37 * **random_state_method** (*int*) - (5) [1~1000|1] Controls the randomness of the estimator. 

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

39 * **test_size** (*float*) - (0.2) [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 * **scale** (*bool*) - (False) Whether or not to scale the input dataset. 

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

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

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

44 

45 Examples: 

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

47 

48 from biobb_ml.classification.logistic_regression import logistic_regression 

49 prop = { 

50 'independent_vars': { 

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

52 }, 

53 'target': { 

54 'column': 'target' 

55 }, 

56 'solver': 'liblinear', 

57 'c_parameter': 0.01, 

58 'test_size': 0.2 

59 } 

60 logistic_regression(input_dataset_path='/path/to/myDataset.csv', 

61 output_model_path='/path/to/newModel.pkl', 

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

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

64 properties=prop) 

65 

66 Info: 

67 * wrapped_software: 

68 * name: scikit-learn LogisticRegression 

69 * version: >=0.24.2 

70 * license: BSD 3-Clause 

71 * ontology: 

72 * name: EDAM 

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

74 

75 """ 

76 

77 def __init__(self, input_dataset_path, output_model_path, 

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

79 properties = properties or {} 

80 

81 # Call parent class constructor 

82 super().__init__(properties) 

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

84 

85 # Input/Output files 

86 self.io_dict = { 

87 "in": {"input_dataset_path": input_dataset_path}, 

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

89 } 

90 

91 # Properties specific for BB 

92 self.independent_vars = properties.get('independent_vars', {}) 

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

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

95 self.solver = properties.get('solver', 'liblinear') 

96 self.c_parameter = properties.get('c_parameter', 0.01) 

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

98 self.random_state_method = properties.get('random_state_method', 5) 

99 self.random_state_train_test = properties.get('random_state_train_test', 5) 

100 self.test_size = properties.get('test_size', 0.2) 

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

102 self.properties = properties 

103 

104 # Check the properties 

105 self.check_properties(properties) 

106 self.check_arguments() 

107 

108 def check_data_params(self, out_log, err_log): 

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

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

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

112 if self.io_dict["out"]["output_test_table_path"]: 

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

114 if self.io_dict["out"]["output_plot_path"]: 

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

116 

117 @launchlogger 

118 def launch(self) -> int: 

119 """Execute the :class:`LogisticRegression <classification.logistic_regression.LogisticRegression>` classification.logistic_regression.LogisticRegression object.""" 

120 

121 # check input/output paths and parameters 

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

123 

124 # Setup Biobb 

125 if self.check_restart(): 

126 return 0 

127 self.stage_files() 

128 

129 # load dataset 

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

131 if 'columns' in self.independent_vars: 

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

133 skiprows = 1 

134 else: 

135 labels = None 

136 skiprows = None 

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

138 

139 # declare inputs, targets and weights 

140 # the inputs are all the independent variables 

141 X = getIndependentVars(self.independent_vars, data, self.out_log, self.__class__.__name__) 

142 fu.log('Independent variables: [%s]' % (getIndependentVarsList(self.independent_vars)), self.out_log, self.global_log) 

143 # target 

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

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

146 # weights 

147 if self.weight: 

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

149 fu.log('Weight column provided', self.out_log, self.global_log) 

150 

151 # train / test split 

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

153 arrays_sets = (X, y) 

154 # if user provide weights 

155 if self.weight: 

156 arrays_sets = arrays_sets + (w,) 

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

158 else: 

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

160 

161 # scale dataset 

162 if self.scale: 

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

164 scaler = StandardScaler() 

165 X_train = scaler.fit_transform(X_train) 

166 

167 # classification 

168 fu.log('Training dataset applying logistic regression', self.out_log, self.global_log) 

169 model = linear_model.LogisticRegression(C=self.c_parameter, solver=self.solver, random_state=self.random_state_method) 

170 

171 arrays_fit = (X_train, y_train) 

172 # if user provide weights 

173 if self.weight: 

174 arrays_fit = arrays_fit + (w_train,) 

175 

176 model.fit(*arrays_fit) 

177 

178 y_hat_train = model.predict(X_train) 

179 # classification report 

180 cr_train = classification_report(y_train, y_hat_train) 

181 # log loss 

182 yhat_prob_train = model.predict_proba(X_train) 

183 l_loss_train = log_loss(y_train, yhat_prob_train) 

184 fu.log('Calculating scores and report for training dataset\n\nCLASSIFICATION REPORT\n\n%s\nLog loss: %.3f\n' % (cr_train, l_loss_train), self.out_log, self.global_log) 

185 

186 # compute confusion matrix 

187 cnf_matrix_train = confusion_matrix(y_train, y_hat_train) 

188 np.set_printoptions(precision=2) 

189 if self.normalize_cm: 

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

191 cm_type = 'NORMALIZED CONFUSION MATRIX' 

192 else: 

193 cm_type = 'CONFUSION MATRIX, WITHOUT NORMALIZATION' 

194 

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

196 

197 # testing 

198 # predict data from x_test 

199 if self.scale: 

200 X_test = scaler.transform(X_test) 

201 y_hat_test = model.predict(X_test) 

202 test_table = pd.DataFrame() 

203 y_hat_prob = model.predict_proba(X_test) 

204 y_hat_prob = np.around(y_hat_prob, decimals=2) 

205 y_hat_prob = tuple(map(tuple, y_hat_prob)) 

206 test_table['P' + np.array2string(np.unique(y_test))] = y_hat_prob 

207 y_test = y_test.reset_index(drop=True) 

208 test_table['target'] = y_test 

209 

210 fu.log('Testing\n\nTEST DATA\n\n%s\n' % test_table, self.out_log, self.global_log) 

211 

212 # classification report 

213 cr = classification_report(y_test, y_hat_test) 

214 # log loss 

215 yhat_prob = model.predict_proba(X_test) 

216 l_loss = log_loss(y_test, yhat_prob) 

217 fu.log('Calculating scores and report for testing dataset\n\nCLASSIFICATION REPORT\n\n%s\nLog loss: %.3f\n' % (cr, l_loss), self.out_log, self.global_log) 

218 

219 # compute confusion matrix 

220 cnf_matrix = confusion_matrix(y_test, y_hat_test) 

221 np.set_printoptions(precision=2) 

222 if self.normalize_cm: 

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

224 cm_type = 'NORMALIZED CONFUSION MATRIX' 

225 else: 

226 cm_type = 'CONFUSION MATRIX, WITHOUT NORMALIZATION' 

227 

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

229 

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

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

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

233 

234 # plot 

235 if self.io_dict["out"]["output_plot_path"]: 

236 vs = y.unique().tolist() 

237 vs.sort() 

238 if len(vs) > 2: 

239 plot = plotMultipleCM(cnf_matrix_train, cnf_matrix, self.normalize_cm, vs) 

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

241 else: 

242 plot = plotBinaryClassifier(model, yhat_prob_train, yhat_prob, cnf_matrix_train, cnf_matrix, y_train, y_test, normalize=self.normalize_cm) 

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

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

245 

246 # save model, scaler and parameters 

247 tv = y.unique().tolist() 

248 tv.sort() 

249 variables = { 

250 'target': self.target, 

251 'independent_vars': self.independent_vars, 

252 'scale': self.scale, 

253 'target_values': tv 

254 } 

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

256 with open(self.io_dict["out"]["output_model_path"], "wb") as f: 

257 joblib.dump(model, f) 

258 if self.scale: 

259 joblib.dump(scaler, f) 

260 joblib.dump(variables, f) 

261 

262 # Copy files to host 

263 self.copy_to_host() 

264 

265 self.tmp_files.extend([ 

266 self.stage_io_dict.get("unique_dir") 

267 ]) 

268 self.remove_tmp_files() 

269 

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

271 

272 return 0 

273 

274 

275def logistic_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: 

276 """Execute the :class:`LogisticRegression <classification.logistic_regression.LogisticRegression>` class and 

277 execute the :meth:`launch() <classification.logistic_regression.LogisticRegression.launch>` method.""" 

278 

279 return LogisticRegression(input_dataset_path=input_dataset_path, 

280 output_model_path=output_model_path, 

281 output_test_table_path=output_test_table_path, 

282 output_plot_path=output_plot_path, 

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

284 

285 

286def main(): 

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

288 parser = argparse.ArgumentParser(description="Wrapper of the scikit-learn LogisticRegression method.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

290 

291 # Specific args of each building block 

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

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

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

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

296 parser.add_argument('--output_plot_path', required=False, help='Path to the statistics plot. If target is binary it shows confusion matrix, distributions of the predicted probabilities of both classes and ROC curve. If target is non-binary it shows confusion matrix. Accepted formats: png.') 

297 

298 args = parser.parse_args() 

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

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

301 

302 # Specific call of each building block 

303 logistic_regression(input_dataset_path=args.input_dataset_path, 

304 output_model_path=args.output_model_path, 

305 output_test_table_path=args.output_test_table_path, 

306 output_plot_path=args.output_plot_path, 

307 properties=properties) 

308 

309 

310if __name__ == '__main__': 

311 main()