Update app.py
Browse files
app.py
CHANGED
|
@@ -5,7 +5,7 @@ import matplotlib.pyplot as plt
|
|
| 5 |
from sklearn.svm import SVC
|
| 6 |
from sklearn.preprocessing import StandardScaler
|
| 7 |
|
| 8 |
-
# --- Sample
|
| 9 |
data = {
|
| 10 |
"5Y_Return": [14.0, 7.5, 13.2, 6.0, 15.0, 8.0, 12.0, 6.5, 10.5, 7.2],
|
| 11 |
"Volatility": [8.0, 6.5, 7.8, 9.0, 7.0, 6.2, 7.1, 8.5, 6.8, 7.9],
|
|
@@ -15,7 +15,7 @@ data = {
|
|
| 15 |
df = pd.DataFrame(data)
|
| 16 |
df["Label"] = df["Rating"].map({"Good": 1, "Bad": 0})
|
| 17 |
|
| 18 |
-
# --- Train
|
| 19 |
X = df[["5Y_Return", "Volatility", "Risk_Score"]]
|
| 20 |
y = df["Label"]
|
| 21 |
|
|
@@ -25,19 +25,18 @@ X_scaled = scaler.fit_transform(X)
|
|
| 25 |
model = SVC(kernel="linear", probability=True)
|
| 26 |
model.fit(X_scaled, y)
|
| 27 |
|
| 28 |
-
# --- Function to
|
| 29 |
def classify_and_plot(return_5y, volatility, risk_score):
|
| 30 |
-
#
|
| 31 |
input_data = [[return_5y, volatility, risk_score]]
|
| 32 |
input_scaled = scaler.transform(input_data)
|
| 33 |
prediction = model.predict(input_scaled)[0]
|
| 34 |
confidence = model.predict_proba(input_scaled)[0][prediction]
|
| 35 |
result = "Good Investment" if prediction == 1 else "Bad Investment"
|
| 36 |
|
| 37 |
-
#
|
| 38 |
X_2d = df[["5Y_Return", "Volatility"]].values
|
| 39 |
y_2d = df["Label"].values
|
| 40 |
-
|
| 41 |
scaler_2d = StandardScaler()
|
| 42 |
X_2d_scaled = scaler_2d.fit_transform(X_2d)
|
| 43 |
|
|
@@ -47,10 +46,12 @@ def classify_and_plot(return_5y, volatility, risk_score):
|
|
| 47 |
# Plot decision boundary
|
| 48 |
fig, ax = plt.subplots(figsize=(6, 5))
|
| 49 |
ax.scatter(X_2d_scaled[:, 0], X_2d_scaled[:, 1], c=y_2d, cmap="bwr", edgecolors="k", s=60)
|
|
|
|
|
|
|
| 50 |
ax.scatter(model_2d.support_vectors_[:, 0], model_2d.support_vectors_[:, 1],
|
| 51 |
s=150, facecolors='none', edgecolors='k', linewidths=1.5, label="Support Vectors")
|
| 52 |
|
| 53 |
-
#
|
| 54 |
xlim = ax.get_xlim()
|
| 55 |
ylim = ax.get_ylim()
|
| 56 |
xx = np.linspace(xlim[0], xlim[1], 30)
|
|
@@ -58,17 +59,17 @@ def classify_and_plot(return_5y, volatility, risk_score):
|
|
| 58 |
YY, XX = np.meshgrid(yy, xx)
|
| 59 |
xy = np.vstack([XX.ravel(), YY.ravel()]).T
|
| 60 |
Z = model_2d.decision_function(xy).reshape(XX.shape)
|
| 61 |
-
|
| 62 |
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1],
|
| 63 |
alpha=0.7, linestyles=['--', '-', '--'])
|
| 64 |
|
|
|
|
| 65 |
ax.set_title("SVM Decision Boundary (2 Features)")
|
| 66 |
ax.set_xlabel("5Y Return (scaled)")
|
| 67 |
ax.set_ylabel("Volatility (scaled)")
|
| 68 |
ax.legend()
|
| 69 |
ax.grid(True)
|
| 70 |
|
| 71 |
-
# Save and return
|
| 72 |
plot_path = "/tmp/svm_plot.png"
|
| 73 |
fig.savefig(plot_path)
|
| 74 |
plt.close(fig)
|
|
@@ -78,12 +79,23 @@ def classify_and_plot(return_5y, volatility, risk_score):
|
|
| 78 |
# --- Gradio UI ---
|
| 79 |
with gr.Blocks() as demo:
|
| 80 |
gr.Markdown("## 🧠 SVM Classifier: Mutual Fund Recommendation")
|
|
|
|
| 81 |
with gr.Row():
|
| 82 |
return_input = gr.Number(label="5-Year Return (%)", value=10.0)
|
| 83 |
vol_input = gr.Number(label="Volatility (%)", value=7.0)
|
| 84 |
risk_input = gr.Number(label="Risk Score (1=Low, 5=High)", value=3)
|
|
|
|
| 85 |
classify_btn = gr.Button("Classify and Show Decision Boundary")
|
| 86 |
output_label = gr.Textbox(label="Prediction")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
output_plot = gr.Image(label="SVM Decision Boundary")
|
| 88 |
|
| 89 |
classify_btn.click(
|
|
@@ -92,6 +104,5 @@ with gr.Blocks() as demo:
|
|
| 92 |
outputs=[output_label, output_plot]
|
| 93 |
)
|
| 94 |
|
| 95 |
-
# Launch app
|
| 96 |
if __name__ == "__main__":
|
| 97 |
demo.launch()
|
|
|
|
| 5 |
from sklearn.svm import SVC
|
| 6 |
from sklearn.preprocessing import StandardScaler
|
| 7 |
|
| 8 |
+
# --- Sample Morningstar-style data ---
|
| 9 |
data = {
|
| 10 |
"5Y_Return": [14.0, 7.5, 13.2, 6.0, 15.0, 8.0, 12.0, 6.5, 10.5, 7.2],
|
| 11 |
"Volatility": [8.0, 6.5, 7.8, 9.0, 7.0, 6.2, 7.1, 8.5, 6.8, 7.9],
|
|
|
|
| 15 |
df = pd.DataFrame(data)
|
| 16 |
df["Label"] = df["Rating"].map({"Good": 1, "Bad": 0})
|
| 17 |
|
| 18 |
+
# --- Train full SVM model for prediction ---
|
| 19 |
X = df[["5Y_Return", "Volatility", "Risk_Score"]]
|
| 20 |
y = df["Label"]
|
| 21 |
|
|
|
|
| 25 |
model = SVC(kernel="linear", probability=True)
|
| 26 |
model.fit(X_scaled, y)
|
| 27 |
|
| 28 |
+
# --- Function to classify and plot 2D SVM boundary ---
|
| 29 |
def classify_and_plot(return_5y, volatility, risk_score):
|
| 30 |
+
# Predict
|
| 31 |
input_data = [[return_5y, volatility, risk_score]]
|
| 32 |
input_scaled = scaler.transform(input_data)
|
| 33 |
prediction = model.predict(input_scaled)[0]
|
| 34 |
confidence = model.predict_proba(input_scaled)[0][prediction]
|
| 35 |
result = "Good Investment" if prediction == 1 else "Bad Investment"
|
| 36 |
|
| 37 |
+
# For plotting, use only 2D
|
| 38 |
X_2d = df[["5Y_Return", "Volatility"]].values
|
| 39 |
y_2d = df["Label"].values
|
|
|
|
| 40 |
scaler_2d = StandardScaler()
|
| 41 |
X_2d_scaled = scaler_2d.fit_transform(X_2d)
|
| 42 |
|
|
|
|
| 46 |
# Plot decision boundary
|
| 47 |
fig, ax = plt.subplots(figsize=(6, 5))
|
| 48 |
ax.scatter(X_2d_scaled[:, 0], X_2d_scaled[:, 1], c=y_2d, cmap="bwr", edgecolors="k", s=60)
|
| 49 |
+
|
| 50 |
+
# Support vectors
|
| 51 |
ax.scatter(model_2d.support_vectors_[:, 0], model_2d.support_vectors_[:, 1],
|
| 52 |
s=150, facecolors='none', edgecolors='k', linewidths=1.5, label="Support Vectors")
|
| 53 |
|
| 54 |
+
# Decision boundary
|
| 55 |
xlim = ax.get_xlim()
|
| 56 |
ylim = ax.get_ylim()
|
| 57 |
xx = np.linspace(xlim[0], xlim[1], 30)
|
|
|
|
| 59 |
YY, XX = np.meshgrid(yy, xx)
|
| 60 |
xy = np.vstack([XX.ravel(), YY.ravel()]).T
|
| 61 |
Z = model_2d.decision_function(xy).reshape(XX.shape)
|
|
|
|
| 62 |
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1],
|
| 63 |
alpha=0.7, linestyles=['--', '-', '--'])
|
| 64 |
|
| 65 |
+
# Annotations
|
| 66 |
ax.set_title("SVM Decision Boundary (2 Features)")
|
| 67 |
ax.set_xlabel("5Y Return (scaled)")
|
| 68 |
ax.set_ylabel("Volatility (scaled)")
|
| 69 |
ax.legend()
|
| 70 |
ax.grid(True)
|
| 71 |
|
| 72 |
+
# Save and return image
|
| 73 |
plot_path = "/tmp/svm_plot.png"
|
| 74 |
fig.savefig(plot_path)
|
| 75 |
plt.close(fig)
|
|
|
|
| 79 |
# --- Gradio UI ---
|
| 80 |
with gr.Blocks() as demo:
|
| 81 |
gr.Markdown("## 🧠 SVM Classifier: Mutual Fund Recommendation")
|
| 82 |
+
|
| 83 |
with gr.Row():
|
| 84 |
return_input = gr.Number(label="5-Year Return (%)", value=10.0)
|
| 85 |
vol_input = gr.Number(label="Volatility (%)", value=7.0)
|
| 86 |
risk_input = gr.Number(label="Risk Score (1=Low, 5=High)", value=3)
|
| 87 |
+
|
| 88 |
classify_btn = gr.Button("Classify and Show Decision Boundary")
|
| 89 |
output_label = gr.Textbox(label="Prediction")
|
| 90 |
+
|
| 91 |
+
gr.Markdown("""### 📊 Benchmark Guide
|
| 92 |
+
**🔴 Blue Dots = Good Investments**
|
| 93 |
+
**🔴 Red Dots = Bad Investments**
|
| 94 |
+
**⚫ Solid Black Line = Decision Boundary**
|
| 95 |
+
**⚫ Dashed Lines = Margins (distance to support vectors)**
|
| 96 |
+
**⭕ Large Hollow Dots = Support Vectors (key data points)**
|
| 97 |
+
""")
|
| 98 |
+
|
| 99 |
output_plot = gr.Image(label="SVM Decision Boundary")
|
| 100 |
|
| 101 |
classify_btn.click(
|
|
|
|
| 104 |
outputs=[output_label, output_plot]
|
| 105 |
)
|
| 106 |
|
|
|
|
| 107 |
if __name__ == "__main__":
|
| 108 |
demo.launch()
|