Spaces:
Runtime error
Runtime error
Update app2.py
Browse files
app2.py
CHANGED
|
@@ -1,36 +1,30 @@
|
|
| 1 |
-
|
| 2 |
import streamlit as st
|
| 3 |
import pandas as pd
|
| 4 |
import numpy as np
|
| 5 |
-
import seaborn as sns
|
| 6 |
import matplotlib.pyplot as plt
|
|
|
|
| 7 |
|
| 8 |
-
from sklearn.model_selection import train_test_split
|
| 9 |
-
from sklearn.preprocessing import LabelEncoder, StandardScaler
|
| 10 |
-
from sklearn.impute import SimpleImputer
|
| 11 |
-
from sklearn.decomposition import PCA
|
| 12 |
-
from sklearn.manifold import TSNE
|
| 13 |
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
|
| 14 |
from sklearn.linear_model import LogisticRegression
|
| 15 |
from sklearn.naive_bayes import GaussianNB
|
| 16 |
from sklearn.svm import SVC
|
| 17 |
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, RocCurveDisplay
|
| 18 |
-
from sklearn.
|
| 19 |
-
from scipy.stats import uniform, randint
|
| 20 |
|
| 21 |
st.set_option('deprecation.showPyplotGlobalUse', False)
|
|
|
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
# Load dataset
|
| 26 |
@st.cache_data
|
| 27 |
def load_data():
|
| 28 |
url = "https://drive.google.com/uc?export=download&id=1QBTnXxORRbJzE5Z2aqKHsVqgB7mqowiN"
|
| 29 |
return pd.read_csv(url)
|
| 30 |
|
| 31 |
df = load_data()
|
| 32 |
-
st.subheader("1.
|
| 33 |
-
st.
|
| 34 |
|
| 35 |
# Fill missing values
|
| 36 |
for col in df.select_dtypes(include='object').columns:
|
|
@@ -38,109 +32,26 @@ for col in df.select_dtypes(include='object').columns:
|
|
| 38 |
for col in df.select_dtypes(include=np.number).columns:
|
| 39 |
df[col] = df[col].fillna(df[col].median())
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
IQR = Q3 - Q1
|
| 45 |
-
df = df[~((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR))).any(axis=1)]
|
| 46 |
-
|
| 47 |
-
# Encoding
|
| 48 |
-
cat_cols = df.select_dtypes(include='object').columns
|
| 49 |
-
for col in cat_cols:
|
| 50 |
-
le = LabelEncoder()
|
| 51 |
-
df[col] = le.fit_transform(df[col])
|
| 52 |
|
| 53 |
-
# Feature
|
| 54 |
if 'Model Year' in df.columns:
|
| 55 |
df['Vehicle_Age'] = 2025 - df['Model Year']
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
# Feature
|
| 63 |
scaler = StandardScaler()
|
| 64 |
X_scaled = scaler.fit_transform(X)
|
| 65 |
-
rf = RandomForestClassifier(random_state=42)
|
| 66 |
rf.fit(X_scaled, y)
|
| 67 |
-
top_features = pd.Series(rf.feature_importances_, index=X.columns).nlargest(
|
| 68 |
-
X = df[top_features]
|
| 69 |
-
|
| 70 |
-
# Subsample for balance
|
| 71 |
-
df['Target'] = y
|
| 72 |
-
df_bal = df.groupby('Target').apply(lambda x: x.sample(min(len(x), 300), random_state=42)).reset_index(drop=True)
|
| 73 |
-
X = df_bal[top_features]
|
| 74 |
-
y = df_bal['Target']
|
| 75 |
-
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.3, random_state=42)
|
| 76 |
-
|
| 77 |
-
# Visualization
|
| 78 |
-
st.subheader("2. Data Visualization")
|
| 79 |
-
|
| 80 |
-
if st.checkbox("Show Correlation Heatmap"):
|
| 81 |
-
plt.figure(figsize=(10, 6))
|
| 82 |
-
sns.heatmap(df[top_features + ['Target']].corr(), annot=True, cmap='coolwarm')
|
| 83 |
-
st.pyplot()
|
| 84 |
-
|
| 85 |
-
if st.checkbox("Show PCA Plot"):
|
| 86 |
-
pca = PCA(n_components=2)
|
| 87 |
-
X_pca = pca.fit_transform(X)
|
| 88 |
-
plt.figure(figsize=(8, 5))
|
| 89 |
-
plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis', alpha=0.6)
|
| 90 |
-
plt.title("PCA Projection")
|
| 91 |
-
st.pyplot()
|
| 92 |
-
|
| 93 |
-
if st.checkbox("Show t-SNE Plot"):
|
| 94 |
-
tsne = TSNE(n_components=2, random_state=42)
|
| 95 |
-
X_tsne = tsne.fit_transform(X)
|
| 96 |
-
plt.figure(figsize=(8, 5))
|
| 97 |
-
plt.scatter(X_tsne[:, 0], X_tsne[:, 1], c=y, cmap='plasma', alpha=0.7)
|
| 98 |
-
plt.title("t-SNE Projection")
|
| 99 |
-
st.pyplot()
|
| 100 |
-
|
| 101 |
-
# Model Training
|
| 102 |
-
st.subheader("3. Model Training & Evaluation")
|
| 103 |
-
|
| 104 |
-
models = {
|
| 105 |
-
'Logistic Regression': LogisticRegression(max_iter=1000),
|
| 106 |
-
'SVM': SVC(probability=True),
|
| 107 |
-
'Gradient Boosting': GradientBoostingClassifier(),
|
| 108 |
-
'Naive Bayes': GaussianNB()
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
for name, model in models.items():
|
| 112 |
-
model.fit(X_train, y_train)
|
| 113 |
-
y_pred = model.predict(X_test)
|
| 114 |
-
st.write(f"### {name}")
|
| 115 |
-
st.text("Classification Report")
|
| 116 |
-
st.text(classification_report(y_test, y_pred))
|
| 117 |
-
st.text("Confusion Matrix")
|
| 118 |
-
st.write(confusion_matrix(y_test, y_pred))
|
| 119 |
-
if hasattr(model, "predict_proba"):
|
| 120 |
-
RocCurveDisplay.from_estimator(model, X_test, y_test)
|
| 121 |
-
st.pyplot()
|
| 122 |
-
|
| 123 |
-
# Hyperparameter Tuning
|
| 124 |
-
st.subheader("4. Hyperparameter Tuning Summary")
|
| 125 |
-
|
| 126 |
-
if st.checkbox("Run Tuning"):
|
| 127 |
-
st.info("Running tuning... may take a few minutes")
|
| 128 |
-
|
| 129 |
-
param_dist_lr = {'C': uniform(0.01, 10), 'penalty': ['l2'], 'solver': ['lbfgs']}
|
| 130 |
-
param_dist_svm = {'C': uniform(0.1, 10)}
|
| 131 |
-
param_dist_gbc = {'n_estimators': randint(50, 150), 'learning_rate': uniform(0.01, 0.2), 'max_depth': randint(3, 6)}
|
| 132 |
-
|
| 133 |
-
sample_X = X_train.sample(min(1000, len(X_train)), random_state=42)
|
| 134 |
-
sample_y = y_train.loc[sample_X.index]
|
| 135 |
-
|
| 136 |
-
rs_lr = RandomizedSearchCV(LogisticRegression(max_iter=1000), param_distributions=param_dist_lr, n_iter=10, cv=3)
|
| 137 |
-
rs_lr.fit(sample_X, sample_y)
|
| 138 |
-
st.write("Best Logistic Regression:", rs_lr.best_params_)
|
| 139 |
-
|
| 140 |
-
rs_svm = RandomizedSearchCV(SVC(probability=True), param_distributions=param_dist_svm, n_iter=5, cv=2)
|
| 141 |
-
rs_svm.fit(sample_X, sample_y)
|
| 142 |
-
st.write("Best SVM:", rs_svm.best_params_)
|
| 143 |
-
|
| 144 |
-
rs_gbc = RandomizedSearchCV(GradientBoostingClassifier(), param_distributions=param_dist_gbc, n_iter=10, cv=3)
|
| 145 |
-
rs_gbc.fit(sample_X, sample_y)
|
| 146 |
-
st.write("Best Gradient Boosting:", rs_gbc.best_params_)
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
|
|
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
+
import seaborn as sns
|
| 6 |
|
| 7 |
+
from sklearn.model_selection import train_test_split
|
| 8 |
+
from sklearn.preprocessing import LabelEncoder, StandardScaler
|
|
|
|
|
|
|
|
|
|
| 9 |
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
|
| 10 |
from sklearn.linear_model import LogisticRegression
|
| 11 |
from sklearn.naive_bayes import GaussianNB
|
| 12 |
from sklearn.svm import SVC
|
| 13 |
from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, RocCurveDisplay
|
| 14 |
+
from sklearn.decomposition import PCA
|
|
|
|
| 15 |
|
| 16 |
st.set_option('deprecation.showPyplotGlobalUse', False)
|
| 17 |
+
st.title("Electric Vehicle ML Dashboard (Optimized for Hugging Face)")
|
| 18 |
|
| 19 |
+
# Load data
|
|
|
|
|
|
|
| 20 |
@st.cache_data
|
| 21 |
def load_data():
|
| 22 |
url = "https://drive.google.com/uc?export=download&id=1QBTnXxORRbJzE5Z2aqKHsVqgB7mqowiN"
|
| 23 |
return pd.read_csv(url)
|
| 24 |
|
| 25 |
df = load_data()
|
| 26 |
+
st.subheader("1. Data Preview")
|
| 27 |
+
st.dataframe(df.head())
|
| 28 |
|
| 29 |
# Fill missing values
|
| 30 |
for col in df.select_dtypes(include='object').columns:
|
|
|
|
| 32 |
for col in df.select_dtypes(include=np.number).columns:
|
| 33 |
df[col] = df[col].fillna(df[col].median())
|
| 34 |
|
| 35 |
+
# Encode categories
|
| 36 |
+
for col in df.select_dtypes(include='object').columns:
|
| 37 |
+
df[col] = LabelEncoder().fit_transform(df[col])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# Feature engineering
|
| 40 |
if 'Model Year' in df.columns:
|
| 41 |
df['Vehicle_Age'] = 2025 - df['Model Year']
|
| 42 |
|
| 43 |
+
# Target setup
|
| 44 |
+
if 'Electric Range' not in df.columns:
|
| 45 |
+
st.error("'Electric Range' column missing!")
|
| 46 |
+
st.stop()
|
| 47 |
+
|
| 48 |
+
df['Target'] = (df['Electric Range'] > df['Electric Range'].median()).astype(int)
|
| 49 |
+
y = df['Target']
|
| 50 |
+
X = df.drop(columns=['Electric Range', 'Target'])
|
| 51 |
|
| 52 |
+
# Feature selection via Random Forest
|
| 53 |
scaler = StandardScaler()
|
| 54 |
X_scaled = scaler.fit_transform(X)
|
| 55 |
+
rf = RandomForestClassifier(n_estimators=50, random_state=42)
|
| 56 |
rf.fit(X_scaled, y)
|
| 57 |
+
top_features = pd.Series(rf.feature_importances_, index=X.columns).nlargest(5).index.tolis_
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|