import streamlit as st import pandas as pd import numpy as np from tensorflow.keras.models import Sequential, load_model from tensorflow.keras.layers import Dense from tensorflow.keras.utils import to_categorical from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split import pickle import matplotlib.pyplot as plt # Streamlit app setup st.title("Dynamic Fault Detection using Deep Learning") # Sidebar for configuration st.sidebar.title("Configuration") # Dynamic Dataset Handling uploaded_files = st.sidebar.file_uploader("Upload one or more datasets", accept_multiple_files=True, type=["xlsx"]) datasets = [] if uploaded_files: for uploaded_file in uploaded_files: data = pd.read_excel(uploaded_file) datasets.append(data) if datasets: combined_data = pd.concat(datasets, ignore_index=True) st.sidebar.header("Target Selection") target_column = st.sidebar.selectbox("Select the target column:", combined_data.columns) X = combined_data.drop(target_column, axis=1) y = combined_data[target_column] if y.dtype == 'object' or len(y.unique()) > 2: y = to_categorical(pd.factorize(y)[0]) test_size = st.sidebar.slider("Test Size (as %)", 10, 50, 20) / 100 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42) scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) with open("scaler.pkl", "wb") as f: pickle.dump(scaler, f) st.write("### Data Preview") st.write(combined_data.head()) num_layers = st.sidebar.slider("Number of Hidden Layers", 1, 5, 2) model = Sequential() model.add(Dense(st.sidebar.slider(f"Number of Neurons (Layer 1)", 1, 256, 64), input_shape=(X_train_scaled.shape[1],), activation=st.sidebar.selectbox(f"Activation Function (Layer 1)", ["relu", "sigmoid", "tanh"], index=0))) for i in range(1, num_layers): model.add(Dense(st.sidebar.slider(f"Number of Neurons (Layer {i+1})", 1, 256, 64), activation=st.sidebar.selectbox(f"Activation Function (Layer {i+1})", ["relu", "sigmoid", "tanh"], index=0))) model.add(Dense(y.shape[1], activation="softmax")) model.compile(optimizer=st.sidebar.selectbox("Optimizer", ["adam", "sgd", "rmsprop"], index=0), loss="categorical_crossentropy", metrics=["accuracy"]) st.write("### Model Summary") model.summary(print_fn=lambda x: st.text(x)) if st.sidebar.button("Train Model"): with st.spinner("Training in progress..."): history = model.fit(X_train_scaled, y_train, epochs=st.sidebar.slider("Epochs", 50, 100, 10), batch_size=st.sidebar.slider("Batch Size", 16, 128, 32), validation_split=0.2) st.success("Model trained successfully!") model.save("trained_model.h5") st.write("### Training History") st.line_chart({"Training Accuracy": history.history["accuracy"], "Validation Accuracy": history.history["val_accuracy"]}) test_loss, test_accuracy = model.evaluate(X_test_scaled, y_test) st.write(f"### Test Accuracy: {test_accuracy * 100:.2f}%") # Display total number of labels and distribution as a table label_counts = combined_data[target_column].value_counts().rename_axis('Label').reset_index(name='Counts') st.metric(label="Total Faults", value=label_counts['Counts'].sum()) st.write("### Fault Distribution") st.table(label_counts) # Prediction Section st.header("Make Predictions") feature_names = X.columns.tolist() if datasets else [] input_data = [st.number_input(f"Enter value for {feature}", step=0.0000001) for feature in feature_names] if st.button("Predict Fault Type"): loaded_model = load_model("trained_model.h5") loaded_scaler = pickle.load(open("scaler.pkl", "rb")) input_scaled = loaded_scaler.transform([input_data]) prediction = loaded_model.predict(input_scaled) predicted_class = np.argmax(prediction, axis=1)[0] st.success(f"The predicted fault class is: {predicted_class}") # Plot the entered data as a line graph plt.figure(figsize=(10, 2)) plt.plot(feature_names, input_data, marker='o') plt.title("Input Data Points") plt.xlabel("Features") plt.ylabel("Value") plt.grid(True) plt.xticks(rotation=45) st.pyplot(plt)