ganning/FlyCatcher
0
1import warnings2warnings.filterwarnings('ignore')3import pandas as pd4from sklearn.metrics import confusion_matrix5from sklearn.metrics import accuracy_score6from sklearn.metrics import precision_score7from sklearn.metrics import recall_score8from sklearn.metrics import f1_score9from sklearn.preprocessing import MinMaxScaler10from sklearn.utils import shuffle11from sklearn.model_selection import train_test_split12from sklearn.linear_model import LogisticRegression13from sklearn.metrics import classification_report, confusion_matrix14from sklearn.model_selection import StratifiedKFold15from sklearn import svm16import numpy as np17from sklearn.inspection import permutation_importance18import gradio as gr19 20df = pd.read_csv('flies.csv')21 22replacement = {23 'a': 0,24 'x': 125}26 27df['Type'] = df['Type'].map(replacement)28 29cols_to_use = ['Wing Length (cm)', 'Abdomen Length (cm)', 'Antenna Length (cm)', 'Max Antenna Width (cm)']30# cols_to_use = ['Abdomen Length (cm)']31 32df_use = df[[*cols_to_use, 'Type']]33 34# Shuffle the dataframe35df_use = shuffle(df_use)36x = df_use.iloc[:,0:len(df_use.columns)-1]37y = df_use.iloc[:, -1]38features = x.columns.values39scaler = MinMaxScaler(feature_range = (0,1))40scaler.fit(x)41x = pd.DataFrame(scaler.transform(x))42x.columns = features43# x_train ,x_test , y_train ,y_test = train_test_split(x, y, train_size= 0.8)44# print(x)45 46skf = StratifiedKFold(n_splits=4, shuffle=True)47kfold = skf.split(x, y)48 49confusions = []50accs = []51precisions = []52recalls = []53f1s = []54importances = []55for i, x in enumerate(kfold):56 print(f"\n------------------Fold: {i+1}---------------")57 58 train, test = df_use.iloc[x[0].tolist()], df_use.iloc[x[1].tolist()]59 ytrain = train[["Type"]]60 print(f"Training: {len(train)}")61 print(f"Testing: {len(test)}")62 ytest = test[["Type"]]63 64 xtrain = train.drop("Type", axis=1)65 xtest = test.drop("Type", axis=1)66 67 model = svm.SVC(kernel='poly')68 model.fit(xtrain , np.squeeze(ytrain))69 ypred = model.predict(xtest)70 71 72 confusions.append(confusion_matrix(ytest, ypred))73 accs.append(accuracy_score(ytest, ypred))74 precisions.append(precision_score(ytest, ypred))75 recalls.append(recall_score(ytest, ypred))76 f1s.append(f1_score(ytest, ypred))77 78 79 80 perm_importance = permutation_importance(model, xtest, ytest)81 features = np.array(cols_to_use)82 83 sorted_idx = perm_importance.importances_mean.argsort()84 85 # print(perm_importance.importances_mean[sorted_idx])86 importances.append(perm_importance.importances_mean[sorted_idx])87 88 89avg_acc = sum(accs) / len(accs)90avg_precision = sum(precisions) / len(precisions)91avg_recall = sum(recalls) / len(recalls)92avg_f1 = sum(f1s) / len(f1s)93 94print()95print96print("Accuracy:", avg_acc)97print("Precision:", avg_precision)98print("Recall:", avg_recall)99print("F1:", avg_f1)100 101matrix = np.asmatrix(np.array(importances))102# print(matrix)103means = matrix.mean(0).A1 # convert back to array104 105 106test1 = [2.81, 1.80, 1.24, 0.46]107test2 = [2.65, 1.84, 1.28, 0.39]108test3 = [3.61, 2.04, 1.40, 0.50]109 110matrix = [111 test1, test2, test3112]113 114 115 116wingL = []117abdL = []118antL = []119antM = []120 121for row in matrix:122 wingL.append(row[0])123 abdL.append(row[1])124 antL.append(row[2])125 antM.append(row[3])126 127 128user_df = pd.DataFrame({129 'Wing Length (cm)': wingL,130 'Abdomen Length (cm)': abdL,131 'Antenna Length (cm)': antL,132 'Max Antenna Width (cm)': antM133})134 135user_df = scaler.transform(user_df)136 137preds = model.predict(user_df)138 139for pred in preds:140 if pred == 0:141 print("A", end = " ")142 else:143 print("X", end = " ")144 145 146def main(wingL, abdL, antL, maxAW):147 # test1 = [2.81, 1.80, 1.24, 0.46] # should predict x148 149 matrix = [150 [wingL, abdL, antL, maxAW]151 ]152 153 wingL = []154 abdL = []155 antL = []156 antM = []157 158 for row in matrix:159 wingL.append(row[0])160 abdL.append(row[1])161 antL.append(row[2])162 antM.append(row[3])163 164 165 user_df = pd.DataFrame({166 'Wing Length (cm)': wingL,167 'Abdomen Length (cm)': abdL,168 'Antenna Length (cm)': antL,169 'Max Antenna Width (cm)': antM170 })171 172 user_df = scaler.transform(user_df)173 174 preds = model.predict(user_df)175 176 if preds[0] == 0:177 return "A"178 else:179 return "X"180 181gr.Interface(182 fn=main, 183 title="FlyCatcher",184 examples=[[2.81, 1.80, 1.24, 0.46], [2.65, 1.84, 1.28, 0.39], [3.61, 2.04, 1.40, 0.50]],185 inputs=[gr.inputs.Number(label="Wing Length (cm)"), 186 gr.inputs.Number(label="Abdomen Length (cm)"),187 gr.inputs.Number(label="Antenna Length (cm)"),188 gr.inputs.Number(label="Max Antenna Width (cm)"),189 ],190 outputs=["text"],191 theme="huggingface").launch(debug=False, share=False)192 