ZainKhan007 commited on
Commit
cde4c10
·
verified ·
1 Parent(s): 6f624ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -56
app.py CHANGED
@@ -1,74 +1,101 @@
1
- import gradio as gr
2
  import pandas as pd
3
  import numpy as np
4
- from tensorflow.keras.models import Sequential
5
  from tensorflow.keras.layers import Dense
6
  from tensorflow.keras.utils import to_categorical
7
  from sklearn.preprocessing import StandardScaler
8
  from sklearn.model_selection import train_test_split
9
  import pickle
 
10
 
11
- def load_and_prepare_data(uploaded_files):
12
- datasets = [pd.read_excel(file) for file in uploaded_files]
13
- combined_data = pd.concat(datasets, ignore_index=True)
14
- return combined_data
 
15
 
16
- def build_and_train_model(combined_data, target_column, num_layers, neurons_per_layer, activations, optimizer, epochs, batch_size, test_size):
17
- X = combined_data.drop(target_column, axis=1)
18
- y = combined_data[target_column]
19
 
20
- if y.dtype == 'object' or len(y.unique()) > 2:
21
- y = to_categorical(pd.factorize(y)[0])
 
22
 
23
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size/100, random_state=42)
24
- scaler = StandardScaler()
25
- X_train_scaled = scaler.fit_transform(X_train)
26
- X_test_scaled = scaler.transform(X_test)
27
 
28
- model = Sequential()
29
- model.add(Dense(neurons_per_layer[0], activation=activations[0], input_shape=(X_train_scaled.shape[1],)))
30
- for neurons, activation in zip(neurons_per_layer[1:], activations[1:]):
31
- model.add(Dense(neurons, activation=activation))
32
- model.add(Dense(y.shape[1], activation='softmax'))
33
 
34
- model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
35
- history = model.fit(X_train_scaled, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2)
36
- evaluation = model.evaluate(X_test_scaled, y_test)
37
- accuracy = evaluation[1] * 100
 
 
 
 
 
 
38
 
39
- return model, scaler, accuracy, history.history
 
 
 
 
40
 
41
- def predict(model, scaler, input_features):
42
- input_scaled = scaler.transform([input_features])
43
- prediction = model.predict(input_scaled)
44
- predicted_class = np.argmax(prediction, axis=1)[0]
45
- return predicted_class
46
 
47
- def main(uploaded_files, target_column, num_layers, neurons, activations, optimizer, epochs, batch_size, test_size, input_features):
48
- combined_data = load_and_prepare_data(uploaded_files)
49
- model, scaler, accuracy, history = build_and_train_model(combined_data, target_column, num_layers, neurons, activations, optimizer, epochs, batch_size, test_size)
50
- predicted_class = predict(model, scaler, input_features)
51
- return predicted_class, accuracy, history
 
 
52
 
53
- iface = gr.Interface(
54
- fn=main,
55
- inputs=[
56
- gr.inputs.File(label="Upload one or more datasets", type="file", accept_multiple_files=True),
57
- gr.inputs.Textbox(label="Target Column Name"),
58
- gr.inputs.Slider(label="Number of Hidden Layers", minimum=1, maximum=5),
59
- gr.inputs.Number(label="Neurons per Layer", default=64),
60
- gr.inputs.Dropdown(label="Activation Functions", choices=["relu", "sigmoid", "tanh"], type="index"),
61
- gr.inputs.Dropdown(label="Optimizer", choices=["adam", "sgd", "rmsprop"]),
62
- gr.inputs.Slider(label="Epochs", minimum=10, maximum=100),
63
- gr.inputs.Slider(label="Batch Size", minimum=10, maximum=100),
64
- gr.inputs.Slider(label="Test Size (%)", minimum=10, maximum=50),
65
- gr.inputs.Number(label="Input Features for Prediction")
66
- ],
67
- outputs=[
68
- gr.outputs.Textbox(label="Predicted Class"),
69
- gr.outputs.Textbox(label="Model Accuracy"),
70
- gr.outputs.Label(label="Training History")
71
- ]
72
- )
73
 
74
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
  import pandas as pd
3
  import numpy as np
4
+ from tensorflow.keras.models import Sequential, load_model
5
  from tensorflow.keras.layers import Dense
6
  from tensorflow.keras.utils import to_categorical
7
  from sklearn.preprocessing import StandardScaler
8
  from sklearn.model_selection import train_test_split
9
  import pickle
10
+ import matplotlib.pyplot as plt
11
 
12
+ # Initialize session state variables
13
+ if 'model_path' not in st.session_state:
14
+ st.session_state['model_path'] = None
15
+ if 'scaler_path' not in st.session_state:
16
+ st.session_state['scaler_path'] = None
17
 
18
+ st.title("Dynamic Fault Detection Dashboard")
 
 
19
 
20
+ # File uploader
21
+ uploaded_files = st.file_uploader("Upload one or more datasets", accept_multiple_files=True, type=["xlsx"])
22
+ data_frames = []
23
 
24
+ if uploaded_files:
25
+ for uploaded_file in uploaded_files:
26
+ data = pd.read_excel(uploaded_file)
27
+ data_frames.append(data)
28
 
29
+ if data_frames:
30
+ combined_data = pd.concat(data_frames, ignore_index=True)
31
+ st.write("### Data Preview", combined_data.head())
 
 
32
 
33
+ # Configuration sidebar
34
+ with st.sidebar:
35
+ target_column = st.selectbox("Select the target column:", combined_data.columns)
36
+ num_layers = st.slider("Number of Hidden Layers", 1, 5, 2)
37
+ neurons = [st.slider(f"Neurons in Layer {i+1}", 10, 256, 64) for i in range(num_layers)]
38
+ activations = [st.selectbox(f"Activation Function for Layer {i+1}", ["relu", "sigmoid", "tanh"], index=0) for i in range(num_layers)]
39
+ optimizer = st.selectbox("Optimizer", ["adam", "sgd", "rmsprop"])
40
+ epochs = st.slider("Epochs", 50, 100, 10)
41
+ batch_size = st.slider("Batch Size", 1, 128, 32)
42
+ test_size = st.slider("Test Size (%)", 5, 40, 20)
43
 
44
+ # Preparing data
45
+ X = combined_data.drop(target_column, axis=1)
46
+ y = combined_data[target_column]
47
+ if y.dtype == 'object' or len(y.unique()) > 2:
48
+ y = to_categorical(pd.factorize(y)[0])
49
 
50
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size/100, random_state=42)
51
+ scaler = StandardScaler()
52
+ X_train_scaled = scaler.fit_transform(X_train)
53
+ X_test_scaled = scaler.transform(X_test)
 
54
 
55
+ # Define and compile the model
56
+ model = Sequential()
57
+ model.add(Dense(neurons[0], activation=activations[0], input_shape=(X_train_scaled.shape[1],)))
58
+ for layer_neurons, layer_activation in zip(neurons[1:], activations[1:]):
59
+ model.add(Dense(layer_neurons, activation=layer_activation))
60
+ model.add(Dense(y.shape[1], activation='softmax'))
61
+ model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
62
 
63
+ # Train button
64
+ if st.button("Train Model"):
65
+ with st.spinner('Model training in progress...'):
66
+ history = model.fit(X_train_scaled, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2)
67
+ st.success('Model trained successfully!')
68
+ model.save('dynamic_model.h5')
69
+ scaler_path = 'dynamic_scaler.pkl'
70
+ with open(scaler_path, 'wb') as f:
71
+ pickle.dump(scaler, f)
72
+ st.session_state['model_path'] = 'dynamic_model.h5'
73
+ st.session_state['scaler_path'] = scaler_path
 
 
 
 
 
 
 
 
 
74
 
75
+ # Show training history
76
+ st.line_chart(history.history['accuracy'])
77
+ st.line_chart(history.history['val_accuracy'])
78
+
79
+ # Evaluate the model
80
+ evaluation = model.evaluate(X_test_scaled, y_test)
81
+ st.metric("Accuracy", f"{evaluation[1]*100:.2f}%")
82
+
83
+ # Prediction part
84
+ st.subheader("Make Predictions")
85
+ if st.session_state['model_path'] and st.session_state['scaler_path']:
86
+ model = load_model(st.session_state['model_path'])
87
+ scaler = pickle.load(open(st.session_state['scaler_path'], 'rb'))
88
+
89
+ input_data = [st.number_input(f"Input {feature}", step=0.0001) for feature in X.columns]
90
+ if st.button("Predict"):
91
+ input_scaled = scaler.transform([input_data])
92
+ prediction = model.predict(input_scaled)
93
+ predicted_class = np.argmax(prediction, axis=1)[0]
94
+ st.success(f"Predicted Fault Class: {predicted_class}")
95
+
96
+ # Additional visualizations
97
+ fig, ax = plt.subplots()
98
+ if not y.empty:
99
+ y.value_counts().plot(kind='bar', ax=ax)
100
+ ax.set_title("Distribution of Target Class")
101
+ st.pyplot(fig)