File size: 6,438 Bytes
5a472d7
06d0d4a
 
 
 
 
 
d7547a1
06d0d4a
5a472d7
 
 
22a5515
 
 
 
 
 
 
 
 
 
 
 
5a472d7
 
 
 
 
bbb0b8f
5a472d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc070db
 
 
 
 
 
31e4d35
5a472d7
 
 
 
 
 
dc070db
 
 
 
 
 
 
 
31e4d35
dc070db
5a472d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc070db
5a472d7
dc070db
5a472d7
 
 
 
 
 
22a5515
5a472d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc070db
 
5a472d7
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import gradio as gr
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import matplotlib.colors as colors
import itertools
from scipy.stats import norm
from scipy import stats
from sklearn.naive_bayes import GaussianNB



def gaussian(x, n, u, s):
    #u = x.mean()
    #s = x.std()

    # divide [x.min(), x.max()] by n
    x = 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, s
    
def plot_figure(N, u1, std1, u2, std2, show_dist, classifier=None):
  #N = 100
  import numpy as np
  import matplotlib.pyplot as pp
  pp.style.use('default')
  val = 0. # this is the value where you want the data to appear on the y-axis.

  points_class1 = [stats.norm.rvs(loc=u1, scale = std1) for x in range(N)]
  points_class2 = [stats.norm.rvs(loc=u2, scale = std2) for x in range(N)]

  pd_class1 = pd.DataFrame({'Feature 1 (X)': points_class1, 'Label (Y)': np.repeat(0,len(points_class1))})
  pd_class2 = pd.DataFrame({'Feature 1 (X)': points_class2, 'Label (Y)': np.repeat(1,len(points_class2))})


  pd_all = pd.concat([pd_class1, pd_class2]).reset_index(drop=True)

  import numpy as np
  X_data= pd_all['Feature 1 (X)'].to_numpy().reshape((len(pd_all),1))
  y_labels= pd_all['Label (Y)']


  # define x, y limits
  x_min, x_max = X_data[:, 0].min() - 1, X_data[:, 0].max() + 1
  y_min, y_max = 0-1, 1 + 1

  fig = pp.figure(figsize=(8, 6)) # figure size in inches
  fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.3, wspace=0.05) 


  pp.tick_params(left = False, right = False , labelleft = False ,
                  labelbottom = True, bottom = False)

  #reference = [stats.uniform.rvs(loc=1, scale = 1) for x in range(N)]
  pp.plot(points_class1, np.zeros_like(points_class1) + val, 'x', label = 'Class 1', markersize = 10)
  pp.plot(points_class2, np.zeros_like(points_class2) + val, 'o', label = 'Class 2', markersize = 10)


  if show_dist:
    x = np.arange(x_min, x_max, 0.01, dtype=np.float) # define range of x
    x, y, u, s = gaussian(x, 10000, np.mean(points_class1), np.std(points_class1) )
    pp.plot(x, y)
    #pp.plot(x, y, label=r'$Gaussian (\mu=%.2f,\ \sigma=%.2f)$' % (u, s))


    x = np.arange(x_min, x_max, 0.01, dtype=np.float) # define range of x
    x, y, u, s = gaussian(x, 10000, np.mean(points_class2), np.std(points_class2) )
    pp.plot(x, y)
    #pp.plot(x, y, label=r'$Gaussian (\mu=%.2f,\ \sigma=%.2f)$' % (u, s))



  ### draw decision boundary on knn 

  import numpy as np
  from matplotlib import pyplot as plt
  from sklearn import neighbors, datasets
  from matplotlib.colors import ListedColormap

  # Create color maps for 3-class classification problem, as with iris
  cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA'])
  cmap_bold = ListedColormap(['#FF0000', '#00FF00'])


  xx, yy = np.meshgrid(np.linspace(x_min, x_max, 100),
                          np.linspace(y_min, y_max, 100))

  
  if classifier == 'LDA':
    from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
    model_sk = LinearDiscriminantAnalysis()
    model_sk.fit(X_data,y_labels)
    zz = model_sk.predict(np.c_[xx.ravel()])

    #Predictions for each point on meshgrid
    #zz = np.array(  [model_sk.predict( [[xx,yy]])[0] for xx, yy in zip(np.ravel(X), np.ravel(Y)) ] )

    #Reshaping the predicted class into the meshgrid shape
    Z = zz.reshape(xx.shape)

    pp.pcolormesh(xx, yy, Z, cmap=cmap_light, alpha=0.2)
  elif classifier == 'QDA':
    from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
    model_sk = QuadraticDiscriminantAnalysis()
    model_sk.fit(X_data,y_labels)
    
    model_sk.fit(X_data,y_labels)
    zz = model_sk.predict(np.c_[xx.ravel()])

    #Predictions for each point on meshgrid
    #zz = np.array(  [model_sk.predict( [[xx,yy]])[0] for xx, yy in zip(np.ravel(X), np.ravel(Y)) ] )

    #Reshaping the predicted class into the meshgrid shape
    Z = zz.reshape(xx.shape)
    
    print("Z: ",Z)
    pp.pcolormesh(xx, yy, Z, cmap=cmap_light, alpha=0.2)
  elif classifier == 'NaiveBayes':
    from sklearn.naive_bayes import GaussianNB
    model_sk = GaussianNB(priors = None)
    model_sk.fit(X_data,y_labels)
    Z = model_sk.predict(np.c_[xx.ravel()])
    Z = Z.reshape(xx.shape)

    pp.pcolormesh(xx, yy, Z, cmap=cmap_light, alpha=0.2)

  

  pp.xlim([x_min, x_max])
  pp.ylim([y_min, y_max])
  pp.xlabel("Feature 1 (X1)", size=20)
  pp.xticks(fontsize=20)
  pp.ylabel("Feature 2 (X2)")
  pp.legend(loc='upper right', borderpad=0, handletextpad=0, fontsize = 20)
  pp.savefig('plot.png')

  return 'plot.png', pd_all



set_mean_class1 = gr.inputs.Slider(-20, 20, step=0.5, default=1, label = 'Mean (Class 1)')
set_std_class1 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Standard Deviation (Class 1)')

# 2. define mean and standard deviation for class 2

set_mean_class2 = gr.inputs.Slider(-20, 20, step=0.5, default=10, label = 'Mean (Class 2)')
set_std_class2 = gr.inputs.Slider(0, 10, step=0.5, default=1.5, label = 'Standard Deviation (Class 2)')

# 3. Define the number of data points 
set_number_points = gr.inputs.Slider(10, 100, step=5, default=20, label = 'Number of samples in each class')

# 4. show distribution or not
set_show_dist = gr.inputs.Checkbox(label="Show data distribution")

# 5. set classifier type
set_classifier = gr.inputs.Dropdown(["None", "LDA", "QDA", "NaiveBayes"])

# 6. define output imagem model
set_out_plot_images = gr.outputs.Image(label="Data visualization")

set_out_plot_table = gr.outputs.Dataframe(type='pandas', label ='Simulated Dataset')





### configure gradio, detailed can be found at https://www.gradio.app/docs/#i_slider
interface = gr.Interface(fn=plot_figure, 
                         inputs=[set_number_points,set_mean_class1,set_std_class1,set_mean_class2,set_std_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 (Single feature)", 
                         description= "Click examples below for a quick demo",
                         theme = 'huggingface',
                         layout = 'vertical', live=True
                         )
interface.launch(debug=True)