test / app.py
aartstudio's picture
Upload 3 files
c448fa9 verified
# -*- coding: utf-8 -*-
"""2.7 (Optional DBS).ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1Js2DNDDuusJx06SBvdh-lmKbuCBTBw9B
chatgpt prompt:
Please create a regression model to predict DBS base on SGD exchange rate, create the model and then use gradio for the interface
"""
# Install dependencies (uncomment if needed)
# !pip install pandas scikit-learn gradio
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import gradio as gr
# 1. LOAD DATA
# Make sure the CSV file is in the same folder, or give full path
df = pd.read_csv("DBS_SingDollar.csv")
# If your header row is exactly: Date,DBS,SGD this will work directly
# Keep only needed columns and drop missing values
df = df[["DBS", "SGD"]].dropna()
X = df[["SGD"]] # feature
y = df["DBS"] # target
# 2. TRAIN / TEST SPLIT
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
# 3. TRAIN MODEL (Linear Regression)
model = LinearRegression()
model.fit(X_train, y_train)
# 4. EVALUATE (optional, shows in console)
y_pred = model.predict(X_test)
rmse = mean_squared_error(y_test, y_pred) ** 0.5
r2 = r2_score(y_test, y_pred)
print(f"RMSE: {rmse:.4f}")
print(f"R²: {r2:.4f}")
# 5. PREDICTION FUNCTION FOR GRADIO
def predict_dbs_price(sgd_rate: float) -> str:
"""
Input: SGD exchange rate (float)
Output: predicted DBS price (string for display)
"""
pred = model.predict([[sgd_rate]])[0]
return f"Predicted DBS price: {pred:.2f}"
# 6. GRADIO INTERFACE
iface = gr.Interface(
fn=predict_dbs_price,
inputs=gr.Number(label="SGD Exchange Rate"),
outputs=gr.Textbox(label="Predicted DBS Price"),
title="DBS Price Predictor",
description="Enter the SGD exchange rate to predict the DBS share price (trained with historical DBS & SGD data)."
)
iface.launch()