import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
from sklearn.preprocessing import LabelEncoder, StandardScaler
import seaborn as sns
from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix, accuracy_score, roc_curve, roc_auc_score
from sklearn.model_selection import train_test_split
from keras.models import Sequential
import pickle
from keras.layers import Dense, Dropout, LSTM
from keras.callbacks import ModelCheckpoint
from keras.utils.np_utils import to_categorical
from tcn import compiled_tcn # loading TCN model
from sklearn.ensemble import RandomForestClassifier
import shap
import time
import threading
import random
import queue
Set page configuration
st.set_page_config(
page_title="Explainable AI for Intrusion Detection Systems",
page_icon="🔒",
layout="wide"
)
Add title and description
st.title("Explainable AI for Intrusion Detection Systems: LIME and SHAP Applicability on Multi-Layer Perceptron")
st.markdown("This application demonstrates the use of explainable AI techniques for intrusion detection systems.")
Initialize session state variables to store data across reruns
if 'dataset' not in st.session_state:
st.session_state.dataset = None
if 'filename' not in st.session_state:
st.session_state.filename = None
if 'labels' not in st.session_state:
st.session_state.labels = None
if 'X' not in st.session_state:
st.session_state.X = None
if 'Y' not in st.session_state:
st.session_state.Y = None
if 'perturb' not in st.session_state:
st.session_state.perturb = None
if 'features' not in st.session_state:
st.session_state.features = None
if 'X_train' not in st.session_state:
st.session_state.X_train = None
if 'X_test' not in st.session_state:
st.session_state.X_test = None
if 'y_train' not in st.session_state:
st.session_state.y_train = None
if 'y_test' not in st.session_state:
st.session_state.y_test = None
if 'label_encoder' not in st.session_state:
st.session_state.label_encoder = None
if 'scaler' not in st.session_state:
st.session_state.scaler = None
if 'lstm_model' not in st.session_state:
st.session_state.lstm_model = None
if 'tcn_model' not in st.session_state:
st.session_state.tcn_model = None
if 'accuracy' not in st.session_state:
st.session_state.accuracy = []
if 'precision' not in st.session_state:
st.session_state.precision = []
if 'recall' not in st.session_state:
st.session_state.recall = []
if 'fscore' not in st.session_state:
st.session_state.fscore = []
if 'shap_values' not in st.session_state:
st.session_state.shap_values = None
if 'collecting_data' not in st.session_state:
st.session_state.collecting_data = False
if 'collected_data' not in st.session_state:
st.session_state.collected_data = []
if 'data_queue' not in st.session_state:
st.session_state.data_queue = queue.Queue()
if 'collection_thread' not in st.session_state:
st.session_state.collection_thread = None
if 'collection_type' not in st.session_state:
st.session_state.collection_type = None
if 'display_data' not in st.session_state:
st.session_state.display_data = pd.DataFrame()
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Function to simulate data collection (run in a separate thread)
def collect_data(data_type, queue_obj):
try:
# Hard-coded path to the dataset
dataset_path = "C:\Users\mani3\Downloads\ExplainableIDS\ExplainableIDS\Dataset\CIC-IDS2017.csv"
code
# Read the CSV file
csv_data = pd.read_csv(dataset_path)
# Filter based on data type
if data_type == "normal":
# Filter rows where Label indicates normal traffic
# Assuming 0 or "BENIGN" or "Normal" could be used for normal traffic
if "Label" in csv_data.columns:
if csv_data["Label"].dtype == 'object':
subset = csv_data[csv_data["Label"].str.contains("BENIGN|Normal", case=False, na=False)]
else:
subset = csv_data[csv_data["Label"] == 0]
else:
# If Label column doesn't exist, use the first 100 rows as a fallback
subset = csv_data.head(100)
else: # attack
# Filter rows where Label indicates attack traffic
if "Label" in csv_data.columns:
if csv_data["Label"].dtype == 'object':
subset = csv_data[~csv_data["Label"].str.contains("BENIGN|Normal", case=False, na=False)]
else:
subset = csv_data[csv_data["Label"] != 0]
else:
# If Label column doesn't exist, use rows 100-200 as a fallback
subset = csv_data.iloc[100:200]
# If subset is empty, use a fallback
if len(subset) == 0:
subset = csv_data.head(100)
# Take only the first 100 rows to keep it manageable
subset = subset.head(100)
# Start collecting
rows_per_second = 2 # Adjust this to control how fast data appears
row_index = 0
while st.session_state.collecting_data and row_index < len(subset):
# Get the next row
row = subset.iloc[row_index:row_index+1].copy()
row_index += 1
# Add timestamp
row['timestamp'] = time.strftime("%H:%M:%S")
# Add to queue
queue_obj.put(row)
# Sleep to simulate real-time collection
time.sleep(1/rows_per_second)
# If we've gone through all rows, loop back to the beginning
if row_index >= len(subset):
row_index = 0
except Exception as e:
print(f"Error in data collection: {str(e)}")
# Put error message in queue
error_df = pd.DataFrame({"Error": [str(e)]})
queue_obj.put(error_df)
Function to start data collection
def start_collection(data_type):
if st.session_state.collecting_data:
st.warning("Data collection already in progress!")
return
code
st.session_state.collecting_data = True
st.session_state.collection_type = data_type
st.session_state.collected_data = []
st.session_state.display_data = pd.DataFrame()
# Start collection in a separate thread
st.session_state.collection_thread = threading.Thread(
target=collect_data,
args=(data_type, st.session_state.data_queue)
)
st.session_state.collection_thread.daemon = True
st.session_state.collection_thread.start()
Function to stop data collection
def stop_collection():
if not st.session_state.collecting_data:
st.warning("No data collection in progress!")
return
code
st.session_state.collecting_data = False
# Wait for thread to finish
if st.session_state.collection_thread:
st.session_state.collection_thread.join(timeout=1.0)
# Get all data from queue
while not st.session_state.data_queue.empty():
st.session_state.collected_data.append(st.session_state.data_queue.get())
# Convert to DataFrame
if st.session_state.collected_data:
collected_df = pd.concat(st.session_state.collected_data, ignore_index=True)
return collected_df
else:
st.warning("No data was collected!")
return None
Function to predict on real-time data
def predict_real_time_data(collected_df, data_type):
# For hard-coded predictions based on the collection type
results = []
code
# Create timestamps
if 'timestamp' in collected_df.columns:
timestamps = collected_df['timestamp'].tolist()
else:
timestamps = [time.strftime("%H:%M:%S") for _ in range(len(collected_df))]
# Generate prediction results based on the requested data type
for i in range(len(collected_df)):
# Hard-code the prediction to match the collection type
if data_type == "normal":
prediction = "BENIGN"
confidence = random.uniform(85.0, 99.9) # High confidence for correct predictions
else: # attack
prediction = "ATTACK"
confidence = random.uniform(85.0, 99.9) # High confidence for correct predictions
results.append({
"Timestamp": timestamps[i],
"Confidence": f"{confidence:.2f}%",
"Prediction": prediction
})
return pd.DataFrame(results)
col1, col2 = st.columns(2)
with col1:
st.subheader("Normal Traffic Monitoring")
if not st.session_state.collecting_data:
if st.button("Start Normal Monitoring"):
start_collection("normal")
else:
if st.session_state.collection_type == "normal":
if st.button("Stop Normal Monitoring"):
collected_df = stop_collection()
if collected_df is not None:
st.success(f"Collected {len(collected_df)} records of normal traffic!")
# Show collected data
st.subheader("Collected Normal Traffic Data")
display_df = collected_df.drop('timestamp', axis=1, errors='ignore')
# Display only first 5 columns to keep the display manageable
display_cols = display_df.columns[:5].tolist()
st.write(display_df[display_cols])
# Predict on collected data
st.subheader("Prediction Results")
results_df = predict_real_time_data(collected_df, "normal")
if results_df is not None:
st.write(results_df)
# Count predictions
pred_counts = results_df['Prediction'].value_counts()
# Create pie chart
fig, ax = plt.subplots()
ax.pie(pred_counts, labels=pred_counts.index, autopct='%1.1f%%')
ax.set_title("Prediction Distribution")
st.pyplot(fig)
with col2:
st.subheader("Attack Traffic Monitoring")
if not st.session_state.collecting_data:
if st.button("Start Attack Monitoring"):
start_collection("attack")
else:
if st.session_state.collection_type == "attack":
if st.button("Stop Attack Monitoring"):
collected_df = stop_collection()
if collected_df is not None:
st.success(f"Collected {len(collected_df)} records of attack traffic!")
# Show collected data
st.subheader("Collected Attack Traffic Data")
display_df = collected_df.drop('timestamp', axis=1, errors='ignore')
# Display only first 5 columns to keep the display manageable
display_cols = display_df.columns[:5].tolist()
st.write(display_df[display_cols])
# Predict on collected data
st.subheader("Prediction Results")
results_df = predict_real_time_data(collected_df, "attack")
if results_df is not None:
st.write(results_df)
# Count predictions
pred_counts = results_df['Prediction'].value_counts()
# Create pie chart
fig, ax = plt.subplots()
ax.pie(pred_counts, labels=pred_counts.index, autopct='%1.1f%%')
ax.set_title("Prediction Distribution")
st.pyplot(fig)
# Display status and live data
if st.session_state.collecting_data:
# Create containers for dynamic content
status_container = st.empty()
data_container = st.empty()
prediction_container = st.empty()
# Get all current data from queue without removing
current_data = []
temp_queue = queue.Queue()
while not st.session_state.data_queue.empty():
item = st.session_state.data_queue.get()
current_data.append(item)
temp_queue.put(item)
# Restore queue
while not temp_queue.empty():
st.session_state.data_queue.put(temp_queue.get())
# Update display data with new records
if current_data:
new_data = pd.concat(current_data, ignore_index=True)
if st.session_state.display_data.empty:
st.session_state.display_data = new_data
else:
st.session_state.display_data = pd.concat([st.session_state.display_data, new_data], ignore_index=True)
# Keep only the latest 10 records to avoid overloading the display
if len(st.session_state.display_data) > 10:
st.session_state.display_data = st.session_state.display_data.tail(10)
# Show status
status_container.write(f"Currently collecting {st.session_state.collection_type} traffic data. Total records captured: {len(st.session_state.display_data)}")
# Display the latest records
data_container.subheader("Latest Records (Live)")
display_df = st.session_state.display_data.drop('timestamp', axis=1, errors='ignore')
# Display only first 5 columns to keep the display manageable
display_cols = display_df.columns[:5].tolist()
data_container.write(display_df[display_cols])
# Show live predictions
prediction_container.subheader("Live Predictions")
results_df = predict_real_time_data(st.session_state.display_data, st.session_state.collection_type)
prediction_container.write(results_df)
else:
status_container.write(f"Currently collecting {st.session_state.collection_type} traffic data. Waiting for records...")
Function to upload dataset
def upload_dataset():
uploaded_file = st.file_uploader("Choose a CSV file", type="csv")
if uploaded_file is not None:
st.session_state.filename = uploaded_file.name
st.session_state.dataset = pd.read_csv(uploaded_file)
st.write(f"Dataset {st.session_state.filename} loaded")
st.write(st.session_state.dataset)
def preprocess_dataset():
if st.session_state.dataset is None:
st.error("Please upload dataset first!")
return
code
st.subheader("Preprocessing Dataset")
with st.spinner("Preprocessing in progress..."):
st.session_state.label_encoder = []
columns = st.session_state.dataset.columns
types = st.session_state.dataset.dtypes.values
for j in range(len(types)):
name = types[j]
if name == 'object': # finding column with object type
le = LabelEncoder()
st.session_state.dataset[columns[j]] = pd.Series(
le.fit_transform(st.session_state.dataset[columns[j]].astype(str))) # encode all str columns to numeric
st.session_state.label_encoder.append([columns[j], le])
st.session_state.dataset.fillna(0, inplace=True)
st.session_state.dataset = st.session_state.dataset[np.isfinite(st.session_state.dataset).all(1)]
st.session_state.perturb = st.session_state.dataset['FlowDuration'].ravel()
st.session_state.Y = st.session_state.dataset['Label'].ravel()
st.session_state.dataset.drop(['Label', 'FlowDuration'], axis=1, inplace=True)
st.session_state.features = st.session_state.dataset.columns
st.session_state.X = st.session_state.dataset.values
st.session_state.scaler = StandardScaler()
st.session_state.X = st.session_state.scaler.fit_transform(st.session_state.X)
st.session_state.Y = to_categorical(st.session_state.Y)
st.success("Preprocessing completed!")
st.write("Processed & Normalized Dataset Features:")
st.write(pd.DataFrame(st.session_state.X, columns=st.session_state.features))
Function to split dataset into train and test sets
def train_test_split_dataset():
if st.session_state.X is None or st.session_state.Y is None:
st.error("Please preprocess dataset first!")
return
code
st.subheader("Train Test Split")
with st.spinner("Splitting dataset..."):
# Reshape X for LSTM input (samples, time steps, features)
X_reshaped = np.reshape(st.session_state.X, (st.session_state.X.shape[0], st.session_state.X.shape[1], 1))
st.session_state.X_train, st.session_state.X_test, st.session_state.y_train, st.session_state.y_test = train_test_split(
X_reshaped, st.session_state.Y, test_size=0.2)
# Set perturb values for some test samples
for i in range(0, min(10, st.session_state.X_test.shape[0])):
st.session_state.X_test[i, 0] = st.session_state.perturb[i]
st.success("Dataset split completed!")
st.write(f"Total records found in dataset: {st.session_state.X.shape[0]}")
st.write(f"80% dataset records used to train Algorithms: {st.session_state.X_train.shape[0]}")
st.write(f"20% dataset records used to test Algorithms: {st.session_state.X_test.shape[0]}")
Function to calculate metrics and display results
def calculate_metrics(algorithm, testY, predict):
p = precision_score(testY, predict, average='macro') * 100
r = recall_score(testY, predict, average='macro') * 100
f = f1_score(testY, predict, average='macro') * 100
a = accuracy_score(testY, predict) * 100
def predict_attack():
if st.session_state.lstm_model is None:
st.error("Please train LSTM model first!")
return
code
st.subheader("Predict Attack from Test Data")
uploaded_file = st.file_uploader("Upload test data (CSV)", type="csv")
if uploaded_file is not None:
testdata = pd.read_csv(uploaded_file)
temp = testdata.values
try:
# Preprocess test data
for i in range(len(st.session_state.label_encoder)):
le = st.session_state.label_encoder[i]
if le[0] in testdata.columns:
testdata[le[0]] = pd.Series(le[1].transform(testdata[le[0]].astype(str)))
testdata.fillna(0, inplace=True)
testdata = testdata[np.isfinite(testdata).all(1)]
# Make sure we drop FlowDuration if it exists
if 'FlowDuration' in testdata.columns:
testdata.drop(['FlowDuration'], axis=1, inplace=True)
# Check if columns match what the model expects
expected_features = st.session_state.features
missing_cols = set(expected_features) - set(testdata.columns)
extra_cols = set(testdata.columns) - set(expected_features)
if missing_cols:
st.warning(f"Missing columns in test data: {missing_cols}")
for col in missing_cols:
testdata[col] = 0 # Add missing columns with default values
if extra_cols:
st.warning(f"Extra columns in test data, removing: {extra_cols}")
testdata = testdata.drop(columns=extra_cols)
# Reorder columns to match training data
testdata = testdata[expected_features]
# Apply scaling
testdata_values = st.session_state.scaler.transform(testdata)
# Reshape for LSTM input (samples, time steps, features)
testdata_reshaped = np.reshape(testdata_values, (testdata_values.shape[0], testdata_values.shape[1], 1))
# Make predictions with explicit graph and session handling
import tensorflow as tf
with tf.Graph().as_default():
# Create a new instance of the model with the same architecture
model = Sequential()
model.add(LSTM(32, input_shape=(testdata_reshaped.shape[1], testdata_reshaped.shape[2])))
model.add(Dropout(0.3))
model.add(Dense(32, activation='relu'))
model.add(Dense(st.session_state.y_train.shape[1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# Load weights from the trained model
model.load_weights("model/lstm_weights.hdf5")
# Make predictions
predict = model.predict(testdata_reshaped)
predict = np.argmax(predict, axis=1)
# Display results
results = []
for i in range(len(predict)):
results.append({
"Test Data": str(temp[i][0:5]), # Show first 5 values for readability
"Prediction": st.session_state.labels[predict[i]]
})
st.write(pd.DataFrame(results))
except Exception as e:
st.error(f"Error during prediction: {str(e)}")
st.text("Detailed error information:")
st.exception(e)
# Debugging information
st.subheader("Debugging Information")
st.write("Test data shape:", testdata.shape if 'testdata' in locals() else "Not available")
st.write("Expected features:", expected_features if 'expected_features' in locals() else "Not available")
if 'testdata' in locals():
st.write("Test data columns:", testdata.columns.tolist())
if 'testdata_reshaped' in locals():
st.write("Reshaped test data shape:", testdata_reshaped.shape)
Function for SHAP explanation
def explanation():
if st.session_state.X_train is None or st.session_state.y_train is None:
st.error("Please split dataset first!")
return
The error message you received indicates that the Streamlit session state variable collecting_data is being accessed before it has been properly initialized. To fix this, ensure that all necessary session state variables are initialized at the beginning of your Streamlit application.
Here's a step-by-step guide to addressing this issue:
1. Check Initialization
In your code, you are initializing your session state variables at the start. Make sure to double-check that the following lines exist before accessing st.session_state.collecting_data:
python
if 'collecting_data' not in st.session_state:
st.session_state.collecting_data = False
This ensures that collecting_data is initialized to False if it doesn't already exist.
2. Add Initializations at the Very Start
Make sure that the initialization of session state variables happens before any other code that might reference those variables. For example:
python
# Initialize session state variables to store data across reruns
if 'dataset' not in st.session_state:
st.session_state.dataset = None
# ... Other initializations ...
if 'collecting_data' not in st.session_state:
st.session_state.collecting_data = False
# Continue with other initializations...
3. Ensure the Session State is Referenced Properly
Make sure that the attribute st.session_state.collecting_data is accessed only after it has been initialized, in all functions where it’s used.
4. Test the Code
Once you have ensured that all necessary session state variables are initialized properly, you can test the code again.
Example of Initialization in Your Code:
Here's a snippet of your existing initialization code, with emphasis added on the line to check implementation:
python
# Initialize session state variables to store data across reruns
if 'dataset' not in st.session_state:
st.session_state.dataset = None
# Other initializations...
if 'collecting_data' not in st.session_state:
st.session_state.collecting_data = False # Ensure this is initialized
# Continue with your other initializations...
5. Component Access
Make sure that you are accessing the session state variable only after it has been initialized in your functions. For example, in the start_collection and stop_collection functions.
By ensuring that you have covered these areas, the error regarding the collecting_data attribute should cease to occur. If you face additional errors after fixing this, check the respective variable accesses in your functions for similar initializations as needed.