Compare commits
12 Commits
cluster3d
...
prediction
Author | SHA1 | Date | |
---|---|---|---|
![]() |
089cc66042 | ||
![]() |
2d1c867bed | ||
![]() |
a914c3f8f9 | ||
![]() |
70641ebca4 | ||
![]() |
e5f05a2c8a | ||
![]() |
972fde561f | ||
![]() |
694ecd0eef | ||
![]() |
e255c67972 | ||
6dcca29cbd | |||
a325603fd9 | |||
5f960df838 | |||
63bce82b3b |
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
__pycache__
|
||||||
|
.venv
|
@@ -13,6 +13,7 @@ uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
|
|||||||
|
|
||||||
if uploaded_file is not None:
|
if uploaded_file is not None:
|
||||||
st.session_state.data = pd.read_csv(uploaded_file)
|
st.session_state.data = pd.read_csv(uploaded_file)
|
||||||
|
st.session_state.original_data = st.session_state.data
|
||||||
st.success("File loaded successfully!")
|
st.success("File loaded successfully!")
|
||||||
|
|
||||||
|
|
||||||
|
138
frontend/normstrategy.py
Normal file
138
frontend/normstrategy.py
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from pandas import DataFrame, Series
|
||||||
|
from pandas.api.types import is_numeric_dtype
|
||||||
|
from typing import Any, Union
|
||||||
|
|
||||||
|
class DataFrameFunction(ABC):
|
||||||
|
"""A command that may be applied in-place to a dataframe."""
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
"""Apply the current function to the given dataframe, in-place.
|
||||||
|
|
||||||
|
The series is described by its label and dataframe."""
|
||||||
|
return df
|
||||||
|
|
||||||
|
|
||||||
|
class MVStrategy(DataFrameFunction):
|
||||||
|
"""A way to handle missing values in a dataframe."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def list_available(df: DataFrame, series: Series) -> list['MVStrategy']:
|
||||||
|
"""Get all the strategies that can be used."""
|
||||||
|
choices = [DropStrategy(), ModeStrategy()]
|
||||||
|
if is_numeric_dtype(series):
|
||||||
|
choices.extend((MeanStrategy(), MedianStrategy(), LinearRegressionStrategy()))
|
||||||
|
return choices
|
||||||
|
|
||||||
|
|
||||||
|
class ScalingStrategy(DataFrameFunction):
|
||||||
|
"""A way to handle missing values in a dataframe."""
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def list_available(df: DataFrame, series: Series) -> list['MVStrategy']:
|
||||||
|
"""Get all the strategies that can be used."""
|
||||||
|
choices = [KeepStrategy()]
|
||||||
|
if is_numeric_dtype(series):
|
||||||
|
choices.extend((MinMaxStrategy(), ZScoreStrategy()))
|
||||||
|
if series.sum() != 0:
|
||||||
|
choices.append(UnitLengthStrategy())
|
||||||
|
return choices
|
||||||
|
|
||||||
|
|
||||||
|
class DropStrategy(MVStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
df.dropna(subset=label, inplace=True)
|
||||||
|
return df
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Drop"
|
||||||
|
|
||||||
|
|
||||||
|
class PositionStrategy(MVStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
series.fillna(self.get_value(series), inplace=True)
|
||||||
|
return df
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_value(self, series: Series) -> Any:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MeanStrategy(PositionStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def get_value(self, series: Series) -> Union[int, float]:
|
||||||
|
return series.mean()
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Use mean"
|
||||||
|
|
||||||
|
|
||||||
|
class MedianStrategy(PositionStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def get_value(self, series: Series) -> Union[int, float]:
|
||||||
|
return series.median()
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Use median"
|
||||||
|
|
||||||
|
|
||||||
|
class ModeStrategy(PositionStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def get_value(self, series: Series) -> Any:
|
||||||
|
return series.mode()[0]
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Use mode"
|
||||||
|
|
||||||
|
|
||||||
|
class LinearRegressionStrategy(MVStrategy):
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
series.interpolate(inplace=True)
|
||||||
|
return df
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Use linear regression"
|
||||||
|
|
||||||
|
|
||||||
|
class KeepStrategy(ScalingStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
return df
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "No-op"
|
||||||
|
|
||||||
|
|
||||||
|
class MinMaxStrategy(ScalingStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
minimum = series.min()
|
||||||
|
maximum = series.max()
|
||||||
|
df[label] = (series - minimum) / (maximum - minimum)
|
||||||
|
return df
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Min-max"
|
||||||
|
|
||||||
|
|
||||||
|
class ZScoreStrategy(ScalingStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
df[label] = (series - series.mean()) / series.std()
|
||||||
|
return df
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Z-Score"
|
||||||
|
|
||||||
|
|
||||||
|
class UnitLengthStrategy(ScalingStrategy):
|
||||||
|
#@typing.override
|
||||||
|
def apply(self, df: DataFrame, label: str, series: Series) -> DataFrame:
|
||||||
|
df[label] = series / series.sum()
|
||||||
|
return df
|
||||||
|
|
||||||
|
def __str__(self) -> str:
|
||||||
|
return "Unit length"
|
32
frontend/pages/normalization.py
Normal file
32
frontend/pages/normalization.py
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
import streamlit as st
|
||||||
|
from normstrategy import MVStrategy, ScalingStrategy
|
||||||
|
|
||||||
|
if "data" in st.session_state:
|
||||||
|
data = st.session_state.original_data
|
||||||
|
st.session_state.original_data = data.copy()
|
||||||
|
|
||||||
|
for column, series in data.items():
|
||||||
|
col1, col2 = st.columns(2)
|
||||||
|
missing_count = series.isna().sum()
|
||||||
|
choices = MVStrategy.list_available(data, series)
|
||||||
|
option = col1.selectbox(
|
||||||
|
f"Missing values of {column} ({missing_count})",
|
||||||
|
choices,
|
||||||
|
index=1,
|
||||||
|
key=f"mv-{column}",
|
||||||
|
)
|
||||||
|
# Always re-get the series to avoid reusing an invalidated series pointer
|
||||||
|
data = option.apply(data, column, data[column])
|
||||||
|
|
||||||
|
choices = ScalingStrategy.list_available(data, series)
|
||||||
|
option = col2.selectbox(
|
||||||
|
"Scaling",
|
||||||
|
choices,
|
||||||
|
key=f"scaling-{column}",
|
||||||
|
)
|
||||||
|
data = option.apply(data, column, data[column])
|
||||||
|
|
||||||
|
st.write(data)
|
||||||
|
st.session_state.data = data
|
||||||
|
else:
|
||||||
|
st.error("file not loaded")
|
64
frontend/pages/prediction_classification.py
Normal file
64
frontend/pages/prediction_classification.py
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
import streamlit as st
|
||||||
|
from sklearn.linear_model import LogisticRegression
|
||||||
|
from sklearn.model_selection import train_test_split
|
||||||
|
from sklearn.metrics import accuracy_score
|
||||||
|
from sklearn.preprocessing import LabelEncoder
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
st.header("Prediction: Classification")
|
||||||
|
|
||||||
|
if "data" in st.session_state:
|
||||||
|
data = st.session_state.data
|
||||||
|
|
||||||
|
with st.form("classification_form"):
|
||||||
|
st.subheader("Classification Parameters")
|
||||||
|
data_name = st.multiselect("Features", data.columns)
|
||||||
|
target_name = st.selectbox("Target", data.columns)
|
||||||
|
test_size = st.slider("Test Size", min_value=0.1, max_value=0.5, value=0.2, step=0.1)
|
||||||
|
st.form_submit_button('Train and Predict')
|
||||||
|
|
||||||
|
if data_name and target_name:
|
||||||
|
X = data[data_name]
|
||||||
|
y = data[target_name]
|
||||||
|
|
||||||
|
label_encoders = {}
|
||||||
|
for column in X.select_dtypes(include=['object']).columns:
|
||||||
|
le = LabelEncoder()
|
||||||
|
X[column] = le.fit_transform(X[column])
|
||||||
|
label_encoders[column] = le
|
||||||
|
|
||||||
|
if y.dtype == 'object':
|
||||||
|
le = LabelEncoder()
|
||||||
|
y = le.fit_transform(y)
|
||||||
|
label_encoders[target_name] = le
|
||||||
|
|
||||||
|
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=42)
|
||||||
|
|
||||||
|
model = LogisticRegression()
|
||||||
|
model.fit(X_train, y_train)
|
||||||
|
y_pred = model.predict(X_test)
|
||||||
|
accuracy = accuracy_score(y_test, y_pred)
|
||||||
|
|
||||||
|
st.subheader("Model Accuracy")
|
||||||
|
st.write(f"Accuracy on test data: {accuracy:.2f}")
|
||||||
|
|
||||||
|
st.subheader("Enter values for prediction")
|
||||||
|
pred_values = []
|
||||||
|
for feature in data_name:
|
||||||
|
if feature in label_encoders:
|
||||||
|
values = list(label_encoders[feature].classes_)
|
||||||
|
value = st.selectbox(f"Value for {feature}", values)
|
||||||
|
value_encoded = label_encoders[feature].transform([value])[0]
|
||||||
|
pred_values.append(value_encoded)
|
||||||
|
else:
|
||||||
|
value = st.number_input(f"Value for {feature}", value=0.0)
|
||||||
|
pred_values.append(value)
|
||||||
|
|
||||||
|
prediction = model.predict(pd.DataFrame([pred_values], columns=data_name))
|
||||||
|
|
||||||
|
if target_name in label_encoders:
|
||||||
|
prediction = label_encoders[target_name].inverse_transform(prediction)
|
||||||
|
|
||||||
|
st.write("Prediction:", prediction[0])
|
||||||
|
else:
|
||||||
|
st.error("File not loaded")
|
29
frontend/pages/prediction_regression.py
Normal file
29
frontend/pages/prediction_regression.py
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import streamlit as st
|
||||||
|
from sklearn.linear_model import LinearRegression
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
st.header("Prediction: Regression")
|
||||||
|
|
||||||
|
if "data" in st.session_state:
|
||||||
|
data = st.session_state.data
|
||||||
|
|
||||||
|
with st.form("regression_form"):
|
||||||
|
st.subheader("Linear Regression Parameters")
|
||||||
|
data_name = st.multiselect("Features", data.select_dtypes(include="number").columns)
|
||||||
|
target_name = st.selectbox("Target", data.select_dtypes(include="number").columns)
|
||||||
|
st.form_submit_button('Train and Predict')
|
||||||
|
|
||||||
|
if data_name and target_name:
|
||||||
|
X = data[data_name]
|
||||||
|
y = data[target_name]
|
||||||
|
|
||||||
|
model = LinearRegression()
|
||||||
|
model.fit(X, y)
|
||||||
|
|
||||||
|
st.subheader("Enter values for prediction")
|
||||||
|
pred_values = [st.number_input(f"Value for {feature}", value=0.0) for feature in data_name]
|
||||||
|
prediction = model.predict(pd.DataFrame([pred_values], columns=data_name))
|
||||||
|
|
||||||
|
st.write("Prediction:", prediction[0])
|
||||||
|
else:
|
||||||
|
st.error("File not loaded")
|
Reference in New Issue
Block a user