Coverage for biobb_ml/classification/classification_predict.py: 74%

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

9from sklearn import linear_model 

10from sklearn.neighbors import KNeighborsClassifier 

11from sklearn.tree import DecisionTreeClassifier 

12from sklearn import ensemble 

13from sklearn import svm 

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.classification.common import check_input_path, check_output_path, getHeader, get_list_of_predictors, get_keys_of_predictors 

18 

19 

20class ClassificationPredict(BiobbObject): 

21 """ 

22 | biobb_ml ClassificationPredict 

23 | Makes predictions from an input dataset and a given classification model. 

24 | Makes predictions from an input dataset (provided either as a file or as a dictionary property) and a given classification model trained with `DecisionTreeClassifier <https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html>`_, `KNeighborsClassifier <https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html>`_, `LogisticRegression <https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html>`_, `RandomForestClassifier <https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html>`_, `Support Vector Machine <https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html>`_ methods. 

25 

26 Args: 

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

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

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

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

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

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

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

34 

35 Examples: 

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

37 

38 from biobb_ml.classification.classification_predict import classification_predict 

39 prop = { 

40 'predictions': [ 

41 { 

42 'var1': 1.0, 

43 'var2': 2.0 

44 }, 

45 { 

46 'var1': 4.0, 

47 'var2': 2.7 

48 } 

49 ] 

50 } 

51 classification_predict(input_model_path='/path/to/myModel.pkl', 

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

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

54 properties=prop) 

55 

56 Info: 

57 * wrapped_software: 

58 * name: scikit-learn 

59 * version: >=0.24.2 

60 * license: BSD 3-Clause 

61 * ontology: 

62 * name: EDAM 

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

64 

65 """ 

66 

67 def __init__(self, input_model_path, output_results_path, 

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

69 properties = properties or {} 

70 

71 # Call parent class constructor 

72 super().__init__(properties) 

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

74 

75 # Input/Output files 

76 self.io_dict = { 

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

78 "out": {"output_results_path": output_results_path} 

79 } 

80 

81 # Properties specific for BB 

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

83 self.properties = properties 

84 

85 # Check the properties 

86 self.check_properties(properties) 

87 self.check_arguments() 

88 

89 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

95 

96 @launchlogger 

97 def launch(self) -> int: 

98 """Execute the :class:`ClassificationPredict <classification.classification_predict.ClassificationPredict>` classification.classification_predict.ClassificationPredict object.""" 

99 

100 # check input/output paths and parameters 

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

102 

103 # Setup Biobb 

104 if self.check_restart(): 

105 return 0 

106 self.stage_files() 

107 

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

109 

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

111 while True: 

112 try: 

113 m = joblib.load(f) 

114 if (isinstance(m, linear_model.LogisticRegression) or isinstance(m, KNeighborsClassifier) or isinstance(m, DecisionTreeClassifier) or isinstance(m, ensemble.RandomForestClassifier) or isinstance(m, svm.SVC)): 

115 new_model = m 

116 if isinstance(m, StandardScaler): 

117 scaler = m 

118 if isinstance(m, dict): 

119 variables = m 

120 except EOFError: 

121 break 

122 

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

124 # load dataset from input_dataset_path file 

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

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

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

128 skiprows = 1 

129 else: 

130 labels = None 

131 skiprows = None 

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

133 else: 

134 # load dataset from properties 

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

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

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

138 predictions = [] 

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

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

141 predictions.append(dict(sorted_pred)) 

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

143 else: 

144 predictions = self.predictions 

145 new_data_table = pd.DataFrame(data=predictions) 

146 

147 if variables['scale']: 

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

149 new_data = scaler.transform(new_data_table) 

150 else: 

151 new_data = new_data_table 

152 

153 p = new_model.predict_proba(new_data) 

154 

155 # if headers, create target column with proper label 

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

157 clss = ' (' + ', '.join(str(x) for x in variables['target_values']) + ')' 

158 new_data_table[variables['target']['column'] + ' ' + clss] = tuple(map(tuple, p)) 

159 else: 

160 new_data_table[len(new_data_table.columns)] = tuple(map(tuple, p)) 

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 classification_predict(input_model_path: str, output_results_path: str, input_dataset_path: str = None, properties: dict = None, **kwargs) -> int: 

179 """Execute the :class:`ClassificationPredict <classification.classification_predict.ClassificationPredict>` class and 

180 execute the :meth:`launch() <classification.classification_predict.ClassificationPredict.launch>` method.""" 

181 

182 return ClassificationPredict(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 classification 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 classification_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()