Spaces:
Sleeping
Sleeping
File size: 4,434 Bytes
f4d4dd8 ce151f9 f4d4dd8 ce151f9 f4d4dd8 ce151f9 f4d4dd8 ce151f9 f4d4dd8 ce151f9 f4d4dd8 5934a9f f4d4dd8 ce151f9 f4d4dd8 5934a9f f4d4dd8 5934a9f f4d4dd8 ce151f9 f4d4dd8 5934a9f f4d4dd8 ce151f9 | 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 136 137 138 139 140 141 142 143 144 145 146 147 | import os
import numpy as np
import pandas as pd
import gradio as gr
import spaces
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
### ------------------------------ ###
### Data Transformation ###
### ------------------------------ ###
# Load dataset
uncleaned_data = pd.read_csv('data.csv')
# Remove timestamp from dataset (first column)
uncleaned_data = uncleaned_data.iloc[:, 1:]
data = pd.DataFrame()
# Track categorical mappings
cat_value_dicts = {}
final_colname = uncleaned_data.columns[-1]
for colname, colval in uncleaned_data.items():
if isinstance(colval.values[0], (np.integer, float, np.floating)):
data[colname] = uncleaned_data[colname].copy()
continue
new_dict = {}
val = 0
transformed_col_vals = []
for item in colval.values:
if item not in new_dict:
new_dict[item] = val
val += 1
transformed_col_vals.append(new_dict[item])
if colname == final_colname:
new_dict = {value: key for key, value in new_dict.items()}
cat_value_dicts[colname] = new_dict
data[colname] = transformed_col_vals
### -------------------------------- ###
### Model Training ###
### -------------------------------- ###
feature_cols = [c for c in data.columns if c != final_colname]
x = data[feature_cols]
y = data[final_colname]
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=42)
# ZeroGPU decorator on startup model training
@spaces.GPU
def train_model(x_tr, y_tr):
clf = LogisticRegression(max_iter=1000)
clf.fit(x_tr, y_tr.values.ravel())
return clf
model = train_model(x_train, y_train)
y_pred = model.predict(x_test)
acc = str(round(metrics.accuracy_score(y_test, y_pred) * 100, 1)) + "%"
def get_feat():
feats = [abs(val) for val in model.coef_[0]]
max_val = max(feats)
idx = feats.index(max_val)
return feature_cols[idx]
most_imp_feat = get_feat()
### -------------------------------- ###
### Helper: Read info.md ###
### -------------------------------- ###
header_text = "Personalized Recommendation AI"
body_text = ""
if os.path.exists('info.md'):
with open('info.md', 'r') as f:
lines = f.readlines()
if lines:
header_text = lines[0].strip()
body_text = "".join(lines[1:])
### ------------------------------- ###
### Interface Creation ###
### ------------------------------- ###
# ZeroGPU decorator on prediction function
@spaces.GPU
def general_predictor(*args):
features = []
for colname, arg in zip(feature_cols, args):
if colname in cat_value_dicts:
features.append(cat_value_dicts[colname][arg])
else:
features.append(float(arg) if arg is not None else 0.0)
new_input = [features]
result = model.predict(new_input)[0]
if final_colname in cat_value_dicts:
return cat_value_dicts[final_colname].get(result, str(result))
return str(result)
with gr.Blocks() as demo:
gr.Markdown(f"# {header_text}")
gr.Markdown('Take the quiz to get a personalized recommendation using AI.')
with gr.Row():
with gr.Column():
inputls = []
for colname in feature_cols:
if colname in cat_value_dicts:
radio_options = list(cat_value_dicts[colname].keys())
inputls.append(gr.Dropdown(radio_options, label=colname))
else:
inputls.append(gr.Number(label=colname))
submit = gr.Button("Click to see your personalized result!", variant="primary")
output = gr.Textbox(label="Your recommendation:", placeholder="your recommendation will appear here")
submit.click(fn=general_predictor, inputs=inputls, outputs=output)
with gr.Row():
with gr.Column():
gr.Markdown(f"### Accuracy:\n{acc}")
with gr.Column():
gr.Markdown(f"### Most important feature:\n{most_imp_feat}")
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 that dataset.*'
)
with gr.Column():
gr.Markdown(body_text)
demo.launch() |