forked from ornlpmcp/ASCENDS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
predict.py
135 lines (109 loc) · 4.16 KB
/
predict.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env python3 -W ignore
import warnings
warnings.filterwarnings('ignore')
import pickle
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import Normalizer
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import cross_val_predict
from sklearn.gaussian_process.kernels import WhiteKernel, ExpSineSquared
import numpy as np
import os
import sys
import configparser
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import csv
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import SGDRegressor
from sklearn.isotonic import IsotonicRegression
from sklearn.metrics import mean_squared_error
from sklearn.ensemble import RandomForestRegressor
from pandas.plotting import scatter_matrix
from sklearn.neighbors import KNeighborsRegressor
from sklearn.isotonic import IsotonicRegression
from sklearn.kernel_ridge import KernelRidge
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import SelectFromModel
from sklearn.svm import LinearSVC
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_regression
from sklearn import linear_model
from sklearn.metrics import r2_score
from sklearn import svm
from sklearn import preprocessing
import argparse
import ast
from pathlib import PurePath
def main(args):
predict_type = args.predict_type
model_file = PurePath(args.model_file)
input_file = PurePath(args.input_file)
project_file = PurePath(args.project_file)
mapping = args.mapping
mapping = ast.literal_eval(mapping)
path_to_model = model_file
data = pd.read_csv(input_file)
model_dict = pickle.load(open(path_to_model, 'rb'))
model = model_dict['model']
original_data = pd.DataFrame(data)
input_cols = model_dict['input_cols']
data = data[input_cols]
try:
scaler = model_dict['fitted_scaler_x']
if scaler!='False' and scaler is not None:
data = scaler.transform(data)
except:
pass
try:
for key in mapping.keys():
data[key] = data[key].map(mapping[key])
except:
pass
if predict_type=='r':
outcome = model.predict(data)
if model_dict['model_abbr']=='NET':
outcome = outcome.reshape(len(outcome),)
result = pd.DataFrame(outcome,columns=[model_dict['target_col']])
final = original_data.join(result)
else:
if model_dict['model_abbr']=='NET':
outcome = model.predict_classes(data)
outcome_prob = model.predict(data)
else:
outcome = model.predict(data)
outcome_prob = model.predict_proba(data)
result = pd.DataFrame(outcome,columns=[model_dict['target_col']])
result_prob = pd.DataFrame(outcome_prob)
final = original_data.join(result_prob).join(result)
new_set_of_dicts = {}
if mapping!={}:
for key in mapping.keys():
dict_item = mapping[key]
new_dict = {}
for key_ in dict_item.keys():
new_dict[dict_item[key_]]=key_
new_set_of_dicts[key] = new_dict
mapping = new_set_of_dicts
for key in mapping.keys():
final[key] = final[key].map(mapping[key])
if predict_type=='c': final = final.rename(columns=mapping[model_dict['target_col']])
model_name=model_file.stem
final.to_csv(project_file / "predictions" / (model_name+"_predicted.csv"), sep=',')
print("* DONE")
if __name__=="__main__":
print("\n * ASCENDS: Advanced data SCiENce toolkit for Non-Data Scientists ")
print(" * ML model predictor \n")
parser = argparse.ArgumentParser()
parser.add_argument("predict_type",help="Type of model to predict with",choices=['r','c'])
parser.add_argument( "model_file")
parser.add_argument( "input_file")
parser.add_argument( "project_file")
parser.add_argument( "--mapping", help="Mapping string value to numbers", default='{}')
args = parser.parse_args()
main(args)