DanOPT commited on
Commit
b0b4225
·
1 Parent(s): 5681904

Added app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -0
app.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ import os
5
+
6
+ # Heaviside step function
7
+ def heaviside_step(x):
8
+ return np.where(x >= 0, 1, 0)
9
+
10
+ # Perceptron Learning Algorithm with detailed logging
11
+ def perceptron_learning(X, D, w, learning_rate=0.1, max_epochs=100):
12
+ epoch_errors = []
13
+ weight_history = [w.copy()]
14
+ epoch = 0
15
+
16
+ print(f"Initial weights: {w}")
17
+ print(f"Learning rate: {learning_rate}")
18
+ print(f"Input patterns X:\n{X}")
19
+ print(f"Desired outputs D: {D}")
20
+
21
+ while epoch < max_epochs:
22
+ total_error = 0
23
+ print(f"\nEpoch {epoch + 1}")
24
+ for i in range(len(X)):
25
+ x_i = X[i]
26
+ d_i = D[i]
27
+ y_i = heaviside_step(np.dot(w, x_i))
28
+
29
+ error = d_i - y_i
30
+ total_error += abs(error)
31
+
32
+ print(f" Pattern {i + 1}: x = {x_i}, d = {d_i}, y = {y_i}, error = {error}")
33
+
34
+ if error != 0:
35
+ w_old = w.copy()
36
+ w = w + learning_rate * error * x_i
37
+ print(f" Weights updated: {w_old} -> {w}")
38
+ else:
39
+ print(" No weight update needed")
40
+
41
+ error_rate = (total_error / len(X)) * 100
42
+ epoch_errors.append(error_rate)
43
+ weight_history.append(w.copy())
44
+
45
+ print(f" Total error: {total_error}")
46
+ print(f" Error rate: {error_rate}%")
47
+ print(f" Current weights: {w}")
48
+
49
+ if total_error == 0:
50
+ print("Convergence achieved!")
51
+ break
52
+
53
+ epoch += 1
54
+
55
+ return w, np.array(weight_history), epoch_errors, epoch
56
+
57
+ # Plot Results
58
+ def plot_results(X, D, w_final, epoch_errors, weight_history):
59
+ fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(18, 6))
60
+
61
+ # Decision Boundary Plot
62
+ for i in range(len(D)):
63
+ color = 'blue' if D[i] == 1 else 'red'
64
+ label = '1' if D[i] == 1 and i == 0 else ('0' if D[i] == 0 and i == 1 else "")
65
+ ax1.scatter(X[i][1], X[i][2], color=color, label=label, s=100)
66
+
67
+ x1_vals = np.linspace(-0.5, 1.5, 100)
68
+ if w_final[2] != 0:
69
+ x2_vals = -(w_final[0] + w_final[1] * x1_vals) / w_final[2]
70
+ ax1.plot(x1_vals, x2_vals, label='Decision Boundary', color='green')
71
+ elif w_final[1] != 0:
72
+ ax1.axvline(x=-w_final[0] / w_final[1], color='k', linestyle='--', label='Vertical Decision Boundary')
73
+
74
+ ax1.set_xlim(-0.5, 1.5)
75
+ ax1.set_ylim(-0.5, 1.5)
76
+ ax1.set_title("Final Decision Boundary")
77
+ ax1.set_xlabel('x1')
78
+ ax1.set_ylabel('x2')
79
+ ax1.legend()
80
+ ax1.grid(True)
81
+
82
+ # Error Rate Plot
83
+ ax2.plot(range(len(epoch_errors)), epoch_errors, marker='o', linestyle='-', color='b')
84
+ ax2.set_title("Error Rate Over Epochs")
85
+ ax2.set_xlabel("Epoch")
86
+ ax2.set_ylabel("Error Rate (%)")
87
+ ax2.grid(True)
88
+
89
+ # Weight History Plot
90
+ epochs = range(len(weight_history))
91
+ ax3.plot(epochs, weight_history[:, 0], 'r', label='w0 (bias)')
92
+ ax3.plot(epochs, weight_history[:, 1], 'g', label='w1 (x1)')
93
+ ax3.plot(epochs, weight_history[:, 2], 'b', label='w2 (x2)')
94
+ ax3.set_title("Weight History")
95
+ ax3.set_xlabel("Epoch")
96
+ ax3.set_ylabel("Weight Value")
97
+ ax3.legend()
98
+ ax3.grid(True)
99
+
100
+ plt.tight_layout()
101
+ return fig
102
+
103
+ # Main function for running the perceptron
104
+ def run_perceptron(w0, w1, w2, learning_rate, max_epochs):
105
+ # Input patterns for OR operator
106
+ X = np.array([[1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]])
107
+ D = np.array([0, 1, 1, 1]) # Desired outputs
108
+
109
+ # Initial weights
110
+ w_initial = np.array([w0, w1, w2], dtype=float)
111
+
112
+ # Train the perceptron
113
+ w_final, weight_history, epoch_errors, epochs = perceptron_learning(X, D, w_initial, learning_rate, max_epochs)
114
+
115
+ # Plot the results
116
+ fig = plot_results(X, D, w_final, epoch_errors, weight_history)
117
+
118
+ # Save the figure to a file
119
+ if not os.path.exists('temp'):
120
+ os.makedirs('temp')
121
+ fig_path = 'temp/perceptron_results.png'
122
+ plt.savefig(fig_path, dpi=300, bbox_inches='tight')
123
+ plt.close(fig)
124
+
125
+ # Format weight history as a string
126
+ weight_history_str = "\n".join([f"Epoch {i}: {w}" for i, w in enumerate(weight_history)])
127
+
128
+ # Final summary
129
+ summary = f"Final weights: {w_final}\nConverged in {epochs} epochs"
130
+
131
+ return fig_path, summary, weight_history_str
132
+
133
+ # Gradio Interface
134
+ iface = gr.Interface(
135
+ fn=run_perceptron,
136
+ inputs=[
137
+ gr.Slider(-1, 1, 1, label="Initial w0 (bias)"),
138
+ gr.Slider(-1, 1, -1, label="Initial w1"),
139
+ gr.Slider(-1, 1, -1, label="Initial w2"),
140
+ gr.Slider(0.01, 1, 0.1, label="Learning Rate"),
141
+ gr.Slider(1, 1000, 100, step=1, label="Max Epochs")
142
+ ],
143
+ outputs=[
144
+ gr.Image(type="filepath", label="Results"),
145
+ gr.Textbox(label="Summary"),
146
+ gr.Textbox(label="Detailed Weight History", lines=10)
147
+ ],
148
+ title="Perceptron Learning for OR Operator",
149
+ description="Adjust the initial weights, learning rate, and maximum epochs to see how the perceptron learns the OR operator. You can download the graph or view it in fullscreen mode."
150
+ )
151
+
152
+ if __name__ == "__main__":
153
+ iface.launch()