Koushikkatakam's picture
Update app.py
0757a20 verified
Raw History Blame Contribute Delete
9.34 kB
import streamlit as st
from keras.models import Sequential
import io
import mlxtend
import tensorflow as tf
tf.compat.v1.reset_default_graph()
from sklearn.datasets import make_regression
from sklearn.metrics import mean_squared_error
from mlxtend.plotting import plot_decision_regions
from keras.layers import InputLayer,Dense
from sklearn.datasets import make_classification,make_moons,make_circles
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler,MinMaxScaler
import warnings
warnings.filterwarnings('ignore', category=UserWarning, module='tensorflow')
# Create a sidebar
st.markdown("""
<h1 style="text-align: right; padding-right: 50px;">Decision Surface Creation</h1>
""", unsafe_allow_html=True)
st.sidebar.title('Select Model')
# Classification_checkbox = st.sidebar.checkbox('Classification Dataset')
# Moon_checkbox = st.sidebar.checkbox('Moons Dataset')
# circles_checkbox = st.sidebar.checkbox('circles Dataset')
# regression_checkbox = st.sidebar.checkbox('Regression Dataset')
options = ['select','make_classification', 'make_moons', 'make_circles','make_regression']
selected_option = st.sidebar.selectbox('Choose an option:', options)
# st.write(selected_option)
st.write('\n')
st.write('\n')
st.sidebar.title('Select Activation Function')
# activation_function = st.sidebar.text_input('Enter Activation Function for Hidden Layers')
activation_f = ['select','relu','tanh','sigmoid','linear']
activation_fv = st.sidebar.selectbox('Choose an option:', activation_f,index=0)
st.write('\n')
st.write('\n')
st.sidebar.title('Enter Number Of Ephocs')
epochs_number = st.sidebar.number_input('Enter Ephocs',
min_value=1,
max_value=2000,
step=1)
# epochs_number=int(epochs_number)
st.write('\n')
st.write('\n')
model=Sequential()
model.add(InputLayer(shape=(2,)))
st.sidebar.title('How many Hidden Layers want to create')
hidden_layers = st.sidebar.number_input('No of Hidden layers',
min_value=0,
max_value=50,
step=1)
# Adding hidden layers
for i in range(1, hidden_layers + 1):
n = st.sidebar.text_input(f'No of Neurons in Layer {i}', '2')
try:
n = int(n)
model.add(Dense(units=n, activation=activation_fv, use_bias=True))
# except ValueError:
# st.error(f"Error: '{n}' is not a valid number for neurons.")
except Exception as e:
st.error(f"Unexpected error: {e}")
if(selected_option!='make_regression'):
model.add(Dense(units=1, activation="sigmoid", use_bias=True))
else:
model.add(Dense(units=1, activation="linear", use_bias=True))
st.write('\n')
st.write('\n')
if st.sidebar.button('Submit'):
if selected_option=='make_circles':
# fv, cv = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, class_sep=4, random_state=10)
fv,cv = make_circles(n_samples=1000, noise=0.1, random_state=42)
elif selected_option=='make_classification':
fv, cv = make_classification(n_samples=1000, n_features=2, n_informative=2, n_redundant=0, n_repeated=0, n_classes=2, class_sep=4, random_state=10)
elif selected_option=='make_moons':
fv,cv = make_moons(n_samples=1000, noise=0.1, random_state=42)
if selected_option=='make_circles' or selected_option=='make_classificatiion' or selected_option=='make_moons':
plt.figure(figsize=(10, 6))
sns.scatterplot(x=fv[:, 0], y=fv[:, 1], hue=cv, palette='viridis')
plt.title('Scatter Plot of Classification Dataset')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
st.pyplot(plt)
# Model summary
buffer = io.StringIO()
model.summary(print_fn=lambda x: buffer.write(x + '\n'))
summary_str = buffer.getvalue()
st.write("### Model Summary")
st.write("```\n" + summary_str + "\n```")
# Split data
x_train, x_test, y_train, y_test = train_test_split(fv, cv, test_size=0.2, random_state=20, stratify=cv)
std = StandardScaler()
x_traint = std.fit_transform(x_train)
x_testt = std.transform(x_test)
# Progress bar
progress_bar = st.progress(0)
status_text = st.empty()
# Train model
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
# history = model.fit(x_traint, y_train, epochs=epochs_number, batch_size=20, validation_split=0.2, verbose=0,
# callbacks=[tf.keras.callbacks.LambdaCallback(on_epoch_end=lambda epoch, logs: progress_bar.progress((epoch + 1) / epochs_number))])
# history = model.fit(x_train, y_train, epochs=epochs_number, batch_size=20, validation_split=0.2, verbose=0,callbacks=[
# tf.keras.callbacks.LambdaCallback(
# on_epoch_end=lambda epoch, logs: progress_bar.progress(int((epoch + 1) / epochs_number * 100))
# )])
def update_progress(epoch, logs):
progress = (epoch + 1) / epochs_number
progress_bar.progress(progress)
status_text.text(f"Training Progress: {int(progress * 100)}%")
# Train the model with the custom callback
history = model.fit(x_traint, y_train, epochs=epochs_number, batch_size=20, validation_split=0.2, verbose=0,callbacks=[tf.keras.callbacks.LambdaCallback(on_epoch_end=update_progress)])
# Training and Validation Loss Plot
st.subheader('Training and Validation Loss')
fig_loss = plt.figure()
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
st.pyplot(fig_loss)
# Decision boundaries plots
# Plot decision boundaries on training data
fig_train_boundary, ax = plt.subplots()
plot_decision_regions(X=x_traint, y=y_train, clf=model, ax=ax)
plt.title('Decision Boundary on Training Data')
st.pyplot(fig_train_boundary)
# Plot decision boundaries on test data
fig_test_boundary, ax = plt.subplots()
plot_decision_regions(X=x_testt, y=y_test, clf=model, ax=ax)
plt.title('Decision Boundary on Test Data')
st.pyplot(fig_test_boundary)
if selected_option=='make_regression':
# Generate regression data
# Generate regression data
fv, cv = make_regression(n_samples=1000, n_features=2, noise=0.1, random_state=42)
# st.write('fv',fv)
# st.write('cv',cv)
# Scatter Plot of Regression Data
plt.figure(figsize=(10, 6))
plt.scatter(fv[:, 0], fv[:, 1], c=cv, cmap='viridis', edgecolor='k') # Add edgecolor for better visibility
plt.title('Scatter Plot of Regression Dataset')
plt.xlabel('Feature 1')
plt.ylabel('Feature 2')
st.pyplot(plt)
# Model summary
buffer = io.StringIO()
model.summary(print_fn=lambda x: buffer.write(x + '\n'))
summary_str = buffer.getvalue()
st.write("### Model Summary")
st.write("```\n" + summary_str + "\n```")
# Split data
x_train, x_test, y_train, y_test = train_test_split(fv, cv, test_size=0.2, random_state=20)
std = StandardScaler()
x_traint = std.fit_transform(x_train)
x_testt = std.transform(x_test)
# Progress bar
progress_bar = st.progress(0)
# Train model
model.compile(optimizer="adam", loss="mean_squared_error", metrics=["mean_squared_error"]) # Use 'adam' for better convergence
history = model.fit(x_traint, y_train, epochs=epochs_number, batch_size=20, validation_split=0.2, verbose=0,
callbacks=[tf.keras.callbacks.LambdaCallback(on_epoch_end=lambda epoch, logs: progress_bar.progress((epoch + 1) / epochs_number))])
# Training and Validation Loss Plot
st.subheader('Training and Validation Loss')
fig_loss = plt.figure()
plt.plot(history.history['loss'], label='Training Loss')
plt.plot(history.history['val_loss'], label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
st.pyplot(fig_loss)
# # Predictions
# y_train_pred = model.predict(x_traint)
# y_test_pred = model.predict(x_testt)
# st.write('x_train',x_traint.shape)
# st.write('y_train',y_train.shape)
# # st.write('x_test',x_test.shape)
# # st.write('y_test',y_test.shape)
# st.write('y_train_pred',y_train_pred.shape)
# # st.write('y_test_pred',y_test_pred.shape)
# fig_train = plt.figure()
# plt.ylim(0, 100) # Example limits
# plt.scatter(x_traint[:,0], y_train, color='b', label='Actual')
# plt.plot(x_traint, y_train_pred, 'r', label='Prediction')
# plt.xlabel('Feature')
# plt.ylabel('Target')
# plt.legend()
# st.pyplot(fig_train)