shingkim commited on
Commit
aa9dfc0
·
verified ·
1 Parent(s): 0bfbe3d

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -0
app.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### ----------------------------- ###
2
+ ### libraries ###
3
+ ### ----------------------------- ###
4
+
5
+ import gradio as gr
6
+ import pandas as pd
7
+ import numpy as np
8
+ from sklearn.model_selection import train_test_split
9
+ from sklearn.linear_model import LogisticRegression
10
+ from sklearn import metrics
11
+
12
+
13
+ ### ------------------------------ ###
14
+ ### data transformation ###
15
+ ### ------------------------------ ###
16
+
17
+ # load dataset
18
+ uncleaned_data = pd.read_csv('data.csv')
19
+
20
+ # remove timestamp from dataset (always first column)
21
+ uncleaned_data = uncleaned_data.iloc[: , 1:]
22
+ data = pd.DataFrame()
23
+
24
+ # keep track of which columns are categorical and what
25
+ # those columns' value mappings are
26
+ # structure: {colname1: {...}, colname2: {...} }
27
+ cat_value_dicts = {}
28
+ final_colname = uncleaned_data.columns[len(uncleaned_data.columns) - 1]
29
+
30
+ # for each column...
31
+ for (colname, colval) in uncleaned_data.iteritems():
32
+
33
+ # check if col is already a number; if so, add col directly
34
+ # to new dataframe and skip to next column
35
+ if isinstance(colval.values[0], (np.integer, float)):
36
+ data[colname] = uncleaned_data[colname].copy()
37
+ continue
38
+
39
+ # structure: {0: "lilac", 1: "blue", ...}
40
+ new_dict = {}
41
+ val = 0 # first index per column
42
+ transformed_col_vals = [] # new numeric datapoints
43
+
44
+ # if not, for each item in that column...
45
+ for (row, item) in enumerate(colval.values):
46
+
47
+ # if item is not in this col's dict...
48
+ if item not in new_dict:
49
+ new_dict[item] = val
50
+ val += 1
51
+
52
+ # then add numerical value to transformed dataframe
53
+ transformed_col_vals.append(new_dict[item])
54
+
55
+ # reverse dictionary only for final col (0, 1) => (vals)
56
+ if colname == final_colname:
57
+ new_dict = {value : key for (key, value) in new_dict.items()}
58
+
59
+ cat_value_dicts[colname] = new_dict
60
+ data[colname] = transformed_col_vals
61
+
62
+
63
+ ### -------------------------------- ###
64
+ ### model training ###
65
+ ### -------------------------------- ###
66
+
67
+ # select features and prediction; automatically selects last column as prediction
68
+ cols = len(data.columns)
69
+ num_features = cols - 1
70
+ x = data.iloc[: , :num_features]
71
+ y = data.iloc[: , num_features:]
72
+
73
+ # split data into training and testing sets
74
+ x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)
75
+
76
+ # instantiate the model (using default parameters)
77
+ model = LogisticRegression()
78
+ model.fit(x_train, y_train.values.ravel())
79
+ y_pred = model.predict(x_test)
80
+
81
+
82
+ ### -------------------------------- ###
83
+ ### article generation ###
84
+ ### -------------------------------- ###
85
+ # borrow file reading function from reader.py
86
+
87
+ def get_feat_max():
88
+ feats = [abs(x) for x in model.coef_[0]]
89
+ max_val = max(feats)
90
+ idx = feats.index(max_val)
91
+ return data.columns[idx]
92
+
93
+ def get_feat_min():
94
+ feats = [abs(x) for x in model.coef_[0]]
95
+ min_val = min(feats)
96
+ idx = feats.index(min_val)
97
+ return data.columns[idx]
98
+
99
+ acc = str(round(metrics.accuracy_score(y_test, y_pred) * 100, 1)) + "%"
100
+ bacc = str(round(metrics.balanced_accuracy_score(y_test, y_pred) * 100, 1)) + "%"
101
+ most_imp_feat = get_feat_max()
102
+ least_imp_feat = get_feat_min()
103
+ # info = get_article(acc, most_imp_feat)
104
+
105
+
106
+
107
+ ### ------------------------------- ###
108
+ ### interface creation ###
109
+ ### ------------------------------- ###
110
+
111
+
112
+ # predictor for generic number of features
113
+ def general_predictor(*args):
114
+ features = []
115
+
116
+ # transform categorical input
117
+ for colname, arg in zip(data.columns, args):
118
+ if (colname in cat_value_dicts):
119
+ features.append(cat_value_dicts[colname][arg])
120
+ else:
121
+ features.append(arg)
122
+
123
+ # predict single datapoint
124
+ new_input = [features]
125
+ result = model.predict(new_input)
126
+ return cat_value_dicts[final_colname][result[0]]
127
+
128
+ # add data labels to replace those lost via star-args
129
+
130
+
131
+ block = gr.Blocks()
132
+
133
+ with open('info.md') as f:
134
+ with block:
135
+ gr.Markdown(f.readline())
136
+ gr.Markdown('Take the quiz to get a personalized recommendation using AI.')
137
+
138
+ with gr.Row():
139
+ with gr.Group():
140
+ inputls = []
141
+ for colname in data.columns:
142
+ # skip last column
143
+ if colname == final_colname:
144
+ continue
145
+
146
+ # access categories dict if data is categorical
147
+ # otherwise, just use a number input
148
+ if colname in cat_value_dicts:
149
+ radio_options = list(cat_value_dicts[colname].keys())
150
+ inputls.append(gr.Dropdown(choices=radio_options, type="value", label=colname))
151
+ else:
152
+ # add numerical input
153
+ inputls.append(gr.Number(label=colname))
154
+ gr.Markdown("<br />")
155
+
156
+ submit = gr.Button("Click to see your personalized result!", variant="primary")
157
+ gr.Markdown("<br />")
158
+ output = gr.Textbox(label="Your recommendation:", placeholder="your recommendation will appear here")
159
+
160
+ submit.click(fn=general_predictor, inputs=inputls, outputs=output)
161
+ gr.Markdown("<br />")
162
+
163
+ with gr.Row():
164
+ with gr.Group():
165
+ gr.Markdown(f"<h3>Accuracy: </h3>{acc}")
166
+ with gr.Group():
167
+ gr.Markdown(f"<h3>Balanced accuracy: </h3>{bacc}")
168
+
169
+
170
+
171
+ with gr.Group():
172
+ gr.Markdown("<br />")
173
+ gr.Markdown(f"<h3>Most important feature: </h3>{most_imp_feat}")
174
+ gr.Markdown("<br />")
175
+ gr.Markdown(f"<h3>Least important feature: </h3>{least_imp_feat}")
176
+
177
+ gr.Markdown("<br />")
178
+
179
+ with gr.Group():
180
+ gr.Markdown('''⭐ Note that <em>accuracy</em> (overall percentage of labels predicted correctly) is based on the uploaded data.csv and reflects how well the AI model can give correct recommendations for that dataset. <em>Balanced accuracy</em> (average accuracy per class) works better for imbalanced datasets because of better accounting for mispredictions of the minority class. Note that accuracy and most/least important feature can be helpful for understanding how the model works, but <em>should not be considered absolute facts about the real world</em>.''')
181
+
182
+ with gr.Group():
183
+ with open('info.md') as f:
184
+ f.readline()
185
+ gr.Markdown(f.read())
186
+
187
+ # show the interface
188
+ block.launch()