5 Commits

Author SHA1 Message Date
6dcca29cbd Rename to original_data 2024-06-19 09:49:16 +02:00
a325603fd9 Add scaling strategies 2024-06-19 09:04:39 +02:00
5f960df838 Support Pandas linear regression 2024-06-07 11:58:52 +02:00
63bce82b3b Implement base MissingValues strategies 2024-06-07 11:00:21 +02:00
Bastien OLLIER
ba1aef5727 Add navigation (#2)
Co-authored-by: bastien ollier <bastien.ollier@etu.uca.fr>
Co-authored-by: clfreville2 <clement.freville2@etu.uca.fr>
Reviewed-on: https://codefirst.iut.uca.fr/git/clement.freville2/miner/pulls/2
Reviewed-by: Clément FRÉVILLE <clement.freville2@etu.uca.fr>
Co-authored-by: Bastien OLLIER <bastien.ollier@noreply.codefirst.iut.uca.fr>
Co-committed-by: Bastien OLLIER <bastien.ollier@noreply.codefirst.iut.uca.fr>
2024-06-07 10:25:37 +02:00
6 changed files with 249 additions and 64 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
__pycache__

48
frontend/exploration.py Normal file
View File

@@ -0,0 +1,48 @@
import pandas as pd
import streamlit as st
st.set_page_config(
page_title="Project Miner",
layout="wide"
)
st.title("Home")
### Exploration
uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
if uploaded_file is not None:
st.session_state.data = pd.read_csv(uploaded_file)
st.session_state.original_data = st.session_state.data
st.success("File loaded successfully!")
if "data" in st.session_state:
data = st.session_state.data
st.write(data.head(10))
st.write(data.tail(10))
st.header("Data Preview")
st.subheader("First 5 Rows")
st.write(data.head())
st.subheader("Last 5 Rows")
st.write(data.tail())
st.header("Data Summary")
st.subheader("Basic Information")
col1, col2 = st.columns(2)
col1.metric("Number of Rows", data.shape[0])
col2.metric("Number of Columns", data.shape[1])
st.write(f"Column Names: {list(data.columns)}")
st.subheader("Missing Values by Column")
missing_values = data.isnull().sum()
st.write(missing_values)
st.subheader("Statistical Summary")
st.write(data.describe())

View File

@@ -1,64 +0,0 @@
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
from pandas.api.types import is_numeric_dtype
st.set_page_config(
page_title="Project Miner",
layout="wide"
)
### Exploration
uploaded_file = st.file_uploader("Upload your CSV file", type=["csv"])
if uploaded_file:
data = pd.read_csv(uploaded_file)
st.success("File loaded successfully!")
st.header("Data Preview")
st.subheader("First 5 Rows")
st.write(data.head())
st.subheader("Last 5 Rows")
st.write(data.tail())
st.header("Data Summary")
st.subheader("Basic Information")
col1, col2 = st.columns(2)
col1.metric("Number of Rows", data.shape[0])
col2.metric("Number of Columns", data.shape[1])
st.write(f"Column Names: {list(data.columns)}")
st.subheader("Missing Values by Column")
missing_values = data.isnull().sum()
st.write(missing_values)
st.subheader("Statistical Summary")
st.write(data.describe())
### Visualization
st.header("Data Visualization")
st.subheader("Histogram")
column_to_plot = st.selectbox("Select Column for Histogram", data.columns)
if column_to_plot:
fig, ax = plt.subplots()
ax.hist(data[column_to_plot].dropna(), bins=20, edgecolor='k')
ax.set_title(f'Histogram of {column_to_plot}')
ax.set_xlabel(column_to_plot)
ax.set_ylabel('Frequency')
st.pyplot(fig)
st.subheader("Boxplot")
dataNumeric = data.select_dtypes(include='number')
column_to_plot = st.selectbox("Select Column for Boxplot", dataNumeric.columns)
if column_to_plot:
fig, ax = plt.subplots()
sns.boxplot(data=data, x=column_to_plot, ax=ax)
ax.set_title(f'Boxplot of {column_to_plot}')
st.pyplot(fig)

138
frontend/normstrategy.py Normal file
View 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"

View 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")

View File

@@ -0,0 +1,30 @@
import streamlit as st
import matplotlib.pyplot as plt
import seaborn as sns
st.header("Data Visualization")
if "data" in st.session_state:
data = st.session_state.data
st.subheader("Histogram")
column_to_plot = st.selectbox("Select Column for Histogram", data.columns)
if column_to_plot:
fig, ax = plt.subplots()
ax.hist(data[column_to_plot].dropna(), bins=20, edgecolor='k')
ax.set_title(f"Histogram of {column_to_plot}")
ax.set_xlabel(column_to_plot)
ax.set_ylabel("Frequency")
st.pyplot(fig)
st.subheader("Boxplot")
dataNumeric = data.select_dtypes(include="number")
column_to_plot = st.selectbox("Select Column for Boxplot", dataNumeric.columns)
if column_to_plot:
fig, ax = plt.subplots()
sns.boxplot(data=data, x=column_to_plot, ax=ax)
ax.set_title(f"Boxplot of {column_to_plot}")
st.pyplot(fig)
else:
st.error("file not loaded")