Talha1218's picture
Update app.py
0e9a22f verified
Raw History Blame Contribute Delete
7.23 kB
import streamlit as st
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score
# File uploader for CSV
uploaded_file = st.file_uploader("Upload CSV File", type=["csv"])
if uploaded_file is not None:
# Read CSV file into DataFrame
df = pd.read_csv(uploaded_file)
# Show data preview and column names for debugging
st.write("Data Preview:")
st.write(df.head())
# Display column names for debugging
st.write("Columns in the uploaded file:")
st.write(df.columns)
# Check if 'Network_Type' exists and 'MR_Level' exists
if 'Network_Type' in df.columns:
# Convert 'Network Type' to numeric
df['Network_Type'] = df['Network_Type'].map({'2G': 0, '3G': 1, '4G': 2, '5G': 3})
else:
st.error("Error: 'Network_Type' column not found in the uploaded file.")
if 'MR_Level' in df.columns:
# Create coverage categories based on MR_Level
def coverage_category(mr_level):
if mr_level >= -65:
return 'Good'
elif -75 <= mr_level < -65:
return 'Medium'
else:
return 'Poor'
# Apply coverage category function to the dataset
df['Coverage'] = df['MR_Level'].apply(coverage_category)
else:
st.error("Error: 'MR_Level' column not found in the uploaded file.")
# Features and target
if 'Network_Type' in df.columns and 'MR_Level' in df.columns:
X = df[['Latitude', 'Longitude', 'Network_Type', 'MR_Level']] # Example features
y = df['Coverage'] # Target variable
# Train-test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Normalize features
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# Train a Random Forest Classifier
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
# Make predictions
y_pred = model.predict(X_test)
# Show accuracy of the model
accuracy = accuracy_score(y_test, y_pred)
st.write(f"Model Accuracy: {accuracy * 100:.2f}%")
# User Input for Prediction (Optional: Predict coverage for new input data)
st.sidebar.write("### Predict Radio Coverage")
lat_input = st.sidebar.number_input("Enter Latitude", min_value=-90.0, max_value=90.0, value=0.0)
lon_input = st.sidebar.number_input("Enter Longitude", min_value=-180.0, max_value=180.0, value=0.0)
network_input = st.sidebar.selectbox("Select Network Type", ["2G", "3G", "4G", "5G"])
mr_level_input = st.sidebar.number_input("Enter MR Level (dBm)", value=-85)
# Preprocessing the user input
network_input = {'2G': 0, '3G': 1, '4G': 2, '5G': 3}[network_input]
input_data = [[lat_input, lon_input, network_input, mr_level_input]]
input_data = scaler.transform(input_data) # Scale user input
# Make the prediction
coverage_prediction = model.predict(input_data)
st.sidebar.write(f"Predicted Coverage: {coverage_prediction[0]}")
# Display the confusion matrix for model performance
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)
st.write("Confusion Matrix:")
st.write(cm)
# Optionally, visualize the predicted coverage categories with a bar chart
coverage_counts = df['Coverage'].value_counts()
st.bar_chart(coverage_counts)
# Allow user to select file format for download
st.write("### Convert and Download Data")
file_format = st.radio("Select File Format for Download", ["XLSX", "JSON"])
if file_format == "XLSX":
# Convert to XLSX and offer for download
excel_file = "converted_file.xlsx"
df.to_excel(excel_file, index=False)
with open(excel_file, "rb") as f:
st.download_button(
label="Download Excel File",
data=f,
file_name=excel_file,
mime="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
elif file_format == "JSON":
# Convert to JSON and offer for download
json_file = "converted_file.json"
df.to_json(json_file, orient='records', lines=True)
with open(json_file, "rb") as f:
st.download_button(
label="Download JSON File",
data=f,
file_name=json_file,
mime="application/json"
)
# Instructions for the user
st.markdown("""
### Instructions:
1. Upload a `.csv` file.
2. View a preview of the data.
3. Select a format to convert the file to: either `.xlsx` or `.json`.
4. Download the converted file in your selected format.
5. Optionally, you can predict the radio coverage based on user input (Latitude, Longitude, MR Level, Network Type).
""")
import streamlit as st
import pandas as pd
# File uploader for CSV
uploaded_file = st.file_uploader("Upload CSV File", type=["csv"])
if uploaded_file is not None:
# Read CSV file into DataFrame
df = pd.read_csv(uploaded_file)
# Show the uploaded file's column names and a preview of the data for debugging
st.write("Columns in the uploaded file:")
st.write(df.columns) # Print column names
st.write("Data Preview:")
st.write(df.head()) # Show a preview of the first few rows
# Check if 'Network_Type' and 'MR_Level' columns exist
if 'Network_Type' in df.columns:
st.write("Network_Type column is present.")
else:
st.error("Error: 'Network_Type' column not found in the uploaded file.")
if 'MR_Level' in df.columns:
st.write("MR_Level column is present.")
else:
st.error("Error: 'MR_Level' column not found in the uploaded file.")
import streamlit as st
import pandas as pd
# File uploader for CSV (with unique key)
uploaded_file = st.file_uploader("Upload CSV File", type=["csv"], key="file_uploader_1")
if uploaded_file is not None:
# Read CSV file into DataFrame
df = pd.read_csv(uploaded_file)
# Show the uploaded file's column names and a preview of the data for debugging
st.write("Columns in the uploaded file:")
st.write(df.columns) # Print column names
st.write("Data Preview:")
st.write(df.head()) # Show a preview of the first few rows
# Check if 'Network_Type' and 'MR_Level' columns exist
if 'Network_Type' in df.columns:
st.write("Network_Type column is present.")
else:
st.error("Error: 'Network_Type' column not found in the uploaded file.")
if 'MR_Level' in df.columns:
st.write("MR_Level column is present.")
else:
st.error("Error: 'MR_Level' column not found in the uploaded file.")