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

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

41 Examples: 

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

43 

44 from biobb_ml.regression.linear_regression import linear_regression 

45 prop = { 

46 'independent_vars': { 

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

48 }, 

49 'target': { 

50 'column': 'target' 

51 }, 

52 'test_size': 0.2 

53 } 

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

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

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

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

58 properties=prop) 

59 

60 Info: 

61 * wrapped_software: 

62 * name: scikit-learn LinearRegression 

63 * version: >=0.24.2 

64 * license: BSD 3-Clause 

65 * ontology: 

66 * name: EDAM 

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

68 

69 """ 

70 

71 def __init__(self, input_dataset_path, output_model_path, 

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

73 properties = properties or {} 

74 

75 # Call parent class constructor 

76 super().__init__(properties) 

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

78 

79 # Input/Output files 

80 self.io_dict = { 

81 "in": {"input_dataset_path": input_dataset_path}, 

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

83 } 

84 

85 # Properties specific for BB 

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

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

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

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

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

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

92 self.properties = properties 

93 

94 # Check the properties 

95 self.check_properties(properties) 

96 self.check_arguments() 

97 

98 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

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

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

106 

107 @launchlogger 

108 def launch(self) -> int: 

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

110 

111 # check input/output paths and parameters 

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

113 

114 # Setup Biobb 

115 if self.check_restart(): 

116 return 0 

117 self.stage_files() 

118 

119 # load dataset 

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

121 if 'columns' in self.independent_vars: 

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

123 skiprows = 1 

124 else: 

125 labels = None 

126 skiprows = None 

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

128 

129 # declare inputs, targets and weights 

130 # the inputs are all the independent variables 

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

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

133 # target 

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

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

136 # weights 

137 if self.weight: 

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

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

140 

141 # train / test split 

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

143 arrays_sets = (X, y) 

144 # if user provide weights 

145 if self.weight: 

146 arrays_sets = arrays_sets + (w,) 

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

148 else: 

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

150 

151 # scale dataset 

152 if self.scale: 

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

154 scaler = StandardScaler() 

155 X_train = scaler.fit_transform(X_train) 

156 

157 # regression 

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

159 model = linear_model.LinearRegression() 

160 arrays_fit = (X_train, y_train) 

161 # if user provide weights 

162 if self.weight: 

163 arrays_fit = arrays_fit + (w_train,) 

164 

165 model.fit(*arrays_fit) 

166 

167 # scores and coefficients train 

168 y_hat_train = model.predict(X_train) 

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

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

171 score = r2_score(y_hat_train, y_train) 

172 bias = model.intercept_ 

173 coef = model.coef_ 

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

175 adj_r2 = adjusted_r2(X_train, y_train, score) 

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

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

178 

179 # r-squared 

180 r2_table = pd.DataFrame() 

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

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

183 

184 # p-values 

185 cols = ['bias'] 

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

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

188 c = [round(bias, 3)] 

189 c.extend(coef) 

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

191 coefs_table['coefficient'] = c 

192 p = [0] 

193 p.extend(p_values) 

194 

195 coefs_table['p-value'] = p 

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

197 

198 # testing 

199 # predict data from x_test 

200 if self.scale: 

201 X_test = scaler.transform(X_test) 

202 y_hat_test = model.predict(X_test) 

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

204 # reset y_test (problem with old indexes column) 

205 y_test = y_test.reset_index(drop=True) 

206 # add real values to predicted ones in test_table table 

207 test_table['target'] = y_test 

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

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

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

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

212 # sort by difference in % 

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

214 test_table = test_table.reset_index(drop=True) 

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

216 

217 # scores and coefficients test 

218 r2_test = r2_score(y_hat_test, y_test) 

219 adj_r2_test = adjusted_r2(X_test, y_test, r2_test) 

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

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

222 

223 # r-squared 

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

225 r2_table_test = pd.DataFrame() 

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

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

228 

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

230 

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

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

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

234 

235 # create test plot 

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

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

238 y_hat_test = y_hat_test.flatten() 

239 y_hat_train = y_hat_train.flatten() 

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

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

242 

243 # save model, scaler and parameters 

244 variables = { 

245 'target': self.target, 

246 'independent_vars': self.independent_vars, 

247 'scale': self.scale 

248 } 

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

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

251 joblib.dump(model, f) 

252 if self.scale: 

253 joblib.dump(scaler, f) 

254 joblib.dump(variables, f) 

255 

256 # Copy files to host 

257 self.copy_to_host() 

258 

259 self.tmp_files.extend([ 

260 self.stage_io_dict.get("unique_dir") 

261 ]) 

262 self.remove_tmp_files() 

263 

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

265 

266 return 0 

267 

268 

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

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

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

272 

273 return LinearRegression(input_dataset_path=input_dataset_path, 

274 output_model_path=output_model_path, 

275 output_test_table_path=output_test_table_path, 

276 output_plot_path=output_plot_path, 

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

278 

279 

280def main(): 

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

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

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

284 

285 # Specific args of each building block 

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

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

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

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

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

291 

292 args = parser.parse_args() 

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

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

295 

296 # Specific call of each building block 

297 linear_regression(input_dataset_path=args.input_dataset_path, 

298 output_model_path=args.output_model_path, 

299 output_test_table_path=args.output_test_table_path, 

300 output_plot_path=args.output_plot_path, 

301 properties=properties) 

302 

303 

304if __name__ == '__main__': 

305 main()