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|
| 5 |
+
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
|
| 6 |
+
from sklearn.metrics import confusion_matrix, classification_report, mean_squared_error, r2_score
|
| 7 |
+
from sklearn.cluster import KMeans
|
| 8 |
+
from sklearn.decomposition import PCA
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import seaborn as sns
|
| 11 |
+
import io
|
| 12 |
+
|
| 13 |
+
def analyze_csv(file, label_col):
|
| 14 |
+
try:
|
| 15 |
+
df = pd.read_csv(file.name if hasattr(file, "name") else file)
|
| 16 |
+
except Exception as e:
|
| 17 |
+
return None, None, None, None, f"error reading csv: {e}"
|
| 18 |
+
|
| 19 |
+
if label_col not in df.columns:
|
| 20 |
+
return None, None, None, None, f"label column '{label_col}' not in data"
|
| 21 |
+
|
| 22 |
+
df = df.dropna()
|
| 23 |
+
X = df.drop(columns=[label_col])
|
| 24 |
+
y = df[label_col]
|
| 25 |
+
|
| 26 |
+
# use only numeric features for modeling; drop non-numeric columns
|
| 27 |
+
X_numeric = X.select_dtypes(include=[np.number])
|
| 28 |
+
if X_numeric.shape[1] == 0:
|
| 29 |
+
return None, None, None, None, "no numeric features available for modeling"
|
| 30 |
+
|
| 31 |
+
results_text = ""
|
| 32 |
+
cm_img = None
|
| 33 |
+
reg_img = None
|
| 34 |
+
fi_img = None
|
| 35 |
+
|
| 36 |
+
# placeholder for feature importances
|
| 37 |
+
feature_importances = None
|
| 38 |
+
|
| 39 |
+
# if label is numeric, treat as regression; otherwise, classification
|
| 40 |
+
if pd.api.types.is_numeric_dtype(y):
|
| 41 |
+
task = "regression"
|
| 42 |
+
X_train, X_test, y_train, y_test = train_test_split(X_numeric, y, test_size=0.3, random_state=42)
|
| 43 |
+
model = RandomForestRegressor(random_state=42)
|
| 44 |
+
model.fit(X_train, y_train)
|
| 45 |
+
y_pred = model.predict(X_test)
|
| 46 |
+
mse = mean_squared_error(y_test, y_pred)
|
| 47 |
+
r2 = r2_score(y_test, y_pred)
|
| 48 |
+
results_text += f"regression results:\nmse: {mse:.3f}\nr2: {r2:.3f}\n"
|
| 49 |
+
# regression scatter plot: true vs predicted
|
| 50 |
+
plt.figure()
|
| 51 |
+
plt.scatter(y_test, y_pred, alpha=0.7)
|
| 52 |
+
plt.xlabel("true values")
|
| 53 |
+
plt.ylabel("predicted values")
|
| 54 |
+
plt.title("regression: true vs predicted")
|
| 55 |
+
buf = io.BytesIO()
|
| 56 |
+
plt.savefig(buf, format="png")
|
| 57 |
+
plt.close()
|
| 58 |
+
buf.seek(0)
|
| 59 |
+
reg_img = buf
|
| 60 |
+
# note: confusion matrix not applicable here
|
| 61 |
+
feature_importances = model.feature_importances_
|
| 62 |
+
else:
|
| 63 |
+
task = "classification"
|
| 64 |
+
# encode labels as integers
|
| 65 |
+
y_encoded = pd.factorize(y)[0]
|
| 66 |
+
X_train, X_test, y_train, y_test = train_test_split(X_numeric, y_encoded, test_size=0.3, random_state=42)
|
| 67 |
+
model = RandomForestClassifier(random_state=42)
|
| 68 |
+
model.fit(X_train, y_train)
|
| 69 |
+
y_pred = model.predict(X_test)
|
| 70 |
+
cm = confusion_matrix(y_test, y_pred)
|
| 71 |
+
cr = classification_report(y_test, y_pred)
|
| 72 |
+
results_text += f"classification results:\n{cr}\n"
|
| 73 |
+
plt.figure()
|
| 74 |
+
sns.heatmap(cm, annot=True, fmt="d", cmap="Blues")
|
| 75 |
+
plt.xlabel("predicted")
|
| 76 |
+
plt.ylabel("true")
|
| 77 |
+
plt.title("confusion matrix")
|
| 78 |
+
buf = io.BytesIO()
|
| 79 |
+
plt.savefig(buf, format="png")
|
| 80 |
+
plt.close()
|
| 81 |
+
buf.seek(0)
|
| 82 |
+
cm_img = buf
|
| 83 |
+
feature_importances = model.feature_importances_
|
| 84 |
+
|
| 85 |
+
# feature importance plot
|
| 86 |
+
fi = pd.Series(feature_importances, index=X_numeric.columns).sort_values(ascending=False)
|
| 87 |
+
plt.figure(figsize=(8,4))
|
| 88 |
+
sns.barplot(x=fi.values, y=fi.index)
|
| 89 |
+
plt.title("feature importances")
|
| 90 |
+
buf = io.BytesIO()
|
| 91 |
+
plt.savefig(buf, format="png", bbox_inches="tight")
|
| 92 |
+
plt.close()
|
| 93 |
+
buf.seek(0)
|
| 94 |
+
fi_img = buf
|
| 95 |
+
|
| 96 |
+
# clustering: kmeans on numeric features; use pca for 2d visualization
|
| 97 |
+
k = 3
|
| 98 |
+
kmeans = KMeans(n_clusters=k, random_state=42)
|
| 99 |
+
clusters = kmeans.fit_predict(X_numeric)
|
| 100 |
+
pca = PCA(n_components=2, random_state=42)
|
| 101 |
+
X_pca = pca.fit_transform(X_numeric)
|
| 102 |
+
plt.figure()
|
| 103 |
+
scatter = plt.scatter(X_pca[:,0], X_pca[:,1], c=clusters, cmap="viridis", alpha=0.7)
|
| 104 |
+
plt.xlabel("pca 1")
|
| 105 |
+
plt.ylabel("pca 2")
|
| 106 |
+
plt.title("kmeans clustering (k=3)")
|
| 107 |
+
plt.colorbar(scatter, ticks=range(k))
|
| 108 |
+
buf = io.BytesIO()
|
| 109 |
+
plt.savefig(buf, format="png", bbox_inches="tight")
|
| 110 |
+
plt.close()
|
| 111 |
+
buf.seek(0)
|
| 112 |
+
cluster_img = buf
|
| 113 |
+
|
| 114 |
+
return cm_img, reg_img, fi_img, cluster_img, results_text
|
| 115 |
+
|
| 116 |
+
def update_dropdown(file):
|
| 117 |
+
try:
|
| 118 |
+
df = pd.read_csv(file.name if hasattr(file, "name") else file)
|
| 119 |
+
return list(df.columns)
|
| 120 |
+
except Exception as e:
|
| 121 |
+
return []
|
| 122 |
+
|
| 123 |
+
with gr.Blocks() as demo:
|
| 124 |
+
gr.markdown("## csv analysis app")
|
| 125 |
+
with gr.Row():
|
| 126 |
+
file_input = gr.File(label="upload csv", file_types=[".csv"])
|
| 127 |
+
label_dropdown = gr.Dropdown(label="select label column", choices=[])
|
| 128 |
+
|
| 129 |
+
file_input.change(fn=update_dropdown, inputs=file_input, outputs=label_dropdown)
|
| 130 |
+
|
| 131 |
+
analyze_btn = gr.Button("analyze")
|
| 132 |
+
with gr.Tabs():
|
| 133 |
+
with gr.TabItem("results"):
|
| 134 |
+
results_textbox = gr.Textbox(label="metrics & results", lines=10)
|
| 135 |
+
with gr.TabItem("confusion matrix"):
|
| 136 |
+
cm_output = gr.Image(label="confusion matrix")
|
| 137 |
+
with gr.TabItem("regression plot"):
|
| 138 |
+
reg_output = gr.Image(label="regression plot")
|
| 139 |
+
with gr.TabItem("feature importances"):
|
| 140 |
+
fi_output = gr.Image(label="feature importances")
|
| 141 |
+
with gr.TabItem("clustering"):
|
| 142 |
+
cluster_output = gr.Image(label="cluster plot")
|
| 143 |
+
|
| 144 |
+
analyze_btn.click(fn=analyze_csv, inputs=[file_input, label_dropdown],
|
| 145 |
+
outputs=[cm_output, reg_output, fi_output, cluster_output, results_textbox])
|
| 146 |
+
|
| 147 |
+
demo.launch()
|