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

96 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 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 * **sandbox_path** (*str*) - ("./") [WF property] Parent path to the sandbox directory. 

35 

36 Examples: 

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

38 

39 from biobb_ml.classification.classification_predict import classification_predict 

40 prop = { 

41 'predictions': [ 

42 { 

43 'var1': 1.0, 

44 'var2': 2.0 

45 }, 

46 { 

47 'var1': 4.0, 

48 'var2': 2.7 

49 } 

50 ] 

51 } 

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

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

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

55 properties=prop) 

56 

57 Info: 

58 * wrapped_software: 

59 * name: scikit-learn 

60 * version: >=0.24.2 

61 * license: BSD 3-Clause 

62 * ontology: 

63 * name: EDAM 

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

65 

66 """ 

67 

68 def __init__(self, input_model_path, output_results_path, 

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

70 properties = properties or {} 

71 

72 # Call parent class constructor 

73 super().__init__(properties) 

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

75 

76 # Input/Output files 

77 self.io_dict = { 

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

79 "out": {"output_results_path": output_results_path} 

80 } 

81 

82 # Properties specific for BB 

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

84 self.properties = properties 

85 

86 # Check the properties 

87 self.check_properties(properties) 

88 self.check_arguments() 

89 

90 def check_data_params(self, out_log, err_log): 

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

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

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

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

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

96 

97 @launchlogger 

98 def launch(self) -> int: 

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

100 

101 # check input/output paths and parameters 

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

103 

104 # Setup Biobb 

105 if self.check_restart(): 

106 return 0 

107 self.stage_files() 

108 

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

110 

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

112 while True: 

113 try: 

114 m = joblib.load(f) 

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

116 new_model = m 

117 if isinstance(m, StandardScaler): 

118 scaler = m 

119 if isinstance(m, dict): 

120 variables = m 

121 except EOFError: 

122 break 

123 

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

125 # load dataset from input_dataset_path file 

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

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

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

129 skiprows = 1 

130 else: 

131 labels = None 

132 skiprows = None 

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

134 else: 

135 # load dataset from properties 

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

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

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

139 predictions = [] 

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

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

142 predictions.append(dict(sorted_pred)) 

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

144 else: 

145 predictions = self.predictions 

146 new_data_table = pd.DataFrame(data=predictions) 

147 

148 if variables['scale']: 

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

150 new_data = scaler.transform(new_data_table) 

151 else: 

152 new_data = new_data_table 

153 

154 p = new_model.predict_proba(new_data) 

155 

156 # if headers, create target column with proper label 

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

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

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

160 else: 

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

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

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

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

165 

166 # Copy files to host 

167 self.copy_to_host() 

168 

169 self.tmp_files.extend([ 

170 self.stage_io_dict.get("unique_dir") 

171 ]) 

172 self.remove_tmp_files() 

173 

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

175 

176 return 0 

177 

178 

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

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

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

182 

183 return ClassificationPredict(input_model_path=input_model_path, 

184 output_results_path=output_results_path, 

185 input_dataset_path=input_dataset_path, 

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

187 

188 

189def main(): 

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

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

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

193 

194 # Specific args of each building block 

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

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

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

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

199 

200 args = parser.parse_args() 

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

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

203 

204 # Specific call of each building block 

205 classification_predict(input_model_path=args.input_model_path, 

206 output_results_path=args.output_results_path, 

207 input_dataset_path=args.input_dataset_path, 

208 properties=properties) 

209 

210 

211if __name__ == '__main__': 

212 main()