deep-matter commited on
Commit
2ec702c
·
1 Parent(s): 7d3e256

Upload 6 files

Browse files
Files changed (6) hide show
  1. README.md +2 -9
  2. app.py +50 -0
  3. demo.py +246 -0
  4. init.py +5 -0
  5. requirements.txt +16 -0
  6. uilit.py +135 -0
README.md CHANGED
@@ -1,13 +1,6 @@
1
  ---
2
- title: Nano AutoGrad
3
- emoji: 📊
4
- colorFrom: red
5
- colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 3.35.2
8
- app_file: app.py
9
- pinned: false
10
- license: creativeml-openrail-m
11
  ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Nano-AutoGrad
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 3.35.2
 
 
 
6
  ---
 
 
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from demo import *
3
+
4
+
5
+
6
+ article = """
7
+ <p style='text-align: center'>
8
+ <a href='https://github.com/deep-matter/Nano-AutoGrad' target='_blank'>Github Repo Nano-AutoGrad</a>
9
+ </p>
10
+ """
11
+
12
+ iface_webcam = gr.Interface(
13
+ Optimization_training_progress_realtime,
14
+ inputs=[
15
+ gr.Radio(["Sparsity"], label="Task"),
16
+ gr.Slider(minimum=1, maximum=100, label="Number of Epochs"),
17
+ gr.Slider(minimum=0.01, maximum=1.0, label="Learning Rate"),
18
+ gr.Number(label="Number of Layers"),
19
+ gr.Number(label="Values for Weights")
20
+ # gr.inputs.Slider(minimum=6, maximum=18, step=6, default=12), # Leaving manual fps out for now
21
+ ],
22
+ outputs=[gr.Plot(),gr.Video(),gr.Video()],
23
+ title="Optimization Training Progress",
24
+ description="Real-time visualization of training progress",
25
+ article=article,
26
+ allow_flagging=False,
27
+ )
28
+
29
+ iface_file = gr.Interface(
30
+ Optimization_training_progress_realtime,
31
+ inputs=[
32
+ gr.Radio(["Classification"], label="Task"),
33
+ gr.Slider(minimum=1, maximum=100, label="Number of Epochs"),
34
+ gr.Slider(minimum=0.01, maximum=1.0, label="Learning Rate"),
35
+ gr.Number(label="Number of Layers"),
36
+ gr.Number(label="Values for Weights")
37
+ ],
38
+ outputs=[gr.Plot(),gr.Video(),gr.Video()],
39
+ title="Optimization Training Progress",
40
+ description="Real-time visualization of training progress",
41
+ article=article,
42
+ allow_flagging=False,
43
+ )
44
+
45
+ if __name__ == '__main__':
46
+ gr.TabbedInterface(
47
+ interface_list=[iface_file, iface_webcam],
48
+ tab_names=["Classification Task", "Sparsity Task"]
49
+
50
+ ).launch(enable_queue=True,share=True)
demo.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from init import *
2
+ import random
3
+ import numpy as np
4
+ from autograd.core.engine import Value
5
+ from autograd.core.nn import Neuron, Layer, MLP
6
+ from autograd.core.Graph import draw_dot
7
+ import time
8
+ from graphviz import Digraph
9
+ import imageio
10
+ from functools import partial
11
+ import matplotlib.animation as animation
12
+ import shutil
13
+ from IPython.display import HTML
14
+ import os
15
+ import pandas as pd
16
+ import plotly.subplots as sp
17
+ import plotly.express as px
18
+ import plotly.graph_objects as go
19
+ from plotly.subplots import make_subplots
20
+ import matplotlib.pyplot as plt
21
+ from matplotlib.animation import FuncAnimation ,FFMpegWriter
22
+ import matplotlib.pyplot as plt
23
+ from uilit import *
24
+ os.environ["PATH"] += os.pathsep + './dev/lib/Python 3.11/site-packages/graphviz'
25
+
26
+ path_data = 'digit-recognizer/data/'
27
+
28
+
29
+
30
+ # loss function
31
+ def loss(model,X_train , y_train , batch_size=None):
32
+
33
+ # inline DataLoader :)
34
+ if batch_size is None:
35
+ Xb, yb = X_train, y_train
36
+ else:
37
+ ri = np.random.permutation(X_train.shape[0])[:batch_size]
38
+ Xb, yb = X_train[ri], y_train[ri]
39
+
40
+ inputs = [list(map(Value, xrow)) for xrow in Xb]
41
+
42
+ # forward the model to get scores
43
+ scores = list(map(model, inputs))
44
+
45
+ # svm "max-margin" loss
46
+ losses = [(1 + -yi*scorei).relu() for yi, scorei in zip(yb, scores)]
47
+ data_loss = sum(losses) * (1.0 / len(losses))
48
+ # L2 regularization
49
+ alpha = 0.05
50
+ reg_loss = alpha * sum((p*p for p in model.parameters()))
51
+ total_loss = data_loss + reg_loss
52
+
53
+ # also get accuracy
54
+ accuracy = [(yi > 0) == (scorei.data > 0) for yi, scorei in zip(yb, scores)]
55
+ return total_loss, sum(accuracy) / len(accuracy) ,scores
56
+
57
+ def Optimization_training_progress_realtime(Task,num_epoch, learning_rate ,num_layer,values_wieghts):
58
+ filename = f"assets/plot_res_{num_epoch-1}.png"
59
+ filename_ = f"assets/graph_wights_update_{num_epoch-1}.png"
60
+ if os.path.exists(filename) or os.path.exists(filename_):
61
+ shutil.rmtree('assets/')
62
+ os.makedirs('assets/')
63
+ # Create empty lists for loss and accuracy
64
+ loss_data = []
65
+ accuracy_data = []
66
+ model = MLP(int(num_layer), [int(values_wieghts),int(values_wieghts),1]) # 2-layer neural network
67
+ # Create subplots with shared x-axis
68
+ fig = make_subplots(rows=2, cols=1, shared_xaxes=True, subplot_titles=("Loss", "Accuracy"))
69
+
70
+ # Initialize empty lists for loss and accuracy
71
+ loss_data = []
72
+ accuracy_data = []
73
+
74
+ # Create initial empty traces
75
+ loss_trace = go.Scatter(x=[], y=[], mode="lines", name="Loss")
76
+ accuracy_trace = go.Scatter(x=[], y=[], mode="lines", name="Accuracy")
77
+
78
+ # Add initial traces to the subplots
79
+ fig.add_trace(loss_trace, row=1, col=1)
80
+ fig.add_trace(accuracy_trace, row=2, col=1)
81
+ # Update layout
82
+ fig.update_layout(
83
+ title="Training Progress",
84
+ xaxis_title="Epoch",
85
+ yaxis=dict(title="Loss"),
86
+ yaxis2=dict(title="Accuracy"),
87
+ showlegend=False,
88
+ hovermode='x',
89
+ height=500,
90
+ width=500,
91
+ template='plotly_white'
92
+ )
93
+ # Define animation frames
94
+ frames = []
95
+ if Task in "Sparsity":
96
+ X_train , Y_train = initialize_data(n_samples=100 ,noise=0.1)
97
+
98
+ elif Task in "Classification":
99
+ FILES , _ = extract_path_df(path_data,10)
100
+ X_train, X_test, Y_train, Y_test = loading_df_to_numpy(FILES[0])
101
+ for k in range(int(num_epoch)):
102
+ # Forward pass
103
+ total_loss, acc,scores = loss(model, X_train, Y_train, batch_size=None)
104
+
105
+ # Backward pass
106
+ model.zero_grad()
107
+ total_loss.backward()
108
+ draw_dot(model(scores),f'graph_wights_update_{k}')
109
+
110
+ # Update (SGD)
111
+
112
+ learning_rate = 1.0 - 0.9 * k / 100
113
+
114
+ for p in model.parameters():
115
+ p.data -= learning_rate * p.grad
116
+
117
+ if k % 2 == 0:
118
+ print(f"step {k} loss {total_loss.data}, accuracy {acc*100}%")
119
+
120
+ # Append data to lists
121
+ loss_data.append(total_loss.data)
122
+ accuracy_data.append(acc)
123
+
124
+ # Update traces
125
+ with fig.batch_update():
126
+ fig.data[0].x = list(range(k+1))
127
+ fig.data[0].y = loss_data
128
+ fig.data[1].x = list(range(k+1))
129
+ fig.data[1].y = accuracy_data
130
+
131
+ # Append current frame to frames list
132
+ frames.append(go.Frame(data=[fig.data[0], fig.data[1]]))
133
+
134
+ if Task in "Sparsity":
135
+ h = 0.25
136
+ x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
137
+ y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
138
+ xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
139
+ np.arange(y_min, y_max, h))
140
+
141
+ Xmesh = np.c_[xx.ravel(), yy.ravel()]
142
+ inputs = [list(map(Value, xrow)) for xrow in Xmesh]
143
+ scores = list(map(model, inputs))
144
+ Z = np.array([s.data > 0 for s in scores])
145
+ Z = Z.reshape(xx.shape)
146
+
147
+ plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
148
+ plt.scatter(X_train[:, 0], X_train[:, 1], c=Y_train, s=40, cmap=plt.cm.Spectral)
149
+ plt.xlim(xx.min(), xx.max())
150
+ plt.ylim(yy.min(), yy.max())
151
+ plt.savefig(f'assets/plot_res_{k}.png')
152
+ # Add frames to animation
153
+ fig.frames = frames
154
+ nframes = int(num_epoch)
155
+ interval = int(num_epoch) * 2
156
+
157
+ # Create animation
158
+ animation = go.Figure(fig)
159
+
160
+ # Set animation settings
161
+ animation.update_layout(
162
+ updatemenus=[
163
+ {
164
+ "buttons": [
165
+ {
166
+ "args": [None, {"frame": {"duration": 500, "redraw": True},
167
+ "fromcurrent": True, "transition": {"duration": 0}}],
168
+ "label": "Play",
169
+ "method": "animate"
170
+ }
171
+ ],
172
+ "showactive": False,
173
+ "type": "buttons"
174
+ }
175
+ ]
176
+ )
177
+
178
+ # Display animation
179
+ # Save animation as GIF
180
+
181
+ if Task in "Sparsity":
182
+ graph_trace("graph_wights_update", nframes,interval)
183
+ fig_2 = plt.figure()
184
+ def animate_predicion(i):
185
+ im1 = plt.imread(f"assets/plot_res_{i}.png")
186
+ plt.imshow(im1)
187
+ plt.title(f"Epoch: {i+1}\nLoss: {loss_data[i]:.4f} - Accuracy: {accuracy_data[i]:.4f}")
188
+ plt.xlabel("prediction")
189
+ plt.axis('off')
190
+
191
+ fig_2.tight_layout()
192
+
193
+ lin_ani = FuncAnimation(fig_2, animate_predicion, frames=nframes, interval=200)
194
+ FFwriter = FFMpegWriter(fps=10)
195
+
196
+ lin_ani.save('out/training.mp4', writer=FFwriter)
197
+ # Display the animation
198
+ # Show the figure
199
+ return animation ,'out/training.mp4', 'out/Graph.mp4'
200
+
201
+ if Task in "Classification":
202
+ graph_trace("graph_wights_update", nframes,interval)
203
+ inputs_test = [list(map(Value, xrow)) for xrow in X_test]
204
+ predictions = [scorei.data.argmax() for scorei in list(map(model, inputs_test))]
205
+
206
+ # Plot a few examples
207
+ num_examples = 8
208
+ fig_1, axes = plt.subplots(2, 2, figsize=(12, 6))
209
+ fig_1.subplots_adjust(hspace=0.4, wspace=0.4)
210
+
211
+ def animate(i):
212
+ for j, ax in enumerate(axes.flatten()):
213
+ if j < num_examples:
214
+ random_index = random.randint(0, X_test.shape[1] - 1)
215
+ ax.imshow(X_test[:, random_index, None].reshape(28, 28), cmap="gray")
216
+ ax.set_title(f"Predicted: {Y_test[random_index]}")
217
+ ax.axis('off')
218
+ else:
219
+ ax.axis('off')
220
+
221
+ fig_1.tight_layout()
222
+
223
+ lin_ani = FuncAnimation(fig_1, animate, frames=nframes, interval=200)
224
+ FFwriter = FFMpegWriter(fps=10)
225
+
226
+ lin_ani.save('out/Predicted.mp4', writer=FFwriter)
227
+ # fig_1.savefig("reulst.png")
228
+ return animation , 'out/Predicted.mp4', 'out/Graph.mp4'
229
+
230
+
231
+
232
+
233
+
234
+
235
+ if __name__ == "__main__":
236
+
237
+ np.random.seed(1337)
238
+ random.seed(1337)
239
+ models = Optimization_training_progress_realtime(
240
+ Task="Sparsity",num_epoch=5, learning_rate=0.002 ,
241
+ num_layer=2,values_wieghts=4)
242
+
243
+
244
+
245
+
246
+
init.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ # Add the parent directory of app.py to the system path
4
+ parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
5
+ sys.path.append(parent_dir)
requirements.txt ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pandas
2
+ plotly
3
+ numpy
4
+ matplotlib
5
+ random2
6
+ scipy
7
+ scikit-learn
8
+ kaleido
9
+ ipython
10
+ nbformat>=4.2.0
11
+ ipywidgets>=7.0.0
12
+ imageio
13
+ graphviz
14
+ gradio
15
+ nano-autograds
16
+ sphinx
uilit.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from init import *
2
+ import numpy as np
3
+ import pandas as pd
4
+ import matplotlib.pyplot as plt
5
+ import os
6
+ from PIL import Image
7
+
8
+ import matplotlib.animation as animation
9
+ from matplotlib.animation import FuncAnimation
10
+ from IPython.display import clear_output
11
+ from autograd.core.engine import Value
12
+ from sklearn.datasets import make_moons, make_blobs
13
+ import plotly.graph_objects as go
14
+ import plotly.io as pio
15
+ import imageio
16
+
17
+ clear_output()
18
+
19
+ # Iterate through the first 6 images
20
+
21
+ def extract_path_df(path_dir, index_show):
22
+ path_file = []
23
+
24
+ for filesname in os.listdir(path_dir):
25
+ path_file.append(os.path.join(path_dir,filesname))
26
+
27
+ for data_df in range(0,len(path_file)):
28
+ data_frame = pd.read_csv(path_file[data_df])
29
+ show_df = data_frame.head(index_show)
30
+ return path_file , f"dataframe: {show_df}"
31
+
32
+ def loading_df_to_numpy(path_file):
33
+ data_df = pd.read_csv(path_file)
34
+ data = np.array(data_df)
35
+ m, n = data.shape
36
+ data_train = data[1000:m].T
37
+ Y_train = data_train[0][40900:]
38
+ X_train = data_train[1:n][:, 40900:]
39
+
40
+
41
+ # Manually split the data into training and testing sets
42
+ split_index = int(X_train.shape[0] * 0.8) # 80% for training, 20% for testing
43
+ X_train_split = X_train[:, :10]
44
+ Y_train_split = Y_train[:10]
45
+ X_test_split = X_train[:,:5]
46
+ Y_test_split = Y_train[:5]
47
+
48
+ return X_train_split, X_test_split, Y_train_split, Y_test_split
49
+
50
+ def initialize_data(n_samples: int, noise: float):
51
+ input_data, Target = make_moons(n_samples=n_samples, noise=noise)
52
+
53
+ Target = Target * 2 - 1 # make y be -1 or 14
54
+ # fig.close()
55
+ return input_data, Target
56
+
57
+
58
+ def plot_sample(DATA_TRAIN,DATA_LABEL):
59
+ num_images = min(6, DATA_TRAIN.shape[1])
60
+ fig, axs = plt.subplots(2, 3, figsize=(10, 7))
61
+
62
+ for i in range(num_images):
63
+ label = DATA_LABEL
64
+ image = DATA_TRAIN[:, i]
65
+ current_image = image.reshape(28, 28) * 255
66
+
67
+ # Determine the subplot coordinates
68
+ row = i // 3
69
+ col = i % 3
70
+
71
+ # Plot the image in the corresponding subplot
72
+ axs[row, col].imshow(current_image, cmap='gray')
73
+ axs[row, col].set_title("Label: {}".format(label))
74
+ axs[row, col].axis('off')
75
+
76
+ plt.tight_layout()
77
+ plt.savefig("sample.png")
78
+
79
+ def copy(model):
80
+ model = SparseMLP(nin=2, nouts=[16, 16, 1], sparsities=[0.,0.9,0.8])
81
+ model.parameters()
82
+ return model
83
+
84
+ def Zvals(model , X_train):
85
+ global X
86
+ h = 0.25
87
+ x_min, x_max = X_train[:, 0].min() - 1, X_train[:, 0].max() + 1
88
+ y_min, y_max = X_train[:, 1].min() - 1, X_train[:, 1].max() + 1
89
+ xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
90
+ np.arange(y_min, y_max, h))
91
+ Xmesh = np.c_[xx.ravel(), yy.ravel()]
92
+ inputs = [list(map(Value, xrow)) for xrow in Xmesh]
93
+ scores = list(map(model, inputs))
94
+ Z = np.array([s.data > 0 for s in scores])
95
+ Z = Z.reshape(xx.shape)
96
+ return Z
97
+
98
+
99
+ def dboundary(model):
100
+ global X
101
+ global Y
102
+ h = 0.25
103
+ x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
104
+ y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
105
+ xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
106
+ np.arange(y_min, y_max, h))
107
+ Xmesh = np.c_[xx.ravel(), yy.ravel()]
108
+ fig, ax = plt.subplots(figsize=(8,8))
109
+ Z = Zvals(model)
110
+ ln = ax.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
111
+ ax.scatter(X[:, 0], X[:, 1], c=Y, s=40, cmap=plt.cm.Spectral)
112
+ ax.set_xlim(xx.min(), xx.max())
113
+ ax.set_ylim(yy.min(), yy.max())
114
+ return fig,ax,ln
115
+
116
+ def graph_trace(Path, nframes, interval):
117
+ animation_frames = []
118
+ # Load the first image to get its dimensions and color mode
119
+ first_frame_path = f"assets/{Path}_0.png"
120
+ first_image = Image.open(first_frame_path)
121
+ width, height = first_image.size
122
+ color_mode = first_image.mode
123
+
124
+ # Resize and convert all the images to the same dimensions and color mode
125
+ resized_width = 900 # Set your desired width
126
+ resized_height = 700 # Set your desired height
127
+
128
+ for i in range(nframes):
129
+ frame_path = f"assets/{Path}_{i}.png"
130
+ image = Image.open(frame_path)
131
+ resized_image = image.resize((resized_width, resized_height)).convert(color_mode)
132
+ animation_frames.append(resized_image)
133
+
134
+ animation_path = "out/Graph.mp4"
135
+ imageio.mimsave(animation_path, animation_frames, format="mp4")