CoolFace
Apppublic

gingerale/Gnomespace

sourceHugging Faceupdated 5y agoView on Hugging Face
1likes
app.py128 linesDownload Raw Back to root
1## ----------------------------- ###2###           libraries           ###3### ----------------------------- ###4import gradio as gr5import pandas as pd6import numpy as np7import os8import warnings9from sklearn.model_selection import train_test_split10from sklearn.linear_model import LogisticRegression11from sklearn import metrics12from reader import get_article13 14warnings.filterwarnings("ignore")15 16 17### ------------------------------ ###18###       data transformation      ###19### ------------------------------ ###20# load dataset21uncleaned_data = pd.read_csv('data.csv')22 23# remove timestamp from dataset (always first column)24if uncleaned_data.columns[0].lower() == 'timestamp':25  uncleaned_data = uncleaned_data.iloc[: , 1:]26data = pd.DataFrame()27 28# keep track of which columns are categorical and what 29# those columns' value mappings are30# structure: {colname1: {...}, colname2: {...} }31cat_value_dicts = {}32final_colname = uncleaned_data.columns[len(uncleaned_data.columns) - 1]33 34# for each column...35for (colname, colval) in uncleaned_data.iteritems():36  # check if col is already a number; if so, add col directly37  # to new dataframe and skip to next column38  if isinstance(colval.values[0], (np.integer, float)):39    data[colname] = uncleaned_data[colname].copy()40    continue41    42  # structure: {0: "lilac", 1: "blue", ...}43  new_dict = {}44  key = 0 # first index per column45  transformed_col_vals = [] # new numeric datapoints46  47  # if not, for each item in that column...48  for item in colval.values:49    50    # if item is not in this col's dict...51    if item not in new_dict:52      new_dict[item] = key53      key += 154    55    # then add numerical value to transformed dataframe56    transformed_col_vals.append(new_dict[item])57  58  # reverse dictionary only for final col (0, 1) => (vals)59  if colname == final_colname:60    new_dict = {value : key for (key, value) in new_dict.items()}61  cat_value_dicts[colname] = new_dict62  data[colname] = transformed_col_vals63  64  65### -------------------------------- ###66###           model training         ###67### -------------------------------- ###68# select features and predicton; automatically selects last column as prediction69num_features = len(data.columns) - 170x = data.iloc[: , :num_features]71y = data.iloc[: , num_features:]72 73# split data into training and testing sets74x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)75 76# instantiate the model (using default parameters)77model = LogisticRegression(multi_class='multinomial', penalty='none', solver='newton-cg')78model.fit(x_train, y_train.values.ravel())79y_pred = model.predict(x_test)80 81 82### -------------------------------- ###83###            file reading          ###84### -------------------------------- ###85# borrow file reading function from reader.py86info = get_article()87 88 89### ------------------------------- ###90###        interface creation       ###91### ------------------------------- ###92# predictor for generic number of features93def general_predictor(*args):94  features = []95  96  # transform categorical input97  for colname, arg in zip(data.columns, args):98    if (colname in cat_value_dicts):99      features.append(cat_value_dicts[colname][arg])100    else:101      features.append(arg)102      103  # predict single datapoint104  new_input = [features]105  result = model.predict(new_input)106  return cat_value_dicts[final_colname][result[0]]107  108# add data labels to replace those lost via star-args109inputls = []110for colname in data.columns:111  # skip last column112  if colname == final_colname:113    continue114    115  # access categories dict if data is categorical116  # otherwise, just use a number input117  if colname in cat_value_dicts:118    radio_options = list(cat_value_dicts[colname].keys())119    inputls.append(gr.inputs.Radio(choices=radio_options, type="value", label=colname))120  else:121    # add numerical input122    inputls.append(gr.inputs.Number(label=colname))123  124# generate gradio interface125interface = gr.Interface(general_predictor, inputs=inputls, outputs="text", article=info['article'], css=info['css'], theme='huggingface', title=info['title'], allow_flagging=False, description=info['description'])126 127# show the interface 128interface.launch(share=True)