Coverage for biobb_ml/regression/regression_predict.py: 75%

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

4import argparse 

5import pandas as pd 

6import joblib 

7from biobb_common.generic.biobb_object import BiobbObject 

8from sklearn.preprocessing import StandardScaler, PolynomialFeatures 

9from sklearn import linear_model 

10from sklearn import ensemble 

11from biobb_common.configuration import settings 

12from biobb_common.tools import file_utils as fu 

13from biobb_common.tools.file_utils import launchlogger 

14from biobb_ml.regression.common import check_input_path, check_output_path, getHeader, get_list_of_predictors, get_keys_of_predictors 

15 

16 

17class RegressionPredict(BiobbObject): 

18 """ 

19 | biobb_ml RegressionPredict 

20 | Makes predictions from an input dataset and a given regression model. 

21 | Makes predictions from an input dataset (provided either as a file or as a dictionary property) and a given regression model trained with `LinearRegression <https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html>`_, `RandomForestRegressor <https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html>`_ methods. 

22 

23 Args: 

24 input_model_path (str): Path to the input model. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/regression/model_regression_predict.pkl>`_. Accepted formats: pkl (edam:format_3653). 

25 input_dataset_path (str) (Optional): Path to the dataset to predict. File type: input. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/data/regression/input_regression_predict.csv>`_. Accepted formats: csv (edam:format_3752). 

26 output_results_path (str): Path to the output results file. File type: output. `Sample file <https://github.com/bioexcel/biobb_ml/raw/master/biobb_ml/test/reference/regression/ref_output_regression_predict.csv>`_. Accepted formats: csv (edam:format_3752). 

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

28 * **predictions** (*list*) - (None) List of dictionaries with all values you want to predict targets. It will be taken into account only in case **input_dataset_path** is not provided. Format: [{ 'var1': 1.0, 'var2': 2.0 }, { 'var1': 4.0, 'var2': 2.7 }] for datasets with headers and [[ 1.0, 2.0 ], [ 4.0, 2.7 ]] for datasets without headers. 

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

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

31 

32 Examples: 

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

34 

35 from biobb_ml.regression.regression_predict import regression_predict 

36 prop = { 

37 'predictions': [ 

38 { 

39 'var1': 1.0, 

40 'var2': 2.0 

41 }, 

42 { 

43 'var1': 4.0, 

44 'var2': 2.7 

45 } 

46 ] 

47 } 

48 regression_predict(input_model_path='/path/to/myModel.pkl', 

49 output_results_path='/path/to/newPredictedResults.csv', 

50 input_dataset_path='/path/to/myDataset.csv', 

51 properties=prop) 

52 

53 Info: 

54 * wrapped_software: 

55 * name: scikit-learn 

56 * version: >=0.24.2 

57 * license: BSD 3-Clause 

58 * ontology: 

59 * name: EDAM 

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

61 

62 """ 

63 

64 def __init__(self, input_model_path, output_results_path, 

65 input_dataset_path=None, properties=None, **kwargs) -> None: 

66 properties = properties or {} 

67 

68 # Call parent class constructor 

69 super().__init__(properties) 

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

71 

72 # Input/Output files 

73 self.io_dict = { 

74 "in": {"input_model_path": input_model_path, "input_dataset_path": input_dataset_path}, 

75 "out": {"output_results_path": output_results_path} 

76 } 

77 

78 # Properties specific for BB 

79 self.predictions = properties.get('predictions', []) 

80 self.properties = properties 

81 

82 # Check the properties 

83 self.check_properties(properties) 

84 self.check_arguments() 

85 

86 def check_data_params(self, out_log, err_log): 

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

88 self.io_dict["in"]["input_model_path"] = check_input_path(self.io_dict["in"]["input_model_path"], "input_model_path", out_log, self.__class__.__name__) 

89 self.io_dict["out"]["output_results_path"] = check_output_path(self.io_dict["out"]["output_results_path"], "output_results_path", False, out_log, self.__class__.__name__) 

90 if self.io_dict["in"]["input_dataset_path"]: 

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

92 

93 @launchlogger 

94 def launch(self) -> int: 

95 """Execute the :class:`RegressionPredict <regression.regression_predict.RegressionPredict>` regression.regression_predict.RegressionPredict object.""" 

96 

97 # check input/output paths and parameters 

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

99 

100 # Setup Biobb 

101 if self.check_restart(): 

102 return 0 

103 self.stage_files() 

104 

105 fu.log('Getting model from %s' % self.io_dict["in"]["input_model_path"], self.out_log, self.global_log) 

106 

107 with open(self.io_dict["in"]["input_model_path"], "rb") as f: 

108 while True: 

109 try: 

110 m = joblib.load(f) 

111 if (isinstance(m, linear_model.LinearRegression) or isinstance(m, ensemble.RandomForestRegressor)): 

112 new_model = m 

113 if isinstance(m, StandardScaler): 

114 scaler = m 

115 if isinstance(m, PolynomialFeatures): 

116 poly_features = m 

117 if isinstance(m, dict): 

118 variables = m 

119 except EOFError: 

120 break 

121 

122 if self.io_dict["in"]["input_dataset_path"]: 

123 # load dataset from input_dataset_path file 

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

125 if 'columns' in variables['independent_vars']: 

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

127 skiprows = 1 

128 else: 

129 labels = None 

130 skiprows = None 

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

132 else: 

133 # load dataset from properties 

134 if 'columns' in variables['independent_vars']: 

135 # sorting self.properties in the correct order given by variables['independent_vars']['columns'] 

136 index_map = {v: i for i, v in enumerate(variables['independent_vars']['columns'])} 

137 predictions = [] 

138 for i, pred in enumerate(self.predictions): 

139 sorted_pred = sorted(pred.items(), key=lambda pair: index_map[pair[0]]) 

140 predictions.append(dict(sorted_pred)) 

141 new_data_table = pd.DataFrame(data=get_list_of_predictors(predictions), columns=get_keys_of_predictors(predictions)) 

142 else: 

143 predictions = self.predictions 

144 new_data_table = pd.DataFrame(data=predictions) 

145 

146 if variables['scale']: 

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

148 new_data = scaler.transform(new_data_table) 

149 else: 

150 new_data = new_data_table 

151 

152 if 'poly_features' in locals(): 

153 new_data = poly_features.transform(new_data) 

154 p = new_model.predict(new_data) 

155 

156 if self.io_dict["in"]["input_dataset_path"] or 'columns' in variables['independent_vars']: 

157 new_data_table[variables['target']['column']] = p 

158 else: 

159 new_data_table[len(new_data_table.columns)] = p 

160 

161 fu.log('Predicting results\n\nPREDICTION RESULTS\n\n%s\n' % new_data_table, self.out_log, self.global_log) 

162 fu.log('Saving results to %s' % self.io_dict["out"]["output_results_path"], self.out_log, self.global_log) 

163 new_data_table.to_csv(self.io_dict["out"]["output_results_path"], index=False, header=True, float_format='%.3f') 

164 

165 # Copy files to host 

166 self.copy_to_host() 

167 

168 self.tmp_files.extend([ 

169 self.stage_io_dict.get("unique_dir") 

170 ]) 

171 self.remove_tmp_files() 

172 

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

174 

175 return 0 

176 

177 

178def regression_predict(input_model_path: str, output_results_path: str, input_dataset_path: str = None, properties: dict = None, **kwargs) -> int: 

179 """Execute the :class:`RegressionPredict <regression.regression_predict.RegressionPredict>` class and 

180 execute the :meth:`launch() <regression.regression_predict.RegressionPredict.launch>` method.""" 

181 

182 return RegressionPredict(input_model_path=input_model_path, 

183 output_results_path=output_results_path, 

184 input_dataset_path=input_dataset_path, 

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

186 

187 

188def main(): 

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

190 parser = argparse.ArgumentParser(description="Makes predictions from an input dataset and a given regression model.", formatter_class=lambda prog: argparse.RawTextHelpFormatter(prog, width=99999)) 

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

192 

193 # Specific args of each building block 

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

195 required_args.add_argument('--input_model_path', required=True, help='Path to the input model. Accepted formats: pkl.') 

196 required_args.add_argument('--output_results_path', required=True, help='Path to the output results file. Accepted formats: csv.') 

197 parser.add_argument('--input_dataset_path', required=False, help='Path to the dataset to predict. Accepted formats: csv.') 

198 

199 args = parser.parse_args() 

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

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

202 

203 # Specific call of each building block 

204 regression_predict(input_model_path=args.input_model_path, 

205 output_results_path=args.output_results_path, 

206 input_dataset_path=args.input_dataset_path, 

207 properties=properties) 

208 

209 

210if __name__ == '__main__': 

211 main()