Spaces:
Runtime error
Runtime error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237import gradio as grimport numpy as npimport pandas as pdfrom matplotlib import pyplot as pltimport matplotlib.colors as colorsimport itertoolsfrom scipy.stats import normfrom scipy import statsfrom sklearn.naive_bayes import GaussianNBdef gaussian(x, n, u, s):#u = x.mean()#s = x.std()# divide [x.min(), x.max()] by nx = np.linspace(x.min(), x.max(), n)a = ((x - u) ** 2) / (2 * (s ** 2))y = 1 / (s * np.sqrt(2 * np.pi)) * np.exp(-a)return x, y, u, simport gradio as gr# 1. define mean and standard deviation for class 1set_fea1_mean_class1 = gr.inputs.Slider(0, 20, step=0.5, default=1, label = 'Feature_1 Mean (Class 1)')set_fea1_var_class1 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Feature_1 Variance (Class 1)')set_fea2_mean_class1 = gr.inputs.Slider(0, 20, step=0.5, default=2, label = 'Feature_2 Mean (Class 1)')set_fea2_var_class1 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Feature_2 Variance (Class 1)')set_fea_covariance_class1 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Feature_1_2 Co-Variance (Class 1)')# 2. define mean and standard deviation for class 2set_fea1_mean_class2 = gr.inputs.Slider(0, 20, step=0.5, default=5, label = 'Feature_1 Mean (Class 2)')set_fea1_var_class2 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Feature_1 Variance (Class 2)')set_fea2_mean_class2 = gr.inputs.Slider(0, 20, step=0.5, default=6, label = 'Feature_2 Mean (Class 2)')set_fea2_var_class2 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Feature_2 Variance (Class 2)')set_fea_covariance_class2 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Feature_1_2 Co-Variance (Class 2)')# 3. Define the number of data pointsset_number_points = gr.inputs.Slider(10, 100, step=5, default=20, label = 'Number of samples in each class')# 4. show distribution or notset_show_dist = gr.inputs.Checkbox(label="Show data distribution")# 5. set classifier typeset_classifier = gr.inputs.Dropdown(["None", "LDA", "QDA", "NaiveBayes"])# 6. define output imagem modelset_out_plot_images = gr.outputs.Image(label="Data visualization")set_out_plot_table = gr.outputs.Dataframe(type='pandas', label ='Simulated Dataset')def plot_figure_twofeature(N, fea1_u1, fea1_var1, fea2_u1, fea2_var1, covariance1, fea1_u2, fea1_var2, fea2_u2, fea2_var2, covariance2, show_dist, classifier=None):#N = 100import numpy as npimport matplotlib.pyplot as pppp.style.use('default')val = 0. # this is the value where you want the data to appear on the y-axis.np.random.seed(seed = 3)mu1 = [fea1_u1, fea2_u1]sigma1 = [[np.sqrt(fea1_var1), np.sqrt(covariance1)], [np.sqrt(covariance1), np.sqrt(fea2_var1)]]points_class1_fea1, points_class1_fea2 = np.random.multivariate_normal(mu1, sigma1, N).Tmu2 = [fea1_u2, fea2_u2]sigma2 = [[np.sqrt(fea1_var2), np.sqrt(covariance2)], [np.sqrt(covariance2), np.sqrt(fea2_var2)]]points_class2_fea1, points_class2_fea2 = np.random.multivariate_normal(mu2, sigma2, N).Tmu_list = [mu1,mu2]sigma_list = [sigma1,sigma2]color_list = ['darkblue','darkgreen']pd_class1 = pd.DataFrame({'Feature 1 (X)': points_class1_fea1,'Feature 2 (X)': points_class1_fea2, 'Label (Y)': np.repeat(0,len(points_class1_fea1))})pd_class2 = pd.DataFrame({'Feature 1 (X)': points_class2_fea1,'Feature 2 (X)': points_class2_fea2, 'Label (Y)': np.repeat(1,len(points_class2_fea1))})pd_all = pd.concat([pd_class1, pd_class2]).reset_index(drop=True)import numpy as np#X_data= pd_all['Feature 1 (X)','Feature 2 (X)'].to_numpy().reshape((len(pd_all),2))#y_labels= pd_all['Label (Y)']#Setup X and y dataX_data = np.asarray(np.vstack((np.hstack((points_class1_fea1, points_class1_fea2)),np.hstack((points_class2_fea1, points_class2_fea2)))).T)y_labels = np.hstack((np.zeros(N),np.ones(N)))print("X_data: ",X_data.shape)fig = pp.figure(figsize=(8, 6)) # figure size in inchesfig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.3, wspace=0.05)#pp.tick_params(left = False, right = False , labelleft = True ,# labelbottom = True, bottom = False)#reference = [stats.uniform.rvs(loc=1, scale = 1) for x in range(N)]pp.plot(points_class1_fea1, points_class1_fea2 + val, 'x', label = 'Class 1', markersize = 10)pp.plot(points_class2_fea1, points_class2_fea2 + val, 'o', label = 'Class 2', markersize = 10)# define x, y limits#x_min, x_max = X_data[:, 0].min() - 1, X_data[:, 0].max() + 1#y_min, y_max = X_data[:, 1].min() - 1, X_data[:, 1].max() + 1x_min, x_max = -5, 15y_min, y_max = -5, 15X_grid, Y_grid = np.meshgrid(np.linspace(x_min, x_max, 100),np.linspace(y_min, y_max, 100))if show_dist:#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%##Plotting the contours of the Gaussians on left hand side plotfor i in range(2):zz = np.array( [stats.multivariate_normal.pdf(np.array([xx,yy]), mean=mu_list[i], cov=sigma_list[i])for xx, yy in zip(np.ravel(X_grid), np.ravel(Y_grid)) ] )#Reshaping the predicted class into the meshgrid shapeZ = zz.reshape(X_grid.shape[0])#Plot the contourspp.contour( X_grid, Y_grid, Z, 5, alpha = .3, colors = color_list[i])### draw decision boundary on knnimport numpy as npfrom matplotlib import pyplot as pltfrom sklearn import neighbors, datasetsfrom matplotlib.colors import ListedColormap# Create color maps for 3-class classification problem, as with iriscmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])cmap_bold = ListedColormap(['#FF0000', '#00FF00'])# plt.scatter(x1, y1, marker='x', alpha = .7, label = 'Class 1', s = 50)# plt.scatter(x2, y2, marker='o', alpha = .7, label = 'Class 2', s = 50)# plt.xlabel("Feature 1 (X1)", size=20)# plt.xticks(fontsize=20)# plt.ylabel("Feature 2 (X2)", size=20)# plt.yticks(fontsize=20)if classifier == 'LDA':from sklearn.discriminant_analysis import LinearDiscriminantAnalysismodel_sk = LinearDiscriminantAnalysis()model_sk.fit(X_data,y_labels)X_grid, Y_grid = np.meshgrid(np.linspace(x_min, x_max, N),np.linspace(y_min, y_max, N))#Predictions for each point on meshgridzz = np.array( [model_sk.predict( [[xx,yy]])[0] for xx, yy in zip(np.ravel(X_grid), np.ravel(Y_grid)) ] )Z = zz.reshape(X_grid.shape)pp.pcolormesh(X_grid, Y_grid, Z, cmap=cmap_light, alpha=0.2)#pp.contour( X_grid, Y_grid, Z, 1, alpha = .3, colors = ('red'))elif classifier == 'QDA':from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysismodel_sk = QuadraticDiscriminantAnalysis()model_sk.fit(X_data,y_labels)X_grid, Y_grid = np.meshgrid(np.linspace(x_min, x_max, N),np.linspace(y_min, y_max, N))#Predictions for each point on meshgridzz = np.array( [model_sk.predict( [[xx,yy]])[0] for xx, yy in zip(np.ravel(X_grid), np.ravel(Y_grid)) ] )Z = zz.reshape(X_grid.shape)pp.pcolormesh(X_grid, Y_grid, Z, cmap=cmap_light, alpha=0.2)elif classifier == 'NaiveBayes':from sklearn.naive_bayes import GaussianNBmodel_sk = GaussianNB(priors = None)model_sk.fit(X_data,y_labels)X_grid, Y_grid = np.meshgrid(np.linspace(x_min, x_max, N),np.linspace(y_min, y_max, N))#Predictions for each point on meshgridzz = np.array( [model_sk.predict( [[xx,yy]])[0] for xx, yy in zip(np.ravel(X_grid), np.ravel(Y_grid)) ] )Z = zz.reshape(X_grid.shape)pp.pcolormesh(X_grid, Y_grid, Z, cmap=cmap_light, alpha=0.2)#Reshaping the predicted class into the meshgrid shape#Plot the contoursprint(x_min, x_max)print(y_min, y_max)#pp.xlim([x_min-0.8*x_max, x_max+0.8*x_max])#pp.ylim([y_min-0.8*y_max, y_max+0.8*y_max])pp.xlim([x_min, x_max])pp.ylim([y_min, y_max])pp.xlabel("Feature 1 (X)", size=20)pp.xticks(fontsize=20)pp.yticks(fontsize=20)pp.ylabel("Feature 2 (X)", size=20)pp.legend(loc='upper right', borderpad=0, handletextpad=0, fontsize = 20)pp.savefig('plot.png')return 'plot.png', pd_all### configure gradio, detailed can be found at https://www.gradio.app/docs/#i_sliderinterface = gr.Interface(fn=plot_figure_twofeature, inputs=[set_number_points,set_fea1_mean_class1,set_fea1_var_class1,set_fea2_mean_class1,set_fea2_var_class1,set_fea_covariance_class1,set_fea1_mean_class2,set_fea1_var_class2,set_fea2_mean_class2,set_fea2_var_class2,set_fea_covariance_class2, set_show_dist, set_classifier],outputs=[set_out_plot_images,set_out_plot_table],examples_per_page = 2,#examples = get_sample_data(10),title="CSCI4750/5750 Demo: Web Application for Probabilistic Classifier (Two feature)",description= "Click examples below for a quick demo",theme = 'huggingface',layout = 'vertical', live=True)interface.launch(debug=True)
app.py+237