File size: 10,900 Bytes
03250df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f46e416
03250df
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
import numpy as np
import plotly.graph_objects as go
import matplotlib.pyplot as plt

from sklearn.datasets import load_digits
from sklearn.preprocessing import MinMaxScaler

from sklearn.decomposition import TruncatedSVD
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.ensemble import RandomTreesEmbedding
from sklearn.manifold import (
    Isomap,
    LocallyLinearEmbedding,
    MDS,
    SpectralEmbedding,
    TSNE
    )
from sklearn.neighbors import NeighborhoodComponentsAnalysis
from sklearn.pipeline import make_pipeline

import gradio as gr

#====================================================================

digits = load_digits(n_class=10)
X, y = digits.data, digits.target

algorithms = ['Linear Discriminant Analysis',
          't-SNE',
          'Truncated SVD',
          'Isomap',
          'Locally Linear Embedding',
          'Random Trees Embedding',
          'Spectral Embedding',
          'Neighborhood Component Analysis']

#====================================================================
class UserInterface:
    def __init__(self):
        self.components = {}
        self.bindings = {}
    
    def add_component(self, name, component, kwargs={}):
        self.components[name] = component(**{'visible': False, **kwargs})

    def all_components(self):
        return list(self.components.values())
    
    def get(self, name):
        return self.components[name]

    def get_kwargs(self, args):
        return {k:v for k,v in zip(list(self.components.keys()), args)}

    def get_arg(self, name, args):
        idx = list(self.components.keys()).index(name)
        return args[idx]

    def add_updater(self, dest, srcs, conds):
        def fn(*args):
            truth_value = True
            for (src, cond) in zip(args, conds):
                truth_value = truth_value and (src == cond)

            return gr.update(visible=truth_value)
        
        for src in srcs:
            self.components[src].change(fn, inputs=[self.components[i] for i in srcs], outputs=self.components[dest])

    def bind(self, dest, src, cond):
        all_srcs, all_conds = [src], [cond]
        
        if src in self.bindings:
            for sub_src, sub_cond in self.bindings[src]:
                all_srcs.append(sub_src)
                all_conds.append(sub_cond)

        self.add_updater(dest, all_srcs, all_conds)
        
        if dest not in self.bindings: self.bindings[dest] = []
        for s, c in zip(all_srcs, all_conds):
                self.bindings[dest].append((s, c))


info = '''
# Giảm kích thước MNIST với học tập đa dạng

Đây là minh chứng về cách có thể sử dụng một số kỹ thuật [học đa dạng](https://scikit-learn.org/stable/modules/manifold.html) để giảm số chiều của tập dữ liệu MNIST từ 784 chiều xuống chỉ còn 2 hoặc 3 chiều cho mục đích trực quan.

Các kỹ thuật học đa dạng tìm cách tìm ra **biểu diễn chiều thấp** của dữ liệu đã cho sao cho các đặc tính nhất định được bảo toàn, chẳng hạn như cấu trúc cục bộ hoặc toàn cầu, khoảng cách lân cận, v.v.

Tất cả các phương pháp được sử dụng ở đây đều **hoàn toàn không được giám sát**, ngoại trừ Phân tích phân biệt tuyến tính và Phân tích thành phần lân cận, 

sử dụng nhãn chữ số được cung cấp. Mỗi phương pháp đều có ưu điểm và nhược điểm. Sử dụng hộp thả xuống bên dưới để chọn một phương pháp, điều chỉnh các siêu tham số của chúng và xem chúng khác nhau như thế nào.
'''

with gr.Blocks(analytics_enabled=False,theme=gr.themes.Soft()) as demo:
    gr.Markdown(info)
    
    with gr.Row():
        with gr.Column():
            ui = UserInterface()
            ui.add_component('algorithm', gr.Dropdown, {'choices': algorithms, 'value': algorithms[0], 'label': 'Model', 'interactive': True, 'visible': True})
            ui.add_component('n_components', gr.Radio, {'choices': ['2D', '3D'], 'value': '3D', 'label': 'Embedding dimensionality', 'visible': True})

            ui.add_component('n_neighbors', gr.Slider, {'minimum': 6, 'maximum': 100, 'value': 30, 'step': 1, 'label': 'Number of neighbors'})

            ui.add_component('tsne_perplexity', gr.Slider, {'minimum': 5, 'maximum': 50, 'value': 30, 'step': 1, 'label': 'Perplexity'})
            ui.add_component('tsne_early_exaggeration', gr.Slider, {'minimum': 2, 'maximum': 100, 'value': 12, 'step': 1, 'label': 'Early Exaggeration'})
            ui.add_component('tsne_n_iter', gr.Slider, {'minimum': 250, 'maximum': 2000, 'value': 1000, 'step': 1, 'label': 'Number of iterations'})
            ui.add_component('tsne_learning_rate_dd', gr.Dropdown, {'choices': ['auto', 'float'], 'value': 'auto', 'label': 'Learning Rate', 'interactive': True})
            ui.add_component('tsne_learning_rate_s', gr.Slider, {'minimum': 10, 'maximum': 2000, 'value': 100, 'step': 1, 'label': 'Learning Rate Value'})
            
            ui.add_component('isomap_p', gr.Slider, {'minimum': 1, 'maximum': 10, 'value': 2, 'step': 1, 'label': 'Minkowski distance Lp'})

            ui.add_component('lle_method', gr.Dropdown, {'choices': ['standard', 'hessian', 'modified', 'ltsa'], 'value': 'standard', 'label': 'Method', 'interactive': True})

            ui.add_component('rte_n_estimators', gr.Slider, {'minimum': 1, 'maximum': 200, 'value': 100, 'step': 1, 'label': 'Number of estimators'})
            ui.add_component('rte_max_depth', gr.Slider, {'minimum': 2, 'maximum': 50, 'value': 5, 'step': 1, 'label': 'Max depth'})

            ui.add_component('se_affinity', gr.Dropdown, {'choices': ['rbf', 'nearest_neighbors'], 'value': 'nearest_neighbors', 'label': 'Affinity matrix calculation method', 'interactive': True})
            ui.add_component('se_gamma', gr.Slider, {'minimum': 0.01, 'maximum': 10, 'value': 0.1, 'step': 0.05, 'label': 'Gamma'})
            ui.add_component('se_n_neighbors', gr.Slider, {'minimum': 6, 'maximum': 1000, 'value': 30, 'step': 1, 'label': 'Number of neighbors'})

            ui.add_component('nca_init', gr.Dropdown, {'choices': ['auto', 'pca', 'lda', 'identity', 'random'], 'value': 'auto', 'label': 'Initialization of the linear transformation', 'interactive': True})
            ui.add_component('nca_max_iter', gr.Slider, {'minimum': 5, 'maximum': 100, 'value': 50, 'step': 1, 'label': 'Maximum number of iterations'})


            #Bindings            
            
            ui.bind('tsne_early_exaggeration', 'algorithm', 't-SNE')
            ui.bind('tsne_perplexity', 'algorithm', 't-SNE')
            ui.bind('tsne_learning_rate_dd', 'algorithm', 't-SNE')
            ui.bind('tsne_learning_rate_s', 'tsne_learning_rate_dd', 'float')
            ui.bind('tsne_n_iter', 'algorithm', 't-SNE')

            ui.bind('n_neighbors', 'algorithm', 'Isomap')
            ui.bind('isomap_p', 'algorithm', 'Isomap')

            ui.bind('n_neighbors', 'algorithm', 'Locally Linear Embedding')
            ui.bind('lle_method', 'algorithm', 'Locally Linear Embedding')

            ui.bind('rte_n_estimators', 'algorithm', 'Random Trees Embedding')
            ui.bind('rte_max_depth', 'algorithm', 'Random Trees Embedding')

            ui.bind('se_affinity', 'algorithm', 'Spectral Embedding')
            ui.bind('se_n_neighbors', 'se_affinity', 'nearest_neighbors')
            ui.bind('se_gamma', 'se_affinity', 'rbf')

            ui.bind('nca_init', 'algorithm', 'Neighborhood Component Analysis')
            ui.bind('nca_max_iter', 'algorithm', 'Neighborhood Component Analysis')
            
            btn = gr.Button('Submit')
        
        with gr.Column():
            plot = gr.Plot(label='')
    
    def create_plot(*args):
        kwargs = ui.get_kwargs(args)

        algorithm = kwargs['algorithm']
        n_components = int(kwargs['n_components'][0])

        model = None
        data = X
        
        if algorithm == 'Linear Discriminant Analysis':
            data = X.copy()
            data.flat[:: X.shape[1] + 1] += 0.01 # Make X invertible
            model = LinearDiscriminantAnalysis()

        elif algorithm == 't-SNE':
            model = TSNE(n_jobs=-1)
            model.perplexity = kwargs['tsne_perplexity']
            model.early_exaggeration = kwargs['tsne_early_exaggeration']
            model.n_iter = kwargs['tsne_n_iter']
            model.learning_rate = 'auto' if (kwargs['tsne_learning_rate_dd'] == 'auto') else kwargs['tsne_learning_rate_s']
        
        elif algorithm == 'Truncated SVD':
            model = TruncatedSVD()

        elif algorithm == 'Isomap':
            model = Isomap(n_jobs=-1)
            model.n_neighbors = kwargs['n_neighbors']
            model.p = kwargs['isomap_p']
            
        elif algorithm == 'Locally Linear Embedding':
            model = LocallyLinearEmbedding(n_jobs=-1)
            model.n_neighbors = kwargs['n_neighbors']
            model.method = kwargs['lle_method']

        elif algorithm == 'Random Trees Embedding':
            model = make_pipeline(RandomTreesEmbedding(n_estimators=kwargs['rte_n_estimators'], max_depth=kwargs['rte_max_depth']), TruncatedSVD(n_components=n_components))

        elif algorithm == 'Spectral Embedding':
            model = SpectralEmbedding(n_jobs=-1)
            model.affinity = kwargs['se_affinity']
            model.gamma = kwargs['se_gamma']
            model.n_neighbors = kwargs['se_n_neighbors']

        elif algorithm == 'Neighborhood Component Analysis':
            model = NeighborhoodComponentsAnalysis()
            model.init = kwargs['nca_init']
            model.max_iter = kwargs['nca_max_iter']

        # ===================
        if algorithm != 'Random Trees Embedding':
            model.n_components = n_components

        projections = model.fit_transform(data, y)
        projections = MinMaxScaler().fit_transform(projections)

        fig = go.Figure()
    
        for digit in digits.target_names:
            subset = projections[y==digit]
            rgba = plt.cm.tab10(digit/10)
            color = f'rgba({rgba[0]}, {rgba[1]}, {rgba[2]}, 0.8)'
            if n_components == 2:
                fig.add_trace(go.Scatter(x=subset[:,0], y=subset[:,1], mode='text', text=str(digit), textfont={'size': 16, 'color': color}))
            elif n_components == 3:
                fig.add_trace(go.Scatter3d(x=subset[:,0], y=subset[:,1], z=subset[:,2], mode='text', text=str(digit), textfont={'size': 16, 'color': color}))
        
        fig.update_traces(showlegend=False)

        return fig

    btn.click(create_plot, ui.all_components(), plot)
    demo.load(create_plot, ui.all_components(), plot)

demo.launch()
# ====================================================================