ZainKhan007 commited on
Commit
1d644b2
·
verified ·
1 Parent(s): 448d4c4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -50
app.py CHANGED
@@ -14,8 +14,9 @@ st.title("Dynamic Fault Detection Dashboard")
14
 
15
  # Sidebar for configuration
16
  st.sidebar.title("Configuration")
17
- uploaded_files = st.sidebar.file_uploader("Upload one or more datasets", accept_multiple_files=True, type=["xlsx"])
18
 
 
 
19
  datasets = []
20
  if uploaded_files:
21
  for uploaded_file in uploaded_files:
@@ -23,67 +24,59 @@ if uploaded_files:
23
  datasets.append(data)
24
 
25
  if datasets:
 
26
  combined_data = pd.concat(datasets, ignore_index=True)
27
- target_column = st.sidebar.selectbox("Select the target column:", combined_data.columns)
28
 
 
 
 
 
29
  X = combined_data.drop(target_column, axis=1)
30
- y = pd.factorize(combined_data[target_column])[0]
31
- y = to_categorical(y)
 
32
 
33
- test_size = st.sidebar.slider("Test Size (as %)", 10, 50, 20) / 100
34
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42)
35
-
36
  scaler = StandardScaler()
37
  X_train_scaled = scaler.fit_transform(X_train)
38
  X_test_scaled = scaler.transform(X_test)
39
-
40
- with open("scaler.pkl", "wb") as f:
41
- pickle.dump(scaler, f)
42
-
43
- st.write("### Data Preview")
44
- st.write(combined_data.head())
45
-
46
- num_layers = st.sidebar.number_input("Number of Hidden Layers", min_value=1, max_value=10, value=2)
47
  model = Sequential()
48
- model.add(Dense(st.sidebar.slider("Number of Neurons (Layer 1)", 1, 256, 64), input_shape=(X_train_scaled.shape[1],), activation=st.sidebar.selectbox("Activation Function (Layer 1)", ["relu", "sigmoid", "tanh"])))
 
49
  for i in range(1, num_layers):
50
- model.add(Dense(st.sidebar.slider("Number of Neurons (Layer {i+1})", 1, 256, 64), activation=st.sidebar.selectbox(f"Activation Function (Layer {i+1})", ["relu", "sigmoid", "tanh"])))
 
51
  model.add(Dense(y.shape[1], activation='softmax'))
52
-
53
- model.compile(optimizer=st.sidebar.selectbox("Optimizer", ["adam", "sgd", "rmsprop"]), loss='categorical_crossentropy', metrics=['accuracy'])
54
-
 
55
  if st.sidebar.button("Train Model"):
56
- with st.spinner("Training in progress..."):
57
- 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)
58
- model.save("trained_model.h5")
59
  st.success("Model trained successfully!")
60
- test_loss, test_accuracy = model.evaluate(X_test_scaled, y_test)
61
- st.write(f"### Test Accuracy: {test_accuracy * 100:.2f}%")
62
-
63
- # Display common target values without a graph
64
- most_common = pd.Series(combined_data[target_column]).value_counts().head(5)
65
- st.write("### Most Common Target Values")
66
- st.write(most_common)
67
 
68
- # Prediction Section
69
- st.header("Make Predictions")
70
- feature_names = X.columns.tolist() if datasets else []
71
- input_data = [st.number_input(f"Enter value for {feature}", step=0.000001) for feature in feature_names]
72
 
73
- if st.button("Predict Fault Type"):
74
- loaded_model = load_model("trained_model.h5")
75
- loaded_scaler = pickle.load(open("scaler.pkl", "rb"))
76
- input_scaled = loaded_scaler.transform([input_data])
77
- prediction = loaded_model.predict(input_scaled)
78
- predicted_class = np.argmax(prediction, axis=1)[0]
79
- st.success(f"The predicted fault class is: {predicted_class}")
80
 
81
- # Plot the entered values as a line chart
82
- plt.figure(figsize=(10, 4))
83
- plt.plot(feature_names, input_data, marker='o')
84
- plt.title("Visualization of Input Features")
85
- plt.xlabel("Features")
86
- plt.ylabel("Values")
87
- plt.xticks(rotation=45)
88
- plt.grid(True)
89
- st.pyplot(plt)
 
14
 
15
  # Sidebar for configuration
16
  st.sidebar.title("Configuration")
 
17
 
18
+ # Dynamic Dataset Handling
19
+ uploaded_files = st.sidebar.file_uploader("Upload one or more datasets", accept_multiple_files=True, type=["xlsx"])
20
  datasets = []
21
  if uploaded_files:
22
  for uploaded_file in uploaded_files:
 
24
  datasets.append(data)
25
 
26
  if datasets:
27
+ # Combine all uploaded datasets into one DataFrame
28
  combined_data = pd.concat(datasets, ignore_index=True)
29
+ st.write("### Data Preview", combined_data.head())
30
 
31
+ # Select target column dynamically
32
+ target_column = st.sidebar.selectbox("Select the target column", combined_data.columns)
33
+
34
+ # Prepare the data
35
  X = combined_data.drop(target_column, axis=1)
36
+ y = combined_data[target_column]
37
+ if y.dtype == 'object' or len(y.unique()) > 2:
38
+ y = pd.get_dummies(y) # One-hot encode the target variable
39
 
40
+ # Data splitting and scaling
41
+ test_size = st.sidebar.slider("Test Size (as %)", min_value=10, max_value=90, value=20, step=5)
42
+ X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size/100, random_state=42)
43
  scaler = StandardScaler()
44
  X_train_scaled = scaler.fit_transform(X_train)
45
  X_test_scaled = scaler.transform(X_test)
46
+
47
+ # Model Configuration
48
+ num_layers = st.sidebar.slider("Number of Hidden Layers", min_value=1, max_value=5, value=2)
 
 
 
 
 
49
  model = Sequential()
50
+ first_layer_neurons = st.sidebar.slider("Neurons in First Layer", min_value=10, max_value=256, step=10, value=50)
51
+ model.add(Dense(first_layer_neurons, activation='relu', input_shape=(X_train_scaled.shape[1],)))
52
  for i in range(1, num_layers):
53
+ neurons = st.sidebar.slider(f"Neurons in Layer {i+1}", min_value=10, max_value=256, step=10, value=50)
54
+ model.add(Dense(neurons, activation='relu'))
55
  model.add(Dense(y.shape[1], activation='softmax'))
56
+
57
+ model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
58
+
59
+ # Model Training
60
  if st.sidebar.button("Train Model"):
61
+ epochs = st.sidebar.slider("Number of Epochs", 10, 100, 50)
62
+ batch_size = st.sidebar.slider("Batch Size", 10, 100, 20)
63
+ history = model.fit(X_train_scaled, y_train, epochs=epochs, batch_size=batch_size, validation_split=0.2)
64
  st.success("Model trained successfully!")
 
 
 
 
 
 
 
65
 
66
+ # Display accuracy and loss graphs
67
+ st.line_chart(history.history['accuracy'])
68
+ st.line_chart(history.history['val_accuracy'])
 
69
 
70
+ # Prediction Section
71
+ if st.button("Make Predictions"):
72
+ input_features = [st.number_input(f"Input {col}", step=0.01) for col in X.columns]
73
+ input_scaled = scaler.transform([input_features])
74
+ prediction = model.predict(input_scaled)
75
+ predicted_class = np.argmax(prediction, axis=1)
76
+ st.write(f"Predicted Fault Class: {predicted_class}")
77
 
78
+ # Visualizing input data distribution
79
+ fig, ax = plt.subplots()
80
+ combined_data[target_column].value_counts().plot(kind='bar', ax=ax)
81
+ ax.set_title("Distribution of Target Variable")
82
+ st.pyplot(fig)