File size: 2,388 Bytes
cc6dcfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# Generate synthetic data
def generate_data(num_points=1000):
    np.random.seed(0)
    X = np.random.randn(num_points, 2)
    y = (X[:, 0]**2 + X[:, 1]**2 < 1).astype(int)
    return X, y

# Create the model
def create_model(input_shape, learning_rate, activation, hidden_layers):
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.InputLayer(input_shape=input_shape))
    for neurons in hidden_layers:
        model.add(tf.keras.layers.Dense(neurons, activation=activation))
    model.add(tf.keras.layers.Dense(1, activation='sigmoid'))
    
    model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
                  loss='binary_crossentropy',
                  metrics=['accuracy'])
    return model

# Plot decision boundary
def plot_decision_boundary(model, X, y):
    x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1),
                         np.arange(y_min, y_max, 0.1))
    grid = np.c_[xx.ravel(), yy.ravel()]
    probs = model.predict(grid).reshape(xx.shape)
    
    plt.contourf(xx, yy, probs, alpha=0.8)
    plt.scatter(X[:, 0], X[:, 1], c=y, edgecolor='k', marker='o')
    st.pyplot(plt.gcf())

def main():
    st.title("Interactive Neural Network Training")
    
    # Sidebar inputs
    learning_rate = st.sidebar.slider("Learning rate", 0.001, 0.1, 0.03)
    activation = st.sidebar.selectbox("Activation function", ["relu", "tanh", "sigmoid"])
    num_hidden_layers = st.sidebar.slider("Number of hidden layers", 1, 5, 2)
    neurons_per_layer = st.sidebar.slider("Neurons per layer", 1, 10, 4)
    batch_size = st.sidebar.slider("Batch size", 1, 100, 10)
    num_epochs = st.sidebar.slider("Number of epochs", 1, 1000, 100)
    
    hidden_layers = [neurons_per_layer] * num_hidden_layers
    
    X, y = generate_data()
    
    model = create_model(input_shape=(2,), learning_rate=learning_rate, activation=activation, hidden_layers=hidden_layers)
    model.fit(X, y, epochs=num_epochs, batch_size=batch_size, validation_split=0.5, verbose=0)
    
    st.write("Training complete")
    
    fig, ax = plt.subplots()
    plot_decision_boundary(model, X, y)
    st.pyplot(fig)

if __name__ == "__main__":
    main()