Skip to content

Commit

Permalink
add: readme and gui model
Browse files Browse the repository at this point in the history
  • Loading branch information
dtruong46me committed Dec 29, 2023
1 parent 5c1aae6 commit 6e03aeb
Show file tree
Hide file tree
Showing 14 changed files with 216 additions and 65 deletions.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,15 @@
# laptop-prices-analysis
## Problem Description

## Data

## Model

## Evaluation

## Installation

## Contribution

|Name|Student ID|Email|
|:-:|:-:|:-:|
|Dinh Nguyen Cong Quy (C)|20214927|quy.dnc
Binary file added assets/knn4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified src/app/__pycache__/predict_price.cpython-310.pyc
Binary file not shown.
Binary file not shown.
22 changes: 15 additions & 7 deletions src/app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import os

from predict_price import *
from rf_predict_price import *

def main():
st.title("Laptop Price Prediction")
Expand Down Expand Up @@ -106,6 +107,8 @@ def main():

st.write("___")

model_name = st.radio("Model", options=["Random Forest", "K-Nearest Neighbor"])

if st.button('Submit'):
df = transfer_to_df(brand=brand_input,
cpu=cpu_input,
Expand All @@ -116,15 +119,20 @@ def main():
storage=storage_input,
os=os_input,
weight=str(weight_input))
st.dataframe(df)
# st.dataframe(df)

MODELNAME = "knn_model_2.pkl"
MODEL_PATH = os.path.abspath(os.path.join(os.path.join(os.path.dirname(__file__)), MODELNAME))

SCALERNAME = "save_scaler.pkl"
SCALER_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), SCALERNAME))

MODELNAME = "knn_model.pkl"
PARENT_DIR = os.path.abspath(os.path.dirname(__file__))
print(PARENT_DIR)
MODEL_PATH = os.path.abspath(os.path.join(PARENT_DIR, MODELNAME))
if model_name == 'K-Nearest Neighbor':
price = knn_predict_price(df, MODEL_PATH, SCALER_PATH)

price = knn_predict_price(df, MODEL_PATH)
st.success(f'{price} USD')
if model_name == 'Random Forest':
price = rf_predict_price(brand_input, cpu_input, gpu_input, str(monitor_input), resolution_input, ram_input, storage_input, os_input, str(weight_input))
st.success(f'{price:.2f} USD')

else:
st.success("0 USD")
Expand Down
Binary file added src/app/encoded_OS_dict.pkl
Binary file not shown.
Binary file added src/app/encoded_brand_dict.pkl
Binary file not shown.
Binary file added src/app/knn_model_2.pkl
Binary file not shown.
22 changes: 14 additions & 8 deletions src/app/predict_price.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,19 @@ def transfer_to_df(brand,

return df

def knn_predict_price(new_data: pd.DataFrame, model_path):
def knn_predict_price(new_data: pd.DataFrame, model_path, scaler_path):
try:
knn = joblib.load(open(model_path, "rb"))
scaler = joblib.load(open(scaler_path, "rb"))

print(new_data)
columns_to_scale = ["Weight", "Monitor", "RAM", "Storage Amount", "GPU Mark", "Width", "Height", "CPU Mark"]
new_data_scaled = pd.DataFrame(scaler.transform(new_data[columns_to_scale]), columns=columns_to_scale)
new_data[columns_to_scale] = new_data_scaled

y_pred = knn.predict(new_data)
print(new_data)
print(y_pred)
print(f"Predicted Price: {y_pred[0]}")

except FileNotFoundError as e:
print(f"Error: {e}")
Expand All @@ -100,18 +105,18 @@ def knn_predict_price(new_data: pd.DataFrame, model_path):


if __name__=="__main__":
BRAND = "ASUS"
CPU = "Intel Core i5-12500H"
GPU = " GeForce RTX 3050"
BRAND = "Apple"
CPU = "Intel Core i7 12700H"
GPU = "Intel Iris Xe"
MONITOR = "17.3"
RESOLUTION = "1920x1080"
RAM = "16GB"
STORAGE = "512GB"
OS = "Windows 11 Home 64-bit"
WEIGHT = "2.60"

# SCALER_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "knn_default_scaler.pkl"))
MODELPATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "knn_model.pkl"))
MODELPATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "knn_model_2.pkl"))
SCALER_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "save_scaler.pkl"))

new_data = transfer_to_df(brand=BRAND,
cpu=CPU,
Expand All @@ -123,8 +128,9 @@ def knn_predict_price(new_data: pd.DataFrame, model_path):
os=OS,
weight=WEIGHT)

print("Unscaled Data:")
print(new_data)

y_hat = knn_predict_price(new_data=new_data, model_path=MODELPATH)
y_hat = knn_predict_price(new_data=new_data, model_path=MODELPATH, scaler_path=SCALER_PATH)
print(y_hat)
print(type(y_hat))
59 changes: 59 additions & 0 deletions src/app/rf_predict_price.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@

import pandas as pd
import pickle
import os
# Now you can import your module
from map_cpu_gpu import *

def predict(t):
current_dir =os.path.dirname(('\\').join(os.path.abspath(__file__).split('\\')))#file save in src/app

file_path = current_dir+'\encoded_brand_dict.pkl' #relative path to file
file_path2 = current_dir + '\encoded_OS_dict.pkl' #relative path to file

with open(file_path, 'rb') as file:
encoded_brand_dict = pickle.load(file)
with open(file_path2, 'rb') as file:
encoded_OS_dict = pickle.load(file)
data_str=t
values = data_str.split(',')

columns = ['Brand', 'CPU Name', 'CPU Mark', 'GPU Name', 'GPU Mark', 'Monitor', 'Width', 'Height',
'RAM', 'Storage Amount', 'OS', 'Weight']

data = pd.DataFrame([values], columns=columns)
data.drop(columns=['CPU Name','GPU Name'],axis=1,inplace=True)
data['Brand'] = data['Brand'].str.lower()
data['Encoded_Brand'] = data['Brand'].apply(lambda x: encoded_brand_dict.get(x) if x in encoded_brand_dict else None)
data.drop(columns=['Brand'],axis=1,inplace=True)
data['Encoded_OS'] = data['OS'].apply(lambda x: encoded_OS_dict.get(x) if x in encoded_OS_dict else 100)
data.drop(columns=['OS'],axis=1,inplace=True)
data['Resolution'] = int(data['Width'])*int(data['Height'])
data.drop(columns=['Width','Height'],axis=1,inplace=True)

file_path3 = current_dir+'\saved_model_random_forest.pkl' #relative path to file

with open(file_path3, 'rb') as file:
loaded_model = pickle.load(file)

features = ['CPU Mark', 'GPU Mark', 'Monitor', 'RAM', 'Storage Amount','Encoded_Brand','Encoded_OS', 'Resolution']

X_new_input = data[features]
predictions_new_input = loaded_model.predict(X_new_input)

return round(predictions_new_input[0],2)


def rf_predict_price(brand: str='Apple',cpu: str='Intel Core i7-11800H',gpu: str='Intel Iris Xe',monitor: str='15.6',resolution: str='1920x1080',ram: str='8GB',storage: str='256GB',os: str='mac0S',weight: str='1.78'):
_, cpu_mark = get_cpu_name(cpu)
_, gpu_mark = get_gpu_name(gpu)
width,height = resolution.split('x')
ram = ram.replace('GB','')
storage = storage.replace('GB','')
text = brand+","+cpu+","+str(cpu_mark)+","+gpu+","+str(gpu_mark)+","+monitor+","+width+","+height+","+ram+","+storage+","+os+","+weight
print(text)
Y_pred = predict(text)
return Y_pred

if __name__=='__main__':
print(rf_predict_price())
File renamed without changes.
File renamed without changes.
Binary file removed src/model/knn_default_scaler.pkl
Binary file not shown.
Loading

0 comments on commit 6e03aeb

Please sign in to comment.