Yatheshr commited on
Commit
875906d
·
verified ·
1 Parent(s): 2170102

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -17
app.py CHANGED
@@ -3,10 +3,9 @@ import pandas as pd
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
  from sklearn.svm import SVC
6
- from sklearn.model_selection import train_test_split
7
  from sklearn.preprocessing import StandardScaler
8
 
9
- # --- Mock Morningstar-style data ---
10
  data = {
11
  "5Y_Return": [14.0, 7.5, 13.2, 6.0, 15.0, 8.0, 12.0, 6.5, 10.5, 7.2],
12
  "Volatility": [8.0, 6.5, 7.8, 9.0, 7.0, 6.2, 7.1, 8.5, 6.8, 7.9],
@@ -14,54 +13,62 @@ data = {
14
  "Rating": ["Good", "Bad", "Good", "Bad", "Good", "Bad", "Good", "Bad", "Good", "Bad"]
15
  }
16
  df = pd.DataFrame(data)
17
- df['Label'] = df['Rating'].map({'Good': 1, 'Bad': 0})
18
 
 
19
  X = df[["5Y_Return", "Volatility", "Risk_Score"]]
20
  y = df["Label"]
21
 
22
- # Scaling
23
  scaler = StandardScaler()
24
  X_scaled = scaler.fit_transform(X)
25
 
26
- # Train SVM
27
  model = SVC(kernel="linear", probability=True)
28
  model.fit(X_scaled, y)
29
 
30
- # --- Classify and plot function ---
31
  def classify_and_plot(return_5y, volatility, risk_score):
 
32
  input_data = [[return_5y, volatility, risk_score]]
33
  input_scaled = scaler.transform(input_data)
34
  prediction = model.predict(input_scaled)[0]
35
  confidence = model.predict_proba(input_scaled)[0][prediction]
36
  result = "Good Investment" if prediction == 1 else "Bad Investment"
37
 
38
- # --- Create plot ---
39
- fig, ax = plt.subplots(figsize=(6, 5))
 
 
 
 
40
 
41
- # Plot original data
42
- scatter = ax.scatter(X_scaled[:, 0], X_scaled[:, 1], c=y, cmap="bwr", edgecolors="k", s=60)
43
- ax.scatter(model.support_vectors_[:, 0], model.support_vectors_[:, 1],
 
 
 
 
44
  s=150, facecolors='none', edgecolors='k', linewidths=1.5, label="Support Vectors")
45
 
46
- # Grid for decision boundary
47
  xlim = ax.get_xlim()
48
  ylim = ax.get_ylim()
49
  xx = np.linspace(xlim[0], xlim[1], 30)
50
  yy = np.linspace(ylim[0], ylim[1], 30)
51
  YY, XX = np.meshgrid(yy, xx)
52
  xy = np.vstack([XX.ravel(), YY.ravel()]).T
53
- Z = model.decision_function(xy).reshape(XX.shape)
54
 
55
  ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1],
56
  alpha=0.7, linestyles=['--', '-', '--'])
57
 
58
- ax.set_title("SVM Decision Boundary")
59
  ax.set_xlabel("5Y Return (scaled)")
60
  ax.set_ylabel("Volatility (scaled)")
61
  ax.legend()
62
  ax.grid(True)
63
 
64
- # Save and return the figure
65
  plot_path = "/tmp/svm_plot.png"
66
  fig.savefig(plot_path)
67
  plt.close(fig)
@@ -70,7 +77,7 @@ def classify_and_plot(return_5y, volatility, risk_score):
70
 
71
  # --- Gradio UI ---
72
  with gr.Blocks() as demo:
73
- gr.Markdown("## 🧠 SVM Classifier: Good or Bad Mutual Fund?")
74
  with gr.Row():
75
  return_input = gr.Number(label="5-Year Return (%)", value=10.0)
76
  vol_input = gr.Number(label="Volatility (%)", value=7.0)
@@ -85,6 +92,6 @@ with gr.Blocks() as demo:
85
  outputs=[output_label, output_plot]
86
  )
87
 
88
- # Run app
89
  if __name__ == "__main__":
90
  demo.launch()
 
3
  import numpy as np
4
  import matplotlib.pyplot as plt
5
  from sklearn.svm import SVC
 
6
  from sklearn.preprocessing import StandardScaler
7
 
8
+ # --- Sample data mimicking Morningstar style ---
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],
 
13
  "Rating": ["Good", "Bad", "Good", "Bad", "Good", "Bad", "Good", "Bad", "Good", "Bad"]
14
  }
15
  df = pd.DataFrame(data)
16
+ df["Label"] = df["Rating"].map({"Good": 1, "Bad": 0})
17
 
18
+ # --- Train the 3-feature SVM model for prediction ---
19
  X = df[["5Y_Return", "Volatility", "Risk_Score"]]
20
  y = df["Label"]
21
 
 
22
  scaler = StandardScaler()
23
  X_scaled = scaler.fit_transform(X)
24
 
 
25
  model = SVC(kernel="linear", probability=True)
26
  model.fit(X_scaled, y)
27
 
28
+ # --- Function to predict and plot ---
29
  def classify_and_plot(return_5y, volatility, risk_score):
30
+ # Prediction
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
+ # --- Use only 2 features for plotting ---
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
 
44
+ model_2d = SVC(kernel="linear")
45
+ model_2d.fit(X_2d_scaled, y_2d)
46
+
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
+ # Grid
54
  xlim = ax.get_xlim()
55
  ylim = ax.get_ylim()
56
  xx = np.linspace(xlim[0], xlim[1], 30)
57
  yy = np.linspace(ylim[0], ylim[1], 30)
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 plot
72
  plot_path = "/tmp/svm_plot.png"
73
  fig.savefig(plot_path)
74
  plt.close(fig)
 
77
 
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)
 
92
  outputs=[output_label, output_plot]
93
  )
94
 
95
+ # Launch app
96
  if __name__ == "__main__":
97
  demo.launch()