girishwangikar commited on
Commit
ae06a1e
1 Parent(s): f580df6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -0
app.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from sklearn.linear_model import LinearRegression
5
+ from sklearn.tree import DecisionTreeClassifier, plot_tree
6
+ from sklearn.cluster import KMeans
7
+
8
+ def plot_neural_network():
9
+ fig, ax = plt.subplots(figsize=(10, 6))
10
+ ax.set_title("Simple Neural Network")
11
+
12
+ layer_sizes = [4, 5, 3, 1]
13
+ layer_positions = [1, 2, 3, 4]
14
+
15
+ for i, layer_size in enumerate(layer_sizes):
16
+ for j in range(layer_size):
17
+ circle = plt.Circle((layer_positions[i], j*2), 0.2, fill=False)
18
+ ax.add_artist(circle)
19
+
20
+ if i < len(layer_sizes) - 1:
21
+ for k in range(layer_sizes[i+1]):
22
+ ax.plot([layer_positions[i], layer_positions[i+1]], [j*2, k*2], 'gray', alpha=0.5)
23
+
24
+ ax.set_xlim(0, 5)
25
+ ax.set_ylim(-1, 9)
26
+ ax.axis('off')
27
+ return fig
28
+
29
+ def plot_linear_regression():
30
+ x = np.linspace(0, 10, 100).reshape(-1, 1)
31
+ y = 2 * x + 1 + np.random.randn(100, 1) * 2
32
+
33
+ model = LinearRegression()
34
+ model.fit(x, y)
35
+
36
+ fig, ax = plt.subplots(figsize=(10, 6))
37
+ ax.scatter(x, y, color='blue', alpha=0.5)
38
+ ax.plot(x, model.predict(x), color='red', linewidth=2)
39
+ ax.set_title("Linear Regression")
40
+ ax.set_xlabel("X")
41
+ ax.set_ylabel("Y")
42
+ return fig
43
+
44
+ def plot_kmeans():
45
+ X = np.random.randn(300, 2) * 0.5
46
+ X[:100] += np.array([2, 2])
47
+ X[100:200] += np.array([-2, 2])
48
+ X[200:] += np.array([0, -2])
49
+
50
+ kmeans = KMeans(n_clusters=3)
51
+ kmeans.fit(X)
52
+
53
+ fig, ax = plt.subplots(figsize=(10, 6))
54
+ scatter = ax.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')
55
+ ax.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1],
56
+ marker='x', s=200, linewidths=3, color='r')
57
+ ax.set_title("K-Means Clustering")
58
+ ax.set_xlabel("Feature 1")
59
+ ax.set_ylabel("Feature 2")
60
+ return fig
61
+
62
+ def plot_decision_tree():
63
+ X = np.random.randn(100, 2)
64
+ y = (X[:, 0] + X[:, 1] > 0).astype(int)
65
+
66
+ clf = DecisionTreeClassifier(max_depth=3, random_state=42)
67
+ clf.fit(X, y)
68
+
69
+ fig, ax = plt.subplots(figsize=(12, 8))
70
+ plot_tree(clf, filled=True, feature_names=['Feature 1', 'Feature 2'], class_names=['Class 0', 'Class 1'], ax=ax)
71
+ ax.set_title("Decision Tree")
72
+ return fig
73
+
74
+ def visualize_algorithm(algorithm):
75
+ if algorithm == "Neural Network":
76
+ fig = plot_neural_network()
77
+ description = "A neural network is a series of algorithms that endeavors to recognize underlying relationships in a set of data through a process that mimics the way the human brain operates. This visualization shows a simple neural network with an input layer (4 neurons), two hidden layers (5 and 3 neurons), and an output layer (1 neuron)."
78
+ elif algorithm == "Linear Regression":
79
+ fig = plot_linear_regression()
80
+ description = "Linear regression is a linear approach to modeling the relationship between a scalar response and one or more explanatory variables. This plot shows a scatter plot of data points and the best-fit line found by linear regression."
81
+ elif algorithm == "K-Means Clustering":
82
+ fig = plot_kmeans()
83
+ description = "K-Means clustering is an unsupervised learning algorithm that attempts to group similar data points into K clusters. This visualization shows the result of K-Means clustering on a 2D dataset with 3 clusters. The 'x' markers represent the cluster centers."
84
+ elif algorithm == "Decision Tree":
85
+ fig = plot_decision_tree()
86
+ description = "A decision tree is a flowchart-like structure in which each internal node represents a test on an attribute, each branch represents the outcome of the test, and each leaf node represents a class label. This visualization shows a decision tree with a maximum depth of 3. The color intensity of each node represents the majority class at that node."
87
+ else:
88
+ fig = plt.figure()
89
+ description = "Invalid algorithm selected."
90
+
91
+ return fig, description
92
+
93
+ iface = gr.Interface(
94
+ fn=visualize_algorithm,
95
+ inputs=gr.Dropdown(["Neural Network", "Linear Regression", "K-Means Clustering", "Decision Tree"], label="Choose an algorithm"),
96
+ outputs=[
97
+ gr.Plot(label="Visualization"),
98
+ gr.Textbox(label="Description")
99
+ ],
100
+ title="Machine Learning Algorithm Visualizer",
101
+ description="Select an algorithm to visualize and learn about:",
102
+ theme="huggingface",
103
+ allow_flagging="never"
104
+ )
105
+
106
+ if __name__ == "__main__":
107
+ iface.launch()