Coverage for biobb_ml/regression/linear_regression.py: 87%

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

4import argparse 

5import numpy as np 

6import pandas as pd 

7import joblib 

8from biobb_common.generic.biobb_object import BiobbObject 

9from sklearn.preprocessing import StandardScaler 

10from sklearn.model_selection import train_test_split 

11from sklearn.feature_selection import f_regression 

12from sklearn.metrics import mean_squared_error, r2_score 

13from sklearn import linear_model 

14from biobb_common.configuration import settings 

15from biobb_common.tools import file_utils as fu 

16from biobb_common.tools.file_utils import launchlogger 

17from biobb_ml.regression.common import check_input_path, check_output_path, getHeader, getIndependentVars, getIndependentVarsList, getTarget, getTargetValue, getWeight, adjusted_r2, plotResults 

18 

19 

20class LinearRegression(BiobbObject): 

21 """ 

22 | biobb_ml LinearRegression 

23 | Wrapper of the scikit-learn LinearRegression method. 

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

25 

26 Args: 

27 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/regression/dataset_linear_regression.csv>`_. Accepted formats: csv (edam:format_3752). 

28 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/regression/ref_output_model_linear_regression.pkl>`_. Accepted formats: pkl (edam:format_3653). 

29 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/regression/ref_output_test_linear_regression.csv>`_. Accepted formats: csv (edam:format_3752). 

30 output_plot_path (str) (Optional): Residual plot checks the error between actual values and predicted values. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/regression/ref_output_plot_linear_regression.png>`_. Accepted formats: png (edam:format_3603). 

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

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

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

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

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

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

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

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

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

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

41 

42 Examples: 

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

44 

45 from biobb_ml.regression.linear_regression import linear_regression 

46 prop = { 

47 'independent_vars': { 

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

49 }, 

50 'target': { 

51 'column': 'target' 

52 }, 

53 'test_size': 0.2 

54 } 

55 linear_regression(input_dataset_path='/path/to/myDataset.csv', 

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

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

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

59 properties=prop) 

60 

61 Info: 

62 * wrapped_software: 

63 * name: scikit-learn LinearRegression 

64 * version: >=0.24.2 

65 * license: BSD 3-Clause 

66 * ontology: 

67 * name: EDAM 

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

69 

70 """ 

71 

72 def __init__(self, input_dataset_path, output_model_path, 

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

74 properties = properties or {} 

75 

76 # Call parent class constructor 

77 super().__init__(properties) 

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

79 

80 # Input/Output files 

81 self.io_dict = { 

82 "in": {"input_dataset_path": input_dataset_path}, 

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

84 } 

85 

86 # Properties specific for BB 

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

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

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

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

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

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

93 self.properties = properties 

94 

95 # Check the properties 

96 self.check_properties(properties) 

97 self.check_arguments() 

98 

99 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

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

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

107 

108 @launchlogger 

109 def launch(self) -> int: 

110 """Execute the :class:`LinearRegression <regression.linear_regression.LinearRegression>` regression.linear_regression.LinearRegression object.""" 

111 

112 # check input/output paths and parameters 

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

114 

115 # Setup Biobb 

116 if self.check_restart(): 

117 return 0 

118 self.stage_files() 

119 

120 # load dataset 

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

122 if 'columns' in self.independent_vars: 

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

124 skiprows = 1 

125 else: 

126 labels = None 

127 skiprows = None 

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

129 

130 # declare inputs, targets and weights 

131 # the inputs are all the independent variables 

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

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

134 # target 

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

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

137 # weights 

138 if self.weight: 

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

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

141 

142 # train / test split 

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

144 arrays_sets = (X, y) 

145 # if user provide weights 

146 if self.weight: 

147 arrays_sets = arrays_sets + (w,) 

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

149 else: 

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

151 

152 # scale dataset 

153 if self.scale: 

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

155 scaler = StandardScaler() 

156 X_train = scaler.fit_transform(X_train) 

157 

158 # regression 

159 fu.log('Training dataset applying linear regression', self.out_log, self.global_log) 

160 model = linear_model.LinearRegression() 

161 arrays_fit = (X_train, y_train) 

162 # if user provide weights 

163 if self.weight: 

164 arrays_fit = arrays_fit + (w_train,) 

165 

166 model.fit(*arrays_fit) 

167 

168 # scores and coefficients train 

169 y_hat_train = model.predict(X_train) 

170 rmse = (np.sqrt(mean_squared_error(y_train, y_hat_train))) 

171 rss = ((y_train - y_hat_train) ** 2).sum() 

172 score = r2_score(y_hat_train, y_train) 

173 bias = model.intercept_ 

174 coef = model.coef_ 

175 coef = ['%.3f' % item for item in coef] 

176 adj_r2 = adjusted_r2(X_train, y_train, score) 

177 p_values = f_regression(X_train, y_train)[1] 

178 p_values = ['%.3f' % item for item in p_values] 

179 

180 # r-squared 

181 r2_table = pd.DataFrame() 

182 r2_table["feature"] = ['R2', 'Adj. R2', 'RMSE', 'RSS'] 

183 r2_table['coefficient'] = [score, adj_r2, rmse, rss] 

184 

185 # p-values 

186 cols = ['bias'] 

187 cols.extend(list(getIndependentVarsList(self.independent_vars).split(", "))) 

188 coefs_table = pd.DataFrame(cols, columns=['feature']) 

189 c = [round(bias, 3)] 

190 c.extend(coef) 

191 c = list(map(float, c)) 

192 coefs_table['coefficient'] = c 

193 p = [0] 

194 p.extend(p_values) 

195 

196 coefs_table['p-value'] = p 

197 fu.log('Calculating scores and coefficients for training dataset\n\nR2, ADJUSTED R2 & RMSE\n\n%s\n\nCOEFFS & P-VALUES\n\n%s\n' % (r2_table, coefs_table), self.out_log, self.global_log) 

198 

199 # testing 

200 # predict data from x_test 

201 if self.scale: 

202 X_test = scaler.transform(X_test) 

203 y_hat_test = model.predict(X_test) 

204 test_table = pd.DataFrame(y_hat_test, columns=['prediction']) 

205 # reset y_test (problem with old indexes column) 

206 y_test = y_test.reset_index(drop=True) 

207 # add real values to predicted ones in test_table table 

208 test_table['target'] = y_test 

209 # calculate difference between target and prediction (absolute and %) 

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

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

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

213 # sort by difference in % 

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

215 test_table = test_table.reset_index(drop=True) 

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

217 

218 # scores and coefficients test 

219 r2_test = r2_score(y_hat_test, y_test) 

220 adj_r2_test = adjusted_r2(X_test, y_test, r2_test) 

221 rmse_test = np.sqrt(mean_squared_error(y_test, y_hat_test)) 

222 rss_test = ((y_test - y_hat_test) ** 2).sum() 

223 

224 # r-squared 

225 pd.set_option('display.float_format', lambda x: '%.6f' % x) 

226 r2_table_test = pd.DataFrame() 

227 r2_table_test["feature"] = ['R2', 'Adj. R2', 'RMSE', 'RSS'] 

228 r2_table_test['coefficient'] = [r2_test, adj_r2_test, rmse_test, rss_test] 

229 

230 fu.log('Calculating scores and coefficients for testing dataset\n\nR2, ADJUSTED R2 & RMSE\n\n%s\n' % r2_table_test, self.out_log, self.global_log) 

231 

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

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

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

235 

236 # create test plot 

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

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

239 y_hat_test = y_hat_test.flatten() 

240 y_hat_train = y_hat_train.flatten() 

241 plot = plotResults(y_train, y_hat_train, y_test, y_hat_test) 

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

243 

244 # save model, scaler and parameters 

245 variables = { 

246 'target': self.target, 

247 'independent_vars': self.independent_vars, 

248 'scale': self.scale 

249 } 

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

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

252 joblib.dump(model, f) 

253 if self.scale: 

254 joblib.dump(scaler, f) 

255 joblib.dump(variables, f) 

256 

257 # Copy files to host 

258 self.copy_to_host() 

259 

260 self.tmp_files.extend([ 

261 self.stage_io_dict.get("unique_dir") 

262 ]) 

263 self.remove_tmp_files() 

264 

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

266 

267 return 0 

268 

269 

270def linear_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: 

271 """Execute the :class:`LinearRegression <regression.linear_regression.LinearRegression>` class and 

272 execute the :meth:`launch() <regression.linear_regression.LinearRegression.launch>` method.""" 

273 

274 return LinearRegression(input_dataset_path=input_dataset_path, 

275 output_model_path=output_model_path, 

276 output_test_table_path=output_test_table_path, 

277 output_plot_path=output_plot_path, 

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

279 

280 

281def main(): 

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

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

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

285 

286 # Specific args of each building block 

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

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

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

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

291 parser.add_argument('--output_plot_path', required=False, help='Residual plot checks the error between actual values and predicted values. Accepted formats: png.') 

292 

293 args = parser.parse_args() 

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

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

296 

297 # Specific call of each building block 

298 linear_regression(input_dataset_path=args.input_dataset_path, 

299 output_model_path=args.output_model_path, 

300 output_test_table_path=args.output_test_table_path, 

301 output_plot_path=args.output_plot_path, 

302 properties=properties) 

303 

304 

305if __name__ == '__main__': 

306 main()