pip install setuptools

#1
Files changed (2) hide show
  1. app.py +60 -61
  2. requirements.txt +4 -3
app.py CHANGED
@@ -18,21 +18,21 @@ from sklearn import metrics
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[-1]
29
 
30
  # for each column...
31
- for (colname, colval) in uncleaned_data.items():
32
 
33
- # check if col is already numeric; if so, add col directly
34
  # to new dataframe and skip to next column
35
- if pd.api.types.is_numeric_dtype(colval):
36
  data[colname] = uncleaned_data[colname].copy()
37
  continue
38
 
@@ -42,7 +42,7 @@ for (colname, colval) in uncleaned_data.items():
42
  transformed_col_vals = [] # new numeric datapoints
43
 
44
  # if not, for each item in that column...
45
- for item in colval.values:
46
 
47
  # if item is not in this col's dict...
48
  if item not in new_dict:
@@ -64,11 +64,11 @@ for (colname, colval) in uncleaned_data.items():
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)
@@ -82,28 +82,32 @@ y_pred = model.predict(x_test)
82
  ### -------------------------------- ###
83
  ### article generation ###
84
  ### -------------------------------- ###
 
85
 
86
  def get_feat():
87
- feats = [abs(val) for val in model.coef_[0]]
88
  max_val = max(feats)
89
  idx = feats.index(max_val)
90
  return data.columns[idx]
91
 
92
- acc = f"{round(metrics.accuracy_score(y_test, y_pred) * 100, 1)}%"
93
  most_imp_feat = get_feat()
 
 
94
 
95
 
96
  ### ------------------------------- ###
97
  ### interface creation ###
98
  ### ------------------------------- ###
99
 
 
100
  # predictor for generic number of features
101
  def general_predictor(*args):
102
  features = []
103
 
104
  # transform categorical input
105
  for colname, arg in zip(data.columns, args):
106
- if colname in cat_value_dicts:
107
  features.append(cat_value_dicts[colname][arg])
108
  else:
109
  features.append(arg)
@@ -113,61 +117,56 @@ def general_predictor(*args):
113
  result = model.predict(new_input)
114
  return cat_value_dicts[final_colname][result[0]]
115
 
 
116
 
117
- # Safe handling of markdown files before launching interface
118
- try:
119
- with open('info.md', 'r', encoding='utf-8') as f:
120
- lines = f.readlines()
121
- info_header = lines[0].strip() if lines else "# AI Recommendation Model"
122
- info_body = "".join(lines[1:]) if len(lines) > 1 else ""
123
- except FileNotFoundError:
124
- info_header = "# AI Recommendation Model"
125
- info_body = "Provide your inputs on the left side to generate a personalized recommendation."
126
 
 
127
 
128
- # Build layout with standard context managers
129
- with gr.Blocks() as block:
130
- gr.Markdown(info_header)
131
  gr.Markdown('Take the quiz to get a personalized recommendation using AI.')
132
 
133
  with gr.Row():
134
- # Left Panel: Core Application & Controls
135
- with gr.Column(scale=1):
136
- with gr.Group():
137
- inputls = []
138
- for colname in data.columns:
139
- # skip last column
140
- if colname == final_colname:
141
- continue
142
-
143
- # access categories dict if data is categorical
144
- # otherwise, just use a number input
145
- if colname in cat_value_dicts:
146
- radio_options = list(cat_value_dicts[colname].keys())
147
- inputls.append(gr.Dropdown(choices=radio_options, label=colname))
148
- else:
149
- inputls.append(gr.Number(label=colname))
150
-
151
- submit = gr.Button("Click to see your personalized result!", variant="primary")
152
- output = gr.Textbox(label="Your recommendation:", placeholder="your recommendation will appear here")
153
-
154
- submit.click(fn=general_predictor, inputs=inputls, outputs=output)
155
-
156
- with gr.Row():
157
- gr.Markdown(f"### Accuracy: \n{acc}")
158
- gr.Markdown(f"### Most important feature: \n{most_imp_feat}")
159
-
160
- gr.Markdown(
161
- "⭐ **Note:** Model accuracy is based on the uploaded `data.csv` and reflects how well "
162
- "the AI model can give correct recommendations for *that specific dataset*. Model accuracy "
163
- "and most important feature can be helpful for understanding how the model works, but "
164
- "*should not be considered absolute facts about the real world*."
165
- )
 
 
166
 
167
- # Right Panel: Reference Documentation
168
- with gr.Column(scale=1):
169
- with gr.Group():
170
- gr.Markdown(info_body)
171
 
172
- # Show and run the interface
173
  block.launch()
 
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
 
 
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:
 
64
  ### model training ###
65
  ### -------------------------------- ###
66
 
67
+ # select features and predicton; 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)
 
82
  ### -------------------------------- ###
83
  ### article generation ###
84
  ### -------------------------------- ###
85
+ # borrow file reading function from reader.py
86
 
87
  def get_feat():
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
+ acc = str(round(metrics.accuracy_score(y_test, y_pred) * 100, 1)) + "%"
94
  most_imp_feat = get_feat()
95
+ # info = get_article(acc, most_imp_feat)
96
+
97
 
98
 
99
  ### ------------------------------- ###
100
  ### interface creation ###
101
  ### ------------------------------- ###
102
 
103
+
104
  # predictor for generic number of features
105
  def general_predictor(*args):
106
  features = []
107
 
108
  # transform categorical input
109
  for colname, arg in zip(data.columns, args):
110
+ if (colname in cat_value_dicts):
111
  features.append(cat_value_dicts[colname][arg])
112
  else:
113
  features.append(arg)
 
117
  result = model.predict(new_input)
118
  return cat_value_dicts[final_colname][result[0]]
119
 
120
+ # add data labels to replace those lost via star-args
121
 
 
 
 
 
 
 
 
 
 
122
 
123
+ block = gr.Blocks()
124
 
125
+ with open('info.md') as f:
126
+ with block:
127
+ gr.Markdown(f.readline())
128
  gr.Markdown('Take the quiz to get a personalized recommendation using AI.')
129
 
130
  with gr.Row():
131
+ with gr.Group():
132
+ inputls = []
133
+ for colname in data.columns:
134
+ # skip last column
135
+ if colname == final_colname:
136
+ continue
137
+
138
+ # access categories dict if data is categorical
139
+ # otherwise, just use a number input
140
+ if colname in cat_value_dicts:
141
+ radio_options = list(cat_value_dicts[colname].keys())
142
+ inputls.append(gr.Dropdown(radio_options, type="value", label=colname))
143
+ else:
144
+ # add numerical input
145
+ inputls.append(gr.Number(label=colname))
146
+ gr.Markdown("<br />")
147
+
148
+ submit = gr.Button("Click to see your personalized result!", variant="primary")
149
+ gr.Markdown("<br />")
150
+ output = gr.Textbox(label="Your recommendation:", placeholder="your recommendation will appear here")
151
+
152
+ submit.click(fn=general_predictor, inputs=inputls, outputs=output)
153
+ gr.Markdown("<br />")
154
+
155
+ with gr.Row():
156
+ with gr.Group():
157
+ gr.Markdown(f"<h3>Accuracy: </h3>{acc}")
158
+ with gr.Group():
159
+ gr.Markdown(f"<h3>Most important feature: </h3>{most_imp_feat}")
160
+
161
+ gr.Markdown("<br />")
162
+
163
+ with gr.Group():
164
+ gr.Markdown('''⭐ Note that model accuracy is based on the uploaded data.csv and reflects how well the AI model can give correct recommendations for <em>that dataset</em>. Model accuracy and most important feature can be helpful for understanding how the model works, but <em>should not be considered absolute facts about the real world</em>.''')
165
 
166
+ with gr.Group():
167
+ with open('info.md') as f:
168
+ f.readline()
169
+ gr.Markdown(f.read())
170
 
171
+ # show the interface
172
  block.launch()
requirements.txt CHANGED
@@ -1,3 +1,4 @@
1
- pandas>=2.0.0
2
- numpy>=1.24.0
3
- scikit-learn>=1.3.0
 
 
1
+ pip>=23.2.1
2
+ pandas==1.3.4
3
+ scikit-learn>=1.0.1
4
+ numpy==1.21.4